-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
1567 lines (1307 loc) · 57.6 KB
/
main.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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
try:
import ujson as json
except ImportError:
import json
import logging
import logging.handlers
import os
import re
from datetime import date
import pandas as pd
import requests
from dotenv import load_dotenv
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logger_file_handler = logging.handlers.RotatingFileHandler(
"status.log",
maxBytes=1024 * 1024,
backupCount=1,
encoding="utf8",
)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
logger_file_handler.setFormatter(formatter)
logger.addHandler(logger_file_handler)
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)
load_dotenv() # take environment variables from .env.
try:
CLIENT_ID = os.environ.get("CLIENT_ID")
CLIENT_SECRET = os.environ.get("CLIENT_SECRET")
if not CLIENT_ID or not CLIENT_SECRET:
raise KeyError
except KeyError:
logger.error("CLIENT_ID or CLIENT_SECRET not available!")
exit(1)
# Wrapper
class GenericWrapper:
def __init__(self, wrapped):
self.wrapped = wrapped
# Fallback lookup for undefined methods
def __getattr__(self, name):
return getattr(self.wrapped, name)
# Comments
#!/bin/python
# coding: utf-8
##########################################################################################################################################
# For templating
# The parser
# For templating
# from jsonspec.pointer import extract, ExtractError
##########################################################################################################################################
# Comments
COMMENT_PREFIX = ("#", ";", "//")
MULTILINE_START = "/*"
MULTILINE_END = "*/"
# Data strings
LONG_STRING = '"""'
# JSON Pointer template
TEMPLATE_RE = re.compile(r"\{\{(.*?)\}\}")
##########################################################################################################################################
class JsonComment(GenericWrapper):
def __init__(self, wrapped=json):
super().__init__(wrapped)
# Loads a JSON string with comments
# Allows to expand the JSON Pointer templates
def loads(self, jsonsc, *args, template=True, **kwargs):
# Splits the string in lines
lines = jsonsc.splitlines()
# Process the lines to remove commented ones
jsons = self._preprocess(lines)
# Calls the wrapped to parse JSON
self.obj = self.wrapped.loads(jsons, *args, **kwargs)
# If there are templates, subs them
if template:
self._templatesub(self.obj)
return self.obj
# Loads a JSON opened file with comments
def load(self, jsonf, *args, **kwargs):
# Reads a text file as a string
# Process the readed JSON string
return self.loads(jsonf.read(), *args, **kwargs)
# Opens a JSON file with comments
# Allows a default value if loading or parsing fails
def loadf(self, path, *args, default=None, **kwargs):
# Preparing the default
json_obj = default
# Opening file in append+read mode
# Allows creation of empty file if non-existent
with open(path, mode="a+", encoding="UTF-8") as jsonf:
try:
# Back to file start
jsonf.seek(0)
# Parse and load the JSON
json_obj = self.load(jsonf, *args, **kwargs)
# If fails, default value is kept
except ValueError:
pass
return json_obj
# Saves a JSON file with indentation
def dumpf(
self, json_obj, path, *args, indent=4, escape_forward_slashes=False, **kwargs
):
# Opening file in write mode
with open(path, mode="w", encoding="UTF-8") as jsonf:
# Dumping the object
# Keyword escape_forward_slashes is only for ujson, standard json raises an exception for unknown keyword
# In that case, the method is called again without it
try:
json.dump(
json_obj,
jsonf,
*args,
indent=indent,
escape_forward_slashes=escape_forward_slashes,
**kwargs,
)
except TypeError:
json.dump(json_obj, jsonf, *args, indent=indent, **kwargs)
# Reads lines and skips comments
def _preprocess(self, lines):
standard_json = ""
is_multiline = False
keep_trail_space = 0
for line in lines:
# 0 if there is no trailing space
# 1 otherwise
keep_trail_space = int(line.endswith(" "))
# Remove all whitespace on both sides
line = line.strip()
# Skip blank lines
if len(line) == 0:
continue
# Skip single line comments
if line.startswith(COMMENT_PREFIX):
continue
# Mark the start of a multiline comment
# Not skipping, to identify single line comments using multiline comment tokens, like
# /***** Comment *****/
if line.startswith(MULTILINE_START):
is_multiline = True
# Skip a line of multiline comments
if is_multiline:
# Mark the end of a multiline comment
if line.endswith(MULTILINE_END):
is_multiline = False
continue
# Replace the multi line data token to the JSON valid one
if LONG_STRING in line:
line = line.replace(LONG_STRING, '"')
standard_json += line + " " * keep_trail_space
# Removing non-standard trailing commas
standard_json = standard_json.replace(",]", "]")
standard_json = standard_json.replace(",}", "}")
return standard_json
# Walks the json object and subs template strings with pointed value
def _templatesub(self, obj):
# Gets items for iterables
if isinstance(obj, dict):
items = obj.items()
elif isinstance(obj, list):
items = enumerate(obj)
else:
items = None
# Walks the iterable
for key, subobj in items:
# If subobj is another iterable, call this method again
if isinstance(subobj, (dict, list)):
self._templatesub(subobj)
# If is a string:
# - Find all matches to the template
# - For each match, get through JSON Pointer the value, which must be a string
# - Substitute each match to the pointed value, or ""
# - The string with all templates substitued is written back to the parent obj
elif isinstance(subobj, str):
obj[key] = TEMPLATE_RE.sub(self._repl_getvalue, subobj)
# Replacement function
# The match has the JSON Pointer
def _repl_getvalue(self, match):
try:
# Extracts the pointed value from the root object
value = extract(self.obj, match[1])
# If it's not a string, it's not valid
if not isinstance(value, str):
raise ValueError("Not a string: {}".format(value))
except (ExtractError, ValueError) as e:
# Sets value to empty string
value = ""
logger.info(e)
return value
##########################################################################################################################################
# from jsoncomment import JsonComment
from collections import defaultdict
def jsonParser(text):
"""
Get parse string to json.
return: converted_Jsontext
"""
parser = JsonComment(json)
converted_Jsontext = parser.loads(text)
return converted_Jsontext
def groupFormDataDetails(list_formDataInstances):
groupLists_formDataInstances = defaultdict(list)
for formDataInstance in list_formDataInstances:
# logger.info(formDataInstance)
# break
groupLists_formDataInstances[formDataInstance["formData"]["type"]].append(
formDataInstance["formData"]
)
return groupLists_formDataInstances
def groupIssueDataDetails(list_issueDataInstances):
groupLists_issueDataInstances = defaultdict(list)
for issues in list_issueDataInstances:
# logger.info(formDataInstance)
# break
groupLists_issueDataInstances[issues["issue"]["type"]].append(issues["issue"])
return groupLists_issueDataInstances
def errorhandler(function, errorMessage):
logger.error(function + " " + errorMessage)
exit(1)
### Auth
class Auth:
def __init__(self, client_id, client_secret, scope):
self.client_id = client_id
self.client_secret = client_secret
self.scope = scope
self.url = "https://ims.bentley.com/connect/token"
def getToken(self):
"""
Get access token.
return: (str)bearer_token
"""
try:
# Data required grant_type, client_id, client_secret and scope
data = {
"grant_type": "client_credentials",
"client_id": self.client_id,
"client_secret": self.client_secret,
"scope": self.scope,
}
response = requests.post(self.url, data=data)
# logger.info(self.client_id)
# logger.info(self.client_secret)
if response.status_code == 200:
content = json.loads(response.content)
token_type = content["token_type"]
access_token = content["access_token"]
bearer_token = f"{token_type} {access_token}"
return bearer_token
else:
errorhandler("getToken", f"failed, {response.status_code}")
except Exception as e:
errorhandler("getToken", f"exception trigged, {e}")
###### iTwinsAPI
class iTwinsAPI:
def __init__(self, key):
self.authorization_key = key
def getAllProjectsviaiTwins(self):
"""
Get all projects via iTwinsAPI.
return: list_projects
"""
url = "https://api.bentley.com/itwins/?subClass=Project"
"""
Returns in the format:
[{'id': '8e6d360a-eb84-4e87-8a31-e99229d9128f', 'class': 'Endeavor', 'subClass': 'Project', 'type': None, 'number': 'JTC Semiconspace (Synchro)', 'displayName': 'JTC D&B Semiconspace @ Tampines WFP', 'status': 'Active'}]
"""
try:
headers = {
"Accept": "application/vnd.bentley.itwin-platform.v1+json",
"Authorization": self.authorization_key,
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
content = jsonParser(response.text)
list_projects = content["iTwins"]
return list_projects
else:
errorhandler(
"getAllProjectsviaiTwins", f"failed {response.status_code}"
)
except Exception as e:
errorhandler("getAllProjectsviaiTwins", "exception trigged" + e)
###### Forms
class FormsAPI:
def __init__(self, key):
self.authorization_key = key
def getProjectFormData(self, projectId, formtype):
"""
Get form data instances.
input: (str)projectId, The GUID of the project to get forms for.
return: (list)list_formDataInstances, The list of form data instances under the project.
[object1, object2 ...], object1->{id:'', displayname:'', type:'', state:''}
"""
try:
url = "https://api.bentley.com/forms/"
# url = f'https://api.bentley.com/forms/?projectId={projectId}'
params = {"type": formtype, "projectId": projectId}
headers = {
"Accept": "application/vnd.bentley.itwin-platform.v1+json",
"Authorization": self.authorization_key,
}
list_formDataInstances = []
while True:
response = requests.get(url, headers=headers, params=params)
# logger.info(response)
if response.status_code == 200:
content = jsonParser(response.text)
list_formDataInstances.extend(content["formDataInstances"])
if "next" in content["_links"]:
url = content["_links"]["next"]["href"]
else:
return list_formDataInstances
else:
logger.info("getFormDataDetails failed", response.status_code)
return None
except Exception as e:
logger.info("getFormDataDetails except trigged", e)
return None
def getFormDataDetails(self, formId):
"""
Get form data details.
input: (str)formId, The ID of the form data instance to retrieve.
return: (dict)content, The dict of form data details.
{
'formData':{
id:'',
subject:'',
description:'',
dueDate:'',
type:'',
...}
}
"""
try:
url = f"https://api.bentley.com/forms/{formId}"
headers = {
"Accept": "application/vnd.bentley.itwin-platform.v1+json",
"Authorization": self.authorization_key,
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
content = jsonParser(response.text)
return content
else:
errorhandler("getFormDataDetails", "failed" + response.status_code)
except Exception as e:
errorhandler("getFormDataDetails", "exception trigged" + e)
def getFormDataAttachments(self, formId):
"""
Get form data attachments ID.
input: (str)formId, The ID of the form data instance to retrieve.
return: (dict)content, The dict of form data attachments details.
{
"attachments": [{
"id": "XZzxOCC8sVvUcgeXz1Ih_exlLgPfRTpAuShXz1cTpAu",
"fileName": "CrackedConcrete.png",
"createdDateTime": "2020-10-20T16:16:30.6704320Z",
"size": 34770,
"caption": "Picture of the cracked concrete",
"binding": null,
"type": "png"
},
{
"id": "XZzxOCC8sVvUcgeXz1Ih_exlLgPfRTpAuShXz1cTpAu",
"fileName": "StreetView.png",
"createdDateTime": "2020-10-20T16:08:30.2804722Z",
"size": 56893,
"caption": "Picture showing the bridge from the perspective of an approaching car",
"binding": "Location",
"type": "png"
}
]
}
Dict{Attachments: List[Dict{"id": },{"id"}]}
"""
try:
url = f"https://api.bentley.com/forms/{formId}/attachments"
headers = {
"Accept": "application/vnd.bentley.itwin-platform.v1+json",
"Authorization": self.authorization_key,
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
content = jsonParser(response.text)
return content
else:
errorhandler("getFormDataAttachments", "failed" + response.status_code)
except Exception as e:
errorhandler("getFormDataAttachments", "exception trigged" + e)
def getFormAttachments(self, formId, attachmentId):
"""
Get form data attachments based on form Id and attachment ID.
input: (str)formId, The ID of the form data instance to retrieve.
(str)attachmentId, The ID of the form attachment to retrieve.
return: The attachment's file contents
"""
try:
url = f"https://api.bentley.com/forms/{formId}/attachments/{attachmentId}"
headers = {
"Accept": "application/vnd.bentley.itwin-platform.v1+json",
"Authorization": self.authorization_key,
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
# content = response.read()
# content = jsonParser(response)
return response
else:
errorhandler("getFormAttachments", "failed" + response.status_code)
except Exception as e:
errorhandler("getFormAttachments", "exception trigged" + e)
def exportFormPdfs(self, formId, folderId):
"""
Get form data attachments based on form Id and folder ID.
input: (str)formId, The ID of the form data instance to retrieve.
(str)folderId, The ID of the folder to retrieve.
return: The export's file contents
fb8p_AI-gEmA8dDxsQ-yiJ2t0gYGwz1PoazaH1hSMOM
"""
try:
# https://api.bentley.com/forms/storageExport?ids[&includeHeader][&fileType][&folderId]
url = f"https://api.bentley.com/forms/storageExport?ids={formId}&folderId={folderId}"
headers = {
"Accept": "application/vnd.bentley.itwin-platform.v1+json",
"Authorization": self.authorization_key,
}
# params = {"folderId": folderId,
# }
response = requests.get(url, headers=headers)
if response.status_code == 200:
# content = jsonParser(response)
return response
else:
errorhandler("exportFormPdfs", "failed" + str(response.status_code))
except Exception as e:
logger.info(e)
# errorhandler('exportFormPdfs', 'exception trigged'+ str(e) )
def updateFormData(self, formId, updateformjsonload):
"""
Create issue data form
input: (str)issueId, The ID of the issue data instance to retrieve.
return: (dict)content, The dict of issue data details.
{
'issueData':{
id:'',
subject:'',
description:'',
dueDate:'',
type:'',
...}
}
"""
try:
url = f"https://api.bentley.com/forms/{formId}"
headers = {
"Accept": "application/vnd.bentley.itwin-platform.v1+json",
"Authorization": self.authorization_key,
"Content-Type": "application/json"
}
# convert string or dictionary into json format
# json_data = payload
# logger.info (json_data)
response = requests.patch(url, data=updateformjsonload, headers=headers)
if response.status_code == 200:
content = jsonParser(response.text)
return content
else:
errorhandler("updateFormData", " failed " + str(response.status_code))
except Exception as e:
errorhandler("updateFormData", " exception trigged " + str(e))
##### Issues
class IssuesAPI:
def __init__(self, key):
self.authorization_key = key
def getProjectIssueDefinitions(self, projectId, formtype):
"""
Get issue data definition.
input: (str)projectId, The GUID of the project to get issue.
return: (list)list_IssueDataInstances, The list of issue data instances under the project.
[object1, object2 ...], object1->{id:'', displayname:'', type:'', state:''}
"""
try:
url = "https://api.bentley.com/issues/formDefinitions?"
params = {"type": formtype, "projectId": projectId}
headers = {
"Accept": "application/vnd.bentley.itwin-platform.v1+json",
"Authorization": self.authorization_key,
}
# list_issueDataDefinition = []
while True:
response = requests.get(url, headers=headers, params=params)
if response.status_code == 200:
content = jsonParser(response.text)
return content
else:
logger.error("getIssueDataDefinitions failed", response.status_code)
return None
except Exception as e:
logger.error("getIssueDataDefinition except trigged", e)
return None
def getProjectIssueData(self, projectId, issuetype):
"""
Get issue data instances.
input: (str)projectId, The GUID of the project to get issue.
return: (list)list_IssueDataInstances, The list of issue data instances under the project.
[object1, object2 ...], object1->{id:'', displayname:'', type:'', state:''}
"""
try:
# url = f'https://api.bentley.com/issues/'
url = f"https://api.bentley.com/issues/?projectId={projectId}&type={issuetype}"
# params = {'type': issuetype,
# '?projectId': projectId
# }
headers = {
"Accept": "application/vnd.bentley.itwin-platform.v1+json",
"Authorization": self.authorization_key,
}
list_issueDataInstances = []
while True:
response = requests.get(url, headers=headers)
# response = requests.get(url, headers=headers, params = params)
if response.status_code == 200:
content = jsonParser(response.text)
list_issueDataInstances.extend(content["issues"])
if "next" in content["_links"]:
url = content["_links"]["next"]["href"]
else:
return list_issueDataInstances
else:
logger.error("getProjectIssueData failed " + str(response.status_code))
return None
except Exception as e:
logger.error("getProjectIssueData except trigged " + str(e))
return None
def getIssueDataDetails(self, issueId):
"""
Get issue data details.
input: (str)issueId, The ID of the issue data instance to retrieve.
return: (dict)content, The dict of issue data details.
{
'issueData':{
id:'',
subject:'',
description:'',
dueDate:'',
type:'',
...}
}
"""
try:
url = f"https://api.bentley.com/issues/{issueId}"
headers = {
"Accept": "application/vnd.bentley.itwin-platform.v1+json",
"Authorization": self.authorization_key,
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
content = jsonParser(response.text)
return content
else:
logger.error("getIssueDataDetails", "failed" + response.status_code)
except Exception as e:
errorhandler("getIssueDataDetails", "exception trigged" + e)
def postIssueData(self, jsonload):
"""
Create issue data form
input: (str)issueId, The ID of the issue data instance to retrieve.
return: (dict)content, The dict of issue data details.
{
'issueData':{
id:'',
subject:'',
description:'',
dueDate:'',
type:'',
...}
}
"""
try:
url = "https://api.bentley.com/issues/"
headers = {
"Accept": "application/vnd.bentley.itwin-platform.v1+json",
"Authorization": self.authorization_key,
"Content-Type": "application/json"
}
# convert string or dictionary into json format
# json_data = payload
# logger.info (json_data)
response = requests.post(url, data=jsonload, headers=headers)
if response.status_code == 201:
content = jsonParser(response.text)
return content
else:
logger.error("postIssueData", "failed" + str(response.status_code))
except Exception as e:
errorhandler("postIssueData", "exception trigged" + str(e))
def updateIssueData(self, issueId, updatejsonload):
"""
update issue data form
input: (str)issueId, The ID of the issue data instance to retrieve.
return: (dict)content, The dict of issue data details.
{
'issueData':{
id:'',
subject:'',
description:'',
dueDate:'',
type:'',
...}
}
"""
try:
url = f"https://api.bentley.com/issues/{issueId}"
headers = {
"Accept": "application/vnd.bentley.itwin-platform.v1+json",
"Authorization": self.authorization_key,
"Content-Type": "application/json"
}
# convert string or dictionary into json format
# json_data = payload
# logger.info (json_data)
response = requests.patch(url, data=updatejsonload, headers=headers)
if response.status_code == 200:
content = jsonParser(response.text)
return content
else:
logger.error("updateIssueData failed " + str(response.status_code))
return None
except Exception as e:
errorhandler("updateIssueData", "exception trigged " + str(e))
def exportIssuePdfs(self, IssueId, folderId):
"""
Get issue data attachments based on issue Id and issue ID.
input: (str)issueId, The ID of the issue data instance to retrieve.
(str)folderId, The ID of the folder to retrieve.
return: The export's file contents
fb8p_AI-gEmA8dDxsQ-yiJ2t0gYGwz1PoazaH1hSMOM
"""
try:
# https://api.bentley.com/issues/storageExport?ids[&includeHeader][&fileType][&folderId]
# https://api.bentley.com/issues/storageExport?ids[&includeHeader][&fileType][&folderId]
url = f"https://api.bentley.com/issues/storageExport?ids={IssueId}&folderId={folderId}"
headers = {
"Accept": "application/vnd.bentley.itwin-platform.v1+json",
"Authorization": self.authorization_key,
}
# params = {"folderId": folderId,
# "fileType": "pdf",
# "includeHeader": "true"
# }
response = requests.get(url, headers=headers)
if response.status_code == 200:
# content = jsonParser(response)
return response
else:
logger.error("exportIssuePdfs", "failed" + str(response.status_code))
except Exception as e:
errorhandler("exportIssuePdfs", "exception trigged" + str(e))
##Export
class StorageAPI:
def __init__(self, key):
self.authorization_key = key
def getTopLevelFolder(self, projectId):
try:
url = f"https://api.bentley.com/storage/?projectId={projectId}"
headers = {
"Accept": "application/vnd.bentley.itwin-platform.v1+json",
"Authorization": self.authorization_key,
}
list_folderInstances = []
response = requests.get(url, headers=headers)
if response.status_code == 200:
content = jsonParser(response.text)
list_folderInstances.extend(content["items"])
return list_folderInstances
# return content
else:
logger.error("getTopLevelFolder failed", response.status_code)
return None
# while(True):
# response = requests.get(url, headers=headers)
# #response = requests.get(url, headers=headers, params = params)
# if(response.status_code == 200):
# content = jsonParser(response.text)
# list_folderInstances.extend(content['items'])
# if('next' in content['_links']):
# url = content['_links']['next']['href']
# logger.info("next")
# else:
# return list_folderInstances
# else:
# logger.info('getTopLevelFolder failed', response.status_code)
# return None
except Exception as e:
logger.info("getTopLevelFolder except trigged", e)
return None
def createFolder(self, folderId, jsonload):
"""
create a new folder
"displayName": "test",
"description": "test folder"
"""
try:
url = f"https://api.bentley.com/storage/folders/{folderId}/folders"
headers = {
"Accept": "application/vnd.bentley.itwin-platform.v1+json",
"Authorization": self.authorization_key,
}
response = requests.post(url, data=jsonload, headers=headers)
if response.status_code == 201:
content = jsonParser(response.text)
return content
else:
errorhandler("createFolder", "failed" + str(response.status_code))
except Exception as e:
errorhandler("createFolder", "exception trigged" + str(e))
##Implementation Account
## Name:JTC_DBE_API
client_id = CLIENT_ID
client_secret = CLIENT_SECRET
# list all required scope
scope = ["itwins:read issues:read issues:modify"]
# Create auth object, and get access token.
auth = Auth(client_id, client_secret, scope)
authorization_key = auth.getToken()
logger.info("Got access token.")
# Create projects_API object, and get all projects. (deprecated)
# projects_API = ProjectsAPI(authorization_key)
# list_projects = projects_API.getAllProjects()
# Create iTwins_API object, and get all projects.
itwins_API = iTwinsAPI(authorization_key)
issues_API = IssuesAPI(authorization_key)
list_projects = itwins_API.getAllProjectsviaiTwins()
logger.info("Got all projects.")
if list_projects is None:
logger.info("No projects.")
exit()
##Read the forms
# list_projects = [{'id': '69c70697-3747-4120-b185-dbd7d54388a0', 'displayName': 'JTC R&R to Biopolis Phase 1 (Synchro)', 'projectNumber': 'JTC BIOR (Synchro)'}]
today = date.today()
for project in list_projects:
if project["id"] == "69c70697-3747-4120-b185-dbd7d54388a0":
# logger.info(project['id'])
# Get Post OT Form
# Get all OT Request form
list_issueDataInstances = issues_API.getProjectIssueData(
project["id"], "Post OT Form"
)
if list_issueDataInstances is None:
logger.info(f"{project['displayName']} - No Post OT Form.")
continue
else:
list_issueDetails = []
logger.info(f"{project['displayName']} - Extracting Post OT Forms")
# Iterate every form ID to get form data details
for issues in list_issueDataInstances:
# logger.info(issues)
# for every issue ID, get the Issue data details
issueDetail = issues_API.getIssueDataDetails(issues["id"])
if issueDetail is not None:
# add to a list
list_issueDetails.append(issueDetail)
# logger.info(list_issueDetails)
else:
logger.info(f"{issues['id']} - No Issue Data Details.")
continue
logger.info(f"{project['displayName']} - Extracted Post OT Forms")
# Group if there is more than one RSS attendance form type
dictLists_IssueDataDetails = groupIssueDataDetails(list_issueDetails)
# logger.info(dictLists_IssueDataDetails)
# logger.info("Extracted Post OT Forms")
# iterate for every Post OT issue
for key in dictLists_IssueDataDetails.keys():
# convert into dataframe
dfPostOT = pd.json_normalize(dictLists_IssueDataDetails[key])
# Convert the datetime into just day, month and year
dfPostOT["createdDateTime"] = dfPostOT["createdDateTime"].apply(
lambda x: pd.to_datetime(x).strftime("%Y-%m-%d")
)
# To filter month and year
dfPostOT["yearmonth"] = dfPostOT["createdDateTime"].apply(
lambda x: pd.to_datetime(x).strftime("%Y-%m")
)
##Update OT hours
##Only update days that there are values
OTHourlist = []
dfPostOT["PostOTTimeIn"] = pd.to_datetime(
dfPostOT["properties.ActualOTStart"], format="%H:%M", errors="coerce"
)
dfPostOT["PostOTTimeOut"] = pd.to_datetime(
dfPostOT["properties.ActualOTEnd"], format="%H:%M", errors="coerce"
)
dfPostOT["PostOTHour"] = (
(
dfPostOT["PostOTTimeOut"].apply(lambda x: x.hour)
- dfPostOT["PostOTTimeIn"].apply(lambda x: x.hour)
)
+ (
dfPostOT["PostOTTimeOut"].apply(lambda x: x.minute)
- dfPostOT["PostOTTimeIn"].apply(lambda x: x.minute)
)
/ 60
) - dfPostOT["properties.RSSMeal1"]
## if OT hours = -ve, need to add 24 hours
dfPostOT["PostOTHour"] = dfPostOT["PostOTHour"].apply(
lambda x: x + 24 if x < 0 else x
)
# Update Attendance Form
for id in dfPostOT["id"]:
if dfPostOT["state"].loc[dfPostOT["id"] == id].values[0] == "Open":