-
Notifications
You must be signed in to change notification settings - Fork 19
/
forge_da.py
406 lines (355 loc) · 17.8 KB
/
forge_da.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
#####################################################################
## Copyright (c) Autodesk, Inc. All rights reserved
## Written by Forge Partner Development
##
## Permission to use, copy, modify, and distribute this software in
## object code form for any purpose and without fee is hereby granted,
## provided that the above copyright notice appears in all copies and
## that both that copyright notice and the limited warranty and
## restricted rights notice below appear in all supporting
## documentation.
##
## AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
## AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
## MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
## DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
## UNINTERRUPTED OR ERROR FREE.
#####################################################################
import os
import sys
import requests
import argparse
import re
import json
import base64
import datetime
from pathlib import Path
import six
import urllib
import hashlib, hmac
import boto3
config = __import__('config')
utility = __import__('utility')
Forge_CLIENT_ID = config.Forge_CLIENT_ID
Forge_CLIENT_SECRET = config.Forge_CLIENT_SECRET
Forge_BASE_URL = config.Forge_BASE_URL
DA_BASE_URL = config.DA_BASE_URL
APP_BUNDDLE_URL = config.APP_BUNDDLE_URL
def getToken():
"""Obtain Forge token given a client id & secret"""
req = { 'client_id' : Forge_CLIENT_ID, 'client_secret': Forge_CLIENT_SECRET, 'grant_type' : 'client_credentials','scope':'code:all bucket:create bucket:read data:read data:write'}
resp = requests.post(Forge_BASE_URL+'/authentication/v1/authenticate', req)
if resp.status_code == 200:
config.token = resp.json()['token_type'] + " " + resp.json()['access_token']
return config.token
else:
print('Get Token Failed! status = {0} ; message = {1}'.format(resp.status_code,resp.text) )
return None
def getNickName():
resp = requests.get(Forge_BASE_URL+DA_BASE_URL+'/forgeapps/me', headers={'Authorization': config.token})
if resp.status_code == 200:
return resp.json()
else:
print('Get Nick Name of Design Automation Failed! status = {0} ; message = {1}'.format(resp.status_code,resp.text ) )
return None
def deleteNickName(name):
resp = requests.delete(Forge_BASE_URL+DA_BASE_URL+'/forgeapps/me', headers={'Authorization': config.token})
if resp.status_code == 200:
return resp.text
else:
print('Delete Nick Name of Design Automation Failed! status = {0} ; message = {1}'.format(resp.status_code,resp.text ) )
return None
def setNickName(name):
resp = requests.patch(Forge_BASE_URL+DA_BASE_URL+'/forgeapps/me', headers={'Authorization': config.token},json={"nickname": name})
if resp.status_code == 200:
return resp.text
else:
print('Set Nick Name of Design Automation Failed! status = {0} ; message = {1}'.format(resp.status_code,resp.text ) )
return None
def dumpEngines():
#now /engines endpoint returns engines in pages, so dump all engines page by page
pageToken = None
resp = requests.get(Forge_BASE_URL+DA_BASE_URL+'/engines', headers={'Authorization': config.token})
if(resp.status_code==200):
engines = resp.json()['data']
while(resp.json()['paginationToken']!=''):
pageToken = resp.json()['paginationToken']
engines.extend(resp.json()['data'])
resp = requests.get(Forge_BASE_URL+DA_BASE_URL+'/engines?page='+str(pageToken), headers={'Authorization': config.token})
if(resp.status_code!=200):
print('Get Engines of Design Automation Failed in one page! status ={0} ; message = {1}'.format(resp.status_code,resp.text ) )
return engines
return engines
else:
print('Get Engines of Design Automation Failed! status ={0} ; message = {1}'.format(resp.status_code,resp.text ) )
return None
def getEngineAttributes(engine):
data = {}
if re.search('3dsMax', engine, re.IGNORECASE):
data['commandLine'] = "$(engine.path)\\3dsmaxbatch.exe -sceneFile \"$(args[inputFile].path)\" \"$(settings[script].path)\""
data['extension'] = "max"
data['script'] = "da = dotNetClass(\"Autodesk.Forge.Sample.DesignAutomation.Max.RuntimeExecute\")\nda.ModifyWindowWidthHeight()\n"
if re.search('AutoCAD', engine, re.IGNORECASE):
data['commandLine'] = "$(engine.path)\\accoreconsole.exe /i \"$(args[inputFile].path)\" /al \"$(appbundles[{0}].path)\" /s \"$(settings[script].path)\""
data['extension'] = "dwg"
data['script'] = "UpdateParam\n"
if re.search('Inventor', engine, re.IGNORECASE):
data['commandLine'] = "$(engine.path)\\InventorCoreConsole.exe /i \"$(args[inputFile].path)\" /al \"$(appbundles[{0}].path)\""
data['extension'] = "ipt"
data['script'] = ""
if re.search('Revit', engine, re.IGNORECASE):
data['commandLine'] = "$(engine.path)\\revitcoreconsole.exe /i \"$(args[inputFile].path)\" /al \"$(appbundles[{0}].path)\""
data['extension'] = "rvt"
data['script'] = ""
return data
def getDefinedAppbundles():
resp = requests.get(Forge_BASE_URL+DA_BASE_URL+'/appbundles', headers={'Authorization': config.token})
if resp.status_code == 200:
return resp.json()['data']
else:
print('Get Appbundles of Design Automation Failed! status ={0} ; message = {1}'.format(resp.status_code,resp.text ) )
return None
#####
# Define a new appbundle
####
def createAppBundle(enginename,appname):
#engineAttributes = getEngineAttributes(enginename)
#commandLine = engineAttributes['commandLine'].format(appname)
appBundleSpec = {}
appBundleSpec['id'] = appname
appBundleSpec['engine'] = enginename
appBundleSpec['description'] = 'Description for {0}'.format(appname)
resp = requests.post(Forge_BASE_URL+DA_BASE_URL+'/appbundles', headers={'Authorization': config.token},json=appBundleSpec)
if resp.status_code == 200:
return resp.json()
else:
print('Create AppBundle of Design Automation Failed! status ={0} ; message = {1}'.format(resp.status_code,resp.text ) )
return None
#####
# create a new appbundle version
####
def createAppBundleVersion(enginename,appname):
#engineAttributes = getEngineAttributes(enginename)
#commandLine = engineAttributes['commandLine'].format(appname)
appBundleSpec = {}
appBundleSpec['engine'] = enginename
appBundleSpec['description'] = 'Description for {0}'.format(appname)
resp = requests.post(Forge_BASE_URL+DA_BASE_URL+'/appbundles/'+appname+'/versions', headers={'Authorization': config.token},json=appBundleSpec)
if resp.status_code == 200:
return resp.json()
else:
print('Create AppBundle of Design Automation Failed! status ={0} ; message = {1}'.format(resp.status_code,resp.text ) )
return None
####
# Create appbundle alias
###
def createAppBundleAlias(appname,alias,version):
aliasSpec ={'version':version,'id':alias}
resp = requests.post(Forge_BASE_URL+DA_BASE_URL+'/appbundles/'+appname+'/aliases', headers={'Authorization': config.token},json=aliasSpec)
if resp.status_code == 200:
return resp.json()
else:
print('Create AppBundle Alias of Design Automation Failed! status ={0} ; message = {1}'.format(resp.status_code,resp.text ) )
return None
####
# Update appbundle alias
###
def updateAppBundleAlias(appname,alias,version):
aliasSpec ={'version':version}
resp = requests.patch(Forge_BASE_URL+DA_BASE_URL+'/appbundles/'+appname+'/aliases/'+alias, headers={'Authorization': config.token},json=aliasSpec)
if resp.status_code == 200:
return resp.json()
else:
print('Create AppBundle Alias of Design Automation Failed! status ={0} ; message = {1}'.format(resp.status_code,resp.text ) )
return None
def uploadZip(appPackagePath,appname,zipname,appFormData):
my_file = Path(appPackagePath + zipname)
#the package file (*.zip) exists
if my_file.is_file():
if sys.version_info[0] < 3:
payload = appFormData
files = {'file': open(appPackagePath + zipname,'rb')}
resp = requests.post(APP_BUNDDLE_URL,files=files, data=payload)
else:
appFormData['file'] = (zipname,open(appPackagePath + zipname,'rb'))
resp = requests.post(APP_BUNDDLE_URL,files=appFormData)
if resp.status_code == 200:
return resp.text
else:
print('UploadZip of Design Automation Failed! status ={0} ; message = {1}'.format(resp.status_code,resp.text ) )
return None
else:
print(' ' + zipname + ' does not exist')
return None
def getDefinedActivities():
resp = requests.get(Forge_BASE_URL+DA_BASE_URL+'/activities', headers={'Authorization': config.token})
if resp.status_code == 200:
return resp.json()['data']
else:
print('Get Activities of Design Automation = {0} ; message = {1}'.format(resp.status_code,resp.text ) )
return None
#####
# Define a new activity
####
def createActivity(enginename,appname,qualifiedAppBundleId,actname):
engineAttributes = getEngineAttributes(enginename)
commandLine = engineAttributes['commandLine'].format(appname)
activitySpec = {}
activitySpec['id'] = actname
activitySpec['engine'] = enginename
activitySpec['commandLine'] = [commandLine]
activitySpec['appbundles'] = [qualifiedAppBundleId]
activitySpec['description'] = 'Description for {0}'.format(actname)
activitySpec['Parameters'] = {}
activitySpec['Parameters']["inputFile"] = {"verb":"get","description":"","localName":"$(inputFile)","zip":False,"ondemand":False}
activitySpec['Parameters']["inputJson"] = {"verb":"get","description":"","localName":"params.json","zip":False,"ondemand":False}
activitySpec['Parameters']["outputFile"] = {"verb":"put","description":"","localName":"outputFile." + engineAttributes["extension"],"zip":False,"ondemand":False,"required":True}
activitySpec['Settings'] ={}
activitySpec['Settings']["script"] ={"Value":engineAttributes["script"]}
resp = requests.post(Forge_BASE_URL+DA_BASE_URL+'/activities', headers={'Authorization': config.token},json=activitySpec)
if resp.status_code == 200:
return resp.json()
else:
print('Create Activity of Design Automation Failed! status ={0} ; message = {1}'.format(resp.status_code,resp.text ) )
return None
####
# Create activity alias
###
def createActivityAlias(actname,alias):
aliasSpec ={'version':1,'id':alias}
resp = requests.post(Forge_BASE_URL+DA_BASE_URL+'/activities/'+actname+'/aliases', headers={'Authorization': config.token},json=aliasSpec)
if resp.status_code == 200:
return resp.json()
else:
print('Create Activity Alias of Design Automation Failed! status ={0} ; message = {1}'.format(resp.status_code,resp.text ) )
return None
####
# Create Bucket
###
def createBucket(bucketname):
payload = {'bucketKey' : bucketname,'policyKey' : 'transient'}
resp = requests.post(Forge_BASE_URL+'/oss/v2/buckets', headers={'Authorization': config.token,'Content-Type':'application/json'},json=payload)
if resp.status_code == 200 or resp.status_code == 409:
return resp.json()
else:
print('Create Bucket of Data Management Failed! status ={0} ; message = {1}'.format(resp.status_code,resp.text ) )
return None
####
# Upload Source File to Bucket
###
def uploadFileToBucket(modelfilePath,bucketname,filename):
my_file = Path(modelfilePath + filename)
#check package file (*.zip) exists
if my_file.is_file():
filesize = os.path.getsize( modelfilePath + filename )
# encoding the file name
if sys.version_info[0] < 3:
encodedfilename= urllib.pathname2url(filename)
else:
encodedfilename= urllib.parse.quote(filename)
resp = requests.put(Forge_BASE_URL+'/oss/v2/buckets/'+bucketname+'/objects/'+encodedfilename, headers={'Authorization': config.token,'Content-Type' : 'application/octet-stream','Content-Length' : str(filesize)},data= open(modelfilePath + filename, 'rb'))
if resp.status_code == 200:
return resp.json()
else:
print('Upload File to Bucket of Data Management Failed! status ={0} ; message = {1}'.format(resp.status_code,resp.text ) )
return None
else:
print(' ' + filename + ' does not exist')
return None
####
# Create WorkItem
###
def createWorkItem(qualifiedActivityId,param):
workItemSpec = {}
workItemSpec['activityId'] = qualifiedActivityId
workItemSpec['arguments'] = {}
inputFileArgument = {}
inputFileArgument['url'] = "https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}".format(param['bucketKey'],param['inputFileNameOSS'])
inputFileArgument['headers'] = {}
inputFileArgument['headers']['Authorization'] = config.token
inputJsonArgument = {}
inputJsonArgument['url'] = 'data:application/json,'+ str(param['jsonInput'])
dateStr = str(datetime.datetime.now())
dateStr = dateStr.replace(':','.') ### : is not accepted as file name
outputFileNameOSS = '{0}_output_{1}'.format(dateStr,param['inputFileNameOSS'])
ossOutputUrl = "https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}".format(param['bucketKey'],outputFileNameOSS)
outputFileArgument = {}
outputFileArgument['url'] = ossOutputUrl
outputFileArgument['headers'] = {}
outputFileArgument['headers']['Authorization'] = config.token
outputFileArgument['verb'] = 'put'
workItemSpec['arguments']['inputFile'] = inputFileArgument
workItemSpec['arguments']['inputJson'] = inputJsonArgument
workItemSpec['arguments']['outputFile'] = outputFileArgument
resp = requests.post(Forge_BASE_URL+DA_BASE_URL+'/workitems', headers={'Authorization': config.token},json=workItemSpec)
if resp.status_code == 200:
copyResJson = resp.json()
#for download the output file. append two elements of json
copyResJson['outputFileNameOSS'] = outputFileNameOSS
copyResJson['ossOutputUrl'] = ossOutputUrl
return copyResJson
else:
print('Create WorkItem of Design Automation Failed! status ={0} ; message = {1}'.format(resp.status_code,resp.text ) )
return None
def getWorkItemStatus(wid):
resp = requests.get(Forge_BASE_URL+DA_BASE_URL+'/workitems/'+wid , headers={'Authorization': config.token})
if resp.status_code == 200:
return resp.json()
else:
print('Get WorkItem Status of Design Automation = {0} ; message = {1}'.format(resp.status_code,resp.text ) )
return None
##other user scenarios ###
## output to personal AWS bucket
def createWorkItem_outputPersonalAWSBucket(qualifiedActivityId,inputparam):
#prepare input parameters of Forge DA
workItemSpec = {}
workItemSpec['activityId'] = qualifiedActivityId
workItemSpec['arguments'] = {}
inputFileArgument = {}
inputFileArgument['url'] = "https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}".format(inputparam['bucketKey'],inputparam['inputFileNameOSS'])
inputFileArgument['headers'] = {}
inputFileArgument['headers']['Authorization'] = config.token
inputJsonArgument = {}
inputJsonArgument['url'] = 'data:application/json,'+ str(inputparam['jsonInput'])
#prepare output parameters of Forge DA (for personal AWS bucket)
dateStr = str(datetime.datetime.now())
dateStr = dateStr.replace(':','.') ### : is not accepted as file name
outputFileNameOSS = '{0}_output_{1}'.format(dateStr,inputparam['inputFileNameOSS'])
#Begin: generate AWS credentials
#check key, secret, token..
if config.Personal_AWS_Key is None or config.Personal_AWS_Secret is None or config.Personal_AWS_Token is None:
print('No AWS key / secret / token is available.')
return None
#get aws credentials by Boto3
s3_client = boto3.client('s3',aws_access_key_id=config.Personal_AWS_Key,aws_secret_access_key=config.Personal_AWS_Secret, aws_session_token=config.Personal_AWS_Token)
if s3_client==None:
print("S3 client is none...")
return None
#call generate_presigned_post of Boto3 to get upload url and fields params
signed_parts = s3_client.generate_presigned_post(Bucket=config.Personal_AWS_Bucket_Key,Key=outputFileNameOSS)
print('---signed_parts----\n{0}'.format(signed_parts))
signed_url = signed_parts['url']
awsOutputUrl = signed_url
outputFileArgument = {}
outputFileArgument['verb'] = 'post'
outputFileArgument['url'] = awsOutputUrl
outputFileArgument['multiparts'] = {}
outputFileArgument['multiparts']['key'] = outputFileNameOSS
outputFileArgument['multiparts']['AWSAccessKeyId'] = signed_parts['fields']['AWSAccessKeyId'] #the same to config.Personal_AWS_Key
outputFileArgument['multiparts']['x-amz-security-token'] = signed_parts['fields']['x-amz-security-token']
outputFileArgument['multiparts']['policy'] = signed_parts['fields']['policy']
outputFileArgument['multiparts']['signature'] = signed_parts['fields']['signature']
##End generate AWS credentials #######
workItemSpec['arguments']['inputFile'] = inputFileArgument
workItemSpec['arguments']['inputJson'] = inputJsonArgument
workItemSpec['arguments']['outputFile'] = outputFileArgument
resp = requests.post(Forge_BASE_URL+DA_BASE_URL+'/workitems', headers={'Authorization': config.token},json=workItemSpec)
if resp.status_code == 200:
copyResJson = resp.json()
#for download the output file. append elements of json
copyResJson['outputFileNameOSS'] = outputFileNameOSS
return copyResJson
else:
print('Create WorkItem of Design Automation, output to personal AWS bucket Failed! status ={0} ; message = {1}'.format(resp.status_code,resp.text ) )
return None
#####