~etc-pgh-launchpad/wildpockets/trunk

« back to all changes in this revision

Viewing changes to resourceserver/submitResource.py

  • Committer: etc-pgh-launchpad at cmu
  • Date: 2010-11-30 20:56:30 UTC
  • Revision ID: etc-pgh-launchpad@lists.andrew.cmu.edu-20101130205630-0blbkcz28ovjl8wj
Committing the Wild Pockets code base to Launchpad.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/python
 
2
"""
 
3
Wild Pockets
 
4
 
 
5
Copyright (c) 2010 Carnegie Mellon University
 
6
 
 
7
Permission is hereby granted, free of charge, to any person obtaining a copy
 
8
of this software and associated documentation files (the "Software"), to deal
 
9
in the Software without restriction, including without limitation the rights
 
10
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 
11
copies of the Software, and to permit persons to whom the Software is
 
12
furnished to do so, subject to the following conditions:
 
13
 
 
14
The above copyright notice and this permission notice shall be included in
 
15
all copies or substantial portions of the Software.
 
16
 
 
17
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 
18
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 
19
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 
20
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 
21
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 
22
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 
23
THE SOFTWARE.
 
24
 
 
25
"""
 
26
 
 
27
 
 
28
import os,urllib,getopt,traceback,sys,os
 
29
"""
 
30
Stores a resource to the server. Entrypoint for the uploader tool
 
31
"""
 
32
 
 
33
import sys
 
34
import libs.auth as auth
 
35
import libs.filenames as filenames
 
36
import libs.save as save
 
37
import libs.protocol as protocolmodule
 
38
##import libs.modelexporter.fileparser as fileparser
 
39
##import libs.modelexporter.model as model
 
40
##import libs.modelexporter.modelExporter as modelExporter
 
41
##import libs.modelexporter.animation as animation
 
42
##import libs.modelexporter.animexporter as animexporter
 
43
##import libs.modelexporter.tokens as tokens
 
44
 
 
45
 
 
46
 
 
47
class AuthenticationError(Exception):
 
48
    def __init__(self,value):
 
49
        self.value=value
 
50
    def __str__(self):
 
51
        return repr(self.value)
 
52
 
 
53
def applyCommands(parser,myImporter):
 
54
    """
 
55
    Applies the commands in the parser to a model
 
56
 
 
57
    To apply commands, the first token in the command is assumed
 
58
    to be the command name. A function with that name is called in model;
 
59
    the remaining parsed tokens are arguments to that function
 
60
    """
 
61
    global importer
 
62
 
 
63
    try:
 
64
        while True:
 
65
            cmd=parser.nextCommand()
 
66
            if cmd==None:
 
67
                return
 
68
            if cmd[0][0]=="_":
 
69
                raise importer.ImporterError("Invalid command "+cmd[0])
 
70
            getattr(myImporter,cmd[0])(*(cmd[1:]))
 
71
    except (importer.ImporterError,Exception),e:
 
72
        raise Exception("Error on line "+str(parser.getCurrentLine())+": "+str(e))
 
73
 
 
74
def convertFile(username,filename,filetype,keywords,version,inputFile):
 
75
    try:
 
76
        version=int(version)
 
77
 
 
78
        # load the libraries
 
79
        libName="libs.modelexporter"+str(version)
 
80
 
 
81
        global fileparser    
 
82
        global model         
 
83
        global modelExporter 
 
84
        global animation     
 
85
        global animexporter  
 
86
        global tokens
 
87
        global importer
 
88
 
 
89
        fileparser    = __import__(libName+".fileparser",globals(),locals(),["*"])
 
90
        model         = __import__(libName+".model",globals(),locals(),["*"])
 
91
        modelExporter = __import__(libName+".modelExporter",globals(),locals(),["*"])
 
92
        animation     = __import__(libName+".animation",globals(),locals(),["*"])
 
93
        animexporter  = __import__(libName+".animexporter",globals(),locals(),["*"])
 
94
        tokens        = __import__(libName+".tokens",globals(),locals(),["*"])
 
95
        importer      = __import__(libName+".importer",globals(),locals(),["*"])
 
96
        
 
97
        
 
98
    except Exception,e:
 
99
        CgiError("Error while loading handler for resource version '"+str(version)+"':\n"+str(e))
 
100
 
 
101
    parser=fileparser.FileParser(inputFile)
 
102
 
 
103
    importsystem=None
 
104
    outputter=None
 
105
    try:
 
106
        if filetype=="model":
 
107
            importsystem=model.Model()
 
108
            outputter=modelExporter.ModelExporter()
 
109
        elif filetype=="animation":
 
110
            importsystem=animation.Animation()
 
111
            outputter=animexporter.AnimExporter()
 
112
        else:
 
113
            raise Exception("Unknown resource type '"+filetype+"'")
 
114
    except SystemExit:
 
115
        raise
 
116
    except Exception,e:
 
117
        raise Exception("Error while determining resource type: "+str(e))
 
118
    
 
119
    applyCommands(parser,importsystem)
 
120
    outstream=outputter.output(importsystem)
 
121
    upload(username,filename,keywords,outstream)
 
122
 
 
123
def upload(username,filename,keywords,binaryOutput):
 
124
    """
 
125
    Uploads the raw output to the server
 
126
    """
 
127
    
 
128
    result=save.doSaveResource(username,filename,datastream=binaryOutput,keywords=keywords,isCgi=False)
 
129
    
 
130
    if result is not None:
 
131
        CgiSuccess("Resource uploaded.\n"+result)
 
132
    else:
 
133
        CgiError("Resource failed to be uploaded.")
 
134
    
 
135
def CgiError(errorString):
 
136
    print 'Content-Type: text/plain'
 
137
    print ''
 
138
    print 'FAIL'
 
139
    print errorString
 
140
    sys.exit(0)
 
141
 
 
142
def CgiSuccess(report):
 
143
    print 'Content-Type: text/plain'
 
144
    print ''
 
145
    print 'SUCCESS'
 
146
    print report
 
147
    sys.exit(0)
 
148
 
 
149
 
 
150
def consoleError(errorString):
 
151
    print "ERROR: "
 
152
    print errorString
 
153
    sys.exit(2)
 
154
 
 
155
def consoleSuccess(report):
 
156
    print report
 
157
    sys.exit(0)
 
158
 
 
159
 
 
160
def processCgi(queryString):
 
161
    """
 
162
    Processes arguments provided as a query string
 
163
    """
 
164
    rawQuery=queryString.split('&')
 
165
    query={}
 
166
    for pair in rawQuery:
 
167
        key,value=pair.split("=")
 
168
        query[key]=value
 
169
 
 
170
    protocol = 0
 
171
    try:
 
172
        protocol = int(query['protocol'])
 
173
    except Exception:
 
174
        pass
 
175
    if (protocol < 2):
 
176
        CgiError("This exporter has been replaced, please download the new exporter")
 
177
        
 
178
    rsprot = 0
 
179
    try:
 
180
        rsprot = int(query['rsprot'])
 
181
    except Exception:
 
182
        pass
 
183
    protocolmodule.rsprot = rsprot
 
184
 
 
185
    if 'user' in query:
 
186
        username=urllib.unquote(query['user'])
 
187
    else:
 
188
        CgiError("No username specified")
 
189
        
 
190
    if 'filename' in query:
 
191
        filename=urllib.unquote(query['filename'])
 
192
    else:
 
193
        CgiError("No filename specified")
 
194
        
 
195
    if not filenames.validateFilename(filename):
 
196
        CgiError("Invalid filename")
 
197
 
 
198
    if 'filetype' in query:
 
199
        filetype=urllib.unquote(query['filetype'])
 
200
    else:
 
201
        CgiError("No filetype specified")
 
202
        
 
203
    if 'keywords' in query:
 
204
        keywords=urllib.unquote(query['keywords']).split(" ")
 
205
    else:
 
206
        keywords=[]
 
207
 
 
208
    if 'protocol' in query:
 
209
        version=urllib.unquote(query['protocol'])
 
210
    else:
 
211
        CgiError("No uploader version specified.")
 
212
 
 
213
    req = auth.AuthenticationRequest(query=query)
 
214
    req.requestWriteAccess(filename)
 
215
    req.perform()
 
216
    if not req.haveAccess():
 
217
        CgiError("Access denied")
 
218
 
 
219
    try:
 
220
        convertFile(username, filename, filetype, keywords, version, sys.stdin)
 
221
    except SystemExit,e:
 
222
        raise
 
223
    except Exception,e:
 
224
        errString=traceback.format_exc()
 
225
        CgiError(errString)    
 
226
    
 
227
def processCommandLine(cmdline):
 
228
    """
 
229
    Handles commands coming in from the command line
 
230
    """
 
231
    optlist,args=getopt.getopt(cmdline,"u:p:f:t:k:")
 
232
 
 
233
    username=None
 
234
    authtoken=""
 
235
    filename=None
 
236
    filetype="model"
 
237
    keywords=[]
 
238
 
 
239
    if len(args)==0:
 
240
        consoleError("No file specified for upload")
 
241
 
 
242
    for o,a in optlist:
 
243
        if o=="-u":
 
244
            username=a
 
245
        elif o=="-p":
 
246
            authtoken=a
 
247
        elif o=="-f":
 
248
            filename=a
 
249
        elif o=="-t":
 
250
            filetype=a
 
251
        elif o=="-k":
 
252
            keywords += a
 
253
 
 
254
    if username==None:
 
255
        consoleError("No username specified.")
 
256
    if filename==None:
 
257
        consoleError("No file name specified.")
 
258
 
 
259
    if not filenames.validateFilename(filename):
 
260
        CgiError("Invalid filename")
 
261
        
 
262
    req = auth.AuthenticationRequest(query={'authservice':'wpwebp', 'user':username, 'password':authtoken})
 
263
 
 
264
    req.requestWriteAccess(filename)
 
265
    req.perform()
 
266
    if not req.haveAccess():
 
267
        CgiError("Access denied")
 
268
        
 
269
    try:
 
270
        convertFile(username, filename, filetype, keywords, 3,file(args[0]))
 
271
    except SystemExit:
 
272
        raise
 
273
    except Exception,e:
 
274
        errString=traceback.format_exc()
 
275
        consoleError(errString)
 
276
    consoleSuccess("Model uploaded.")
 
277
 
 
278
alternateErrorHandler = CgiError
 
279
if __name__=="__main__":
 
280
    if 'QUERY_STRING' in os.environ:
 
281
        processCgi(os.environ['QUERY_STRING'])
 
282
    else:
 
283
        processCommandLine(sys.argv[1:])