1 __copyright__ = "Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License"
4 import httplib as httpclient
7 class httpUploadDataStream(object):
8 def __init__(self, progressCallback):
12 self._progressCallback = progressCallback
14 def write(self, data):
19 for n in xrange(0, blocks):
20 self._dataList.append(data[n*2048:n*2048+2048])
21 self._dataList.append(data[blocks*2048:])
22 self._totalLength += size
25 if self._readPos >= len(self._dataList):
27 ret = self._dataList[self._readPos]
29 if self._progressCallback is not None:
30 self._progressCallback(float(self._readPos / len(self._dataList)))
34 return self._totalLength
36 class Youmagine(object):
37 def __init__(self, authToken, progressCallback = None):
38 self._hostUrl = 'api.youmagine.com'
39 self._viewUrl = 'www.youmagine.com'
40 self._authUrl = 'https://www.youmagine.com/integrations/cura/authorized_integrations/new'
41 self._authToken = authToken
45 self._hostReachable = True
46 self._progressCallback = progressCallback
57 ('3D printer parts and enhancements', 11),
61 ('Creative Commons - Attribution Share Alike', 'ccbysa'),
62 ('Creative Commons - Attribution Non-Commercial ShareAlike', 'ccbyncsa'),
63 ('Creative Commons - Attribution No Derivatives', 'ccbynd'),
64 ('Creative Commons - Attribution Non-Commercial No Derivatives', 'ccbyncsa'),
68 def getAuthorizationUrl(self):
71 def getCategories(self):
72 return map(lambda n: n[0], self._categories)
74 def getLicenses(self):
75 return map(lambda n: n[0], self._licenses)
77 def setAuthToken(self, token):
78 self._authToken = token
82 def getAuthToken(self):
83 return self._authToken
85 def isHostReachable(self):
86 return self._hostReachable
88 def viewUrlForDesign(self, id):
89 return 'https://%s/designs/%d' % (self._viewUrl, id)
91 def editUrlForDesign(self, id):
92 return 'https://%s/designs/%d/edit' % (self._viewUrl, id)
94 def isAuthorized(self):
95 if self._authToken is None:
97 if self._userName is None:
98 #No username yet, try to request the username to see if the authToken is valid.
99 result = self._request('GET', '/authorized_integrations/%s/whoami.json' % (self._authToken))
101 if 'error' in result:
102 self._authToken = None
104 self._userName = result['screen_name']
105 self._userID = result['id']
108 def createDesign(self, name, description, category, license):
109 res = self._request('POST', '/designs.json', {'design[name]': name, 'design[excerpt]': description, 'design[design_category_id]': filter(lambda n: n[0] == category, self._categories)[0][1], 'design[license]': filter(lambda n: n[0] == license, self._licenses)[0][1]})
115 def publishDesign(self, id):
116 res = self._request('PUT', '/designs/%d/mark_as/publish.json' % (id), {'ignore': 'me'})
121 def createDocument(self, designId, name, contents):
122 res = self._request('POST', '/designs/%d/documents.json' % (designId), {'document[name]': name, 'document[description]': 'Uploaded from Cura'}, {'document[file]': (name, contents)})
128 def createImage(self, designId, name, contents):
129 res = self._request('POST', '/designs/%d/images.json' % (designId), {'image[name]': name, 'image[description]': 'Uploaded from Cura'}, {'image[file]': (name, contents)})
135 def listDesigns(self):
136 res = self._request('GET', '/users/%s/designs.json' % (self._userID))
139 def _request(self, method, url, postData = None, files = None):
141 if self._authToken is not None:
142 url += '?auth_token=%s' % (self._authToken)
143 error = 'Failed to connect to %s' % self._hostUrl
144 for n in xrange(0, retryCount):
145 if self._http is None:
146 self._http = httpclient.HTTPSConnection(self._hostUrl)
148 if files is not None:
149 boundary = 'wL36Yn8afVp8Ag7AmP8qZ0SA4n1v9T'
150 s = httpUploadDataStream(self._progressCallback)
151 for k, v in files.iteritems():
154 s.write('--%s\r\n' % (boundary))
155 s.write('Content-Disposition: form-data; name="%s"; filename="%s"\r\n' % (k, filename))
156 s.write('Content-Type: application/octet-stream\r\n')
157 s.write('Content-Transfer-Encoding: binary\r\n')
159 s.write(fileContents)
162 for k, v in postData.iteritems():
163 s.write('--%s\r\n' % (boundary))
164 s.write('Content-Disposition: form-data; name="%s"\r\n' % (k))
168 s.write('--%s--\r\n' % (boundary))
170 self._http.request(method, url, s, {"Content-type": "multipart/form-data; boundary=%s" % (boundary), "Content-Length": len(s)})
171 elif postData is not None:
172 self._http.request(method, url, urllib.urlencode(postData), {"Content-type": "application/x-www-form-urlencoded"})
174 self._http.request(method, url)
179 response = self._http.getresponse()
180 responseText = response.read()
185 if responseText == '':
187 return json.loads(responseText)
189 print response.getheaders()
191 error = 'Failed to decode JSON response'
192 self._hostReachable = False
193 return {'error': error}
196 #Fake Youmagine class to test without internet
197 class FakeYoumagine(Youmagine):
198 def __init__(self, authToken, callback):
199 super(FakeYoumagine, self).__init__(authToken)
200 self._authUrl = 'file:///C:/Models/output.html'
201 self._authToken = None
203 def isAuthorized(self):
204 if self._authToken is None:
206 if self._userName is None:
207 self._userName = 'FakeYoumagine'
211 def isHostReachable(self):
214 def createDesign(self, name, description, category, license):
217 def publishDesign(self, id):
220 def createDocument(self, designId, name, contents):
221 print "Create document: %s" % (name)
222 f = open("C:/models/%s" % (name), "wb")
227 def createImage(self, designId, name, contents):
228 print "Create image: %s" % (name)
229 f = open("C:/models/%s" % (name), "wb")
234 def listDesigns(self):
237 def _request(self, method, url, postData = None, files = None):
238 print "Err: Tried to do request: %s %s" % (method, url)