-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClockifyAPI.py
More file actions
904 lines (757 loc) · 32.5 KB
/
ClockifyAPI.py
File metadata and controls
904 lines (757 loc) · 32.5 KB
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "Markus Proeller"
__copyright__ = "Copyright 2019, pieye GmbH (www.pieye.org)"
__maintainer__ = "Markus Proeller"
__email__ = "markus.proeller@pieye.org"
import datetime
import json
import logging
import time
from enum import Enum
import requests
class RetVal(Enum):
OK = 0
ERR = 1
EXISTS = 2
FORBIDDEN = 3
class HourlyRate:
def __init__(self, amount, currency="EUR"):
self.rate = {}
self.rate["amount"] = amount
self.rate["currency"] = currency
class MemberShip:
def __init__(self, api):
self.connector = api
self.memberShip = []
self.workspace = ""
def addMembership(self, userMail, projectName, workspace,
membershipType="PROJECT", membershipStatus="ACTIVE",
hourlyRate=None, manager=False):
self.workspace = workspace
userID = self.connector.getUserIDByMail(userMail, workspace)
# prjID = self.connector.getProjectID(projectName, workspace)
membership = {}
membership["membershipStatus"] = membershipStatus
membership["membershipType"] = membershipType
# membership["targetId"] = prjID
membership["userId"] = userID
membership["manager"] = manager
if hourlyRate != None:
membership["hourlyRate"] = hourlyRate.rate
self.memberShip.append(membership)
def getManagerUserMail(self):
mail = ""
for m in self.memberShip:
if m["manager"] == True:
mail = self.connector.getUserMailById(m["userId"], self.workspace)
break
return mail
def getData(self):
return self.memberShip
class ClockifyAPI:
def __init__(self, apiToken, adminEmail="", reqTimeout=0.01, fallbackUserMail=None):
self.logger = logging.getLogger('clockify-automation')
self.url = 'https://api.clockify.me/api/v1'
self.urlWorking = 'https://api.clockify.me/api/v1'
self._syncClients = True
self._syncUsers = True
self._syncProjects = True
self._syncTags = True
self._syncGroups = True
self._syncTasks = True
self._adminEmail = adminEmail
self._reqTimeout = reqTimeout
self.fallbackUserMail = fallbackUserMail
self._APIusers = []
adminFound = False
fallbackFound = False
for token in [apiToken]:
self.logger.info("testing clockify APIKey %s" % token)
self.apiToken = token
url = self.url + "/user"
rv = self._request(url)
if rv.status_code != 200:
raise RuntimeError("error loading user (API token %s), status code %s" % (token, str(rv.status_code)))
rv = rv.json()
user = {}
user["name"] = rv["name"]
user["token"] = token
user["email"] = rv["email"]
user["id"] = rv["id"]
if (rv["status"].upper() != "ACTIVE") and (rv["status"].upper() != "PENDING_EMAIL_VERIFICATION"):
raise RuntimeError(
"user '%s' is not an active user in clockify. Please activate the user for the migration process" %
user["email"])
self._APIusers.append(user)
if rv["email"].lower() == adminEmail.lower():
adminFound = True
if self.fallbackUserMail != None:
if rv["email"].lower() == self.fallbackUserMail.lower():
fallbackFound = True
self.logger.info("...ok, key resolved to email %s" % rv["email"])
if not adminFound:
raise RuntimeError("admin mail address was given as %s but not found in clockify API tokens" % adminEmail)
if fallbackFound == False and self.fallbackUserMail != None:
raise RuntimeError(
"falback user mail address was given as %s but not found in clockify API tokens" % self.fallbackUserMail)
self._loadedUserEmail = None
self._loadUser(self._APIusers[0]["email"])
self._getWorkspaces()
def _loadAdmin(self):
return self._loadUser(self._adminEmail)
def _loadUser(self, userMail):
mailChk = self._loadedUserEmail
if mailChk == None:
mailChk = ""
if userMail.lower() == mailChk.lower():
return RetVal.OK
userLoaded = False
for user in self._APIusers:
if user["email"].lower() == userMail.lower():
self.apiToken = user["token"]
self.email = user["email"]
self.userID = user["id"]
url = self.url + "/user"
rv = self._request(url)
if rv.status_code != 200:
raise RuntimeError("error loading user %s, status code %s" % (user["email"], str(rv.status_code)))
userLoaded = True
self._loadedUserEmail = user["email"]
break
if userLoaded == False:
rv = RetVal.ERR
self.logger.warning("user %s not found" % userMail)
else:
rv = RetVal.OK
return rv
def multiGetRequest(self, url, idKey="id"):
headers = {
'X-Api-Key': self.apiToken}
curPage = 1
rvData = []
while True:
body = {"page": curPage, "page-size": 50}
rv = requests.get(url, headers=headers, params=body)
if rv.status_code == 200:
data = rv.json()
if len(data) < 50:
rvData.extend(data)
break
else:
# check if we got new data
chkID = data[0][idKey]
if not any(d[idKey] == chkID for d in rvData):
rvData.extend(data)
else:
break
curPage += 1
else:
raise RuntimeError("get on url %s failed with status code %d" % (url, rv.status_code))
return rvData
def _request(self, url, body=None, typ="GET"):
headers = {
'X-Api-Key': self.apiToken}
if typ == "GET":
response = requests.get(url, headers=headers, params=body)
elif typ == "POST":
response = requests.post(url, headers=headers, json=body)
elif typ == "DELETE":
response = requests.delete(url, headers=headers)
else:
raise RuntimeError("invalid request type %s" % typ)
time.sleep(self._reqTimeout)
return response
def getWorkspaces(self):
return self.workspaces
def getWorkspaceID(self, workspaceName):
wsId = None
workspaces = self.getWorkspaces()
for ws in workspaces:
if ws["name"] == workspaceName:
wsId = ws["id"]
if wsId == None:
raise RuntimeError("Workspace %s not found. Available workspaces: %s" % (workspaceName, workspaces))
return wsId
def _getWorkspaces(self):
url = self.url + "/workspaces"
rv = self._request(url)
if rv.status_code == 200:
self.workspaces = rv.json()
else:
raise RuntimeError("Querying workspaces for user %s failed, status code=%d, msg=%s" % (
self._APIusers[0]["email"], rv.status_code, rv.text))
return self.workspaces
def addClient(self, name, workspace):
curUser = self._loadedUserEmail
self._loadAdmin()
wsId = self.getWorkspaceID(workspace)
url = self.url + "/workspaces/%s/clients" % wsId
params = {"name": name}
rv = self._request(url, body=params, typ="POST")
if rv.ok == False:
if rv.status_code == 400:
rv = RetVal.EXISTS
else:
self.logger.warning(
"Error adding client %s, status code=%d, msg=%s" % (name, rv.status_code, rv.reason))
rv = RetVal.ERR
else:
rv = RetVal.OK
self._syncClients = True
self._loadUser(curUser)
return rv
def getClients(self, workspace):
if self._syncClients == True:
curUser = self._loadedUserEmail
self._loadAdmin()
wsId = self.getWorkspaceID(workspace)
url = self.url + "/workspaces/%s/clients" % wsId
self.clients = self.multiGetRequest(url)
self._syncClients = False
self.logger.info("finished getting clockify clients, saving results to clockify_clients.json")
f = open("clockify_clients.json", "w")
f.write(json.dumps(self.clients, indent=2))
f.close()
self._loadUser(curUser)
return self.clients
def getTasksOnProject(self, workspace, projectName):
curUser = self._loadedUserEmail
self._loadAdmin()
wsId = self.getWorkspaceID(workspace)
pId = self.getProjectID(projectName, workspace)
url = self.url + "/workspaces/%s/projects/%s/tasks" % (wsId, pId)
self.pTasks = self.multiGetRequest(url)
self._loadUser(curUser)
return self.pTasks
def getTaskIdFromTasks(self, taskName, pTasks):
tId = None
if pTasks != None:
for t in pTasks:
if t["name"] == taskName:
tId = t["id"]
if tId == None:
raise RuntimeError("Task %s not found." % (taskName))
return tId
def getClientID(self, client, workspace, skipCliQuery=False):
clId = None
if skipCliQuery:
clients = self.clients
else:
clients = self.getClients(workspace)
for c in clients:
if c["name"] == client:
clId = c["id"]
if clId == None:
raise RuntimeError("Client %s not found in workspace %s" % (client, workspace))
return clId
def getProjects(self, workspace, skipPrjQuery=False):
if self._syncProjects == True:
curUser = self._loadedUserEmail
self.projects = []
for user in self._APIusers:
self.logger.info("synchronizing clockify projects for user %s..." % user["email"])
self._loadUser(user["email"])
wsId = self.getWorkspaceID(workspace)
url = self.url + "/workspaces/%s/projects" % wsId
projects = self.multiGetRequest(url)
self.projects.extend(projects)
self.logger.info("finished synchronizing clockify projects, saving results to clockify_projects.json")
f = open("clockify_projects.json", "w")
f.write(json.dumps(self.projects, indent=2))
f.close()
self._loadUser(curUser)
self._syncProjects = False
return self.projects
# using Working API entry point
def getWorkspaceProjects(self, workspace, skipPrjQuery=False):
if self._syncProjects == True:
curUser = self._loadedUserEmail
if skipPrjQuery:
projects = self.projects
else:
self.projects = []
wsId = self.getWorkspaceID(workspace)
url = self.urlWorking + "/workspaces/%s/projects/" % wsId
self.projects = self.multiGetRequest(url)
self._syncProjects = False
self.logger.info("Finished getting clockify projects, saving results to clockify_projects.json")
f = open("clockify_projects.json", "w")
f.write(json.dumps(self.projects, indent=2))
f.close()
self._loadUser(curUser)
return self.projects
def getProjectID(self, project, workspace, skipPrjQuery=False):
pId = None
if skipPrjQuery:
projects = self.projects
else:
projects = self.getProjects(workspace, skipPrjQuery)
for p in projects:
if p["name"] == project:
pId = p["id"]
if pId == None:
raise RuntimeError("Project %s not found in workspace %s" % (project, workspace))
return pId
def getUsers(self, workspace):
if self._syncUsers == True:
curUser = self._loadedUserEmail
self._loadAdmin()
wsId = self.getWorkspaceID(workspace)
url = self.url + "/workspace/%s/users" % wsId
rv = self._request(url, typ="GET")
self.users = rv.json()
self._syncUsers = False
self.logger.info("finsihed getting clockify users, saving results to clockify_users.json")
f = open("clockify_users.json", "w")
f.write(json.dumps(self.users, indent=2))
f.close()
self._loadUser(curUser)
return self.users
def getUsersInProject(self, wsId, pId):
userIds = []
url = self.urlWorking + "/workspaces/%s/projects/%s/users" % (wsId, pId)
rv = self._request(url, typ="GET")
userIds = rv.json()
self.logger.info("Finished getting users already assigned to the project.")
return userIds
def getUserIDByName(self, user, workspace):
uId = None
users = self.getUsers(workspace)
for u in users:
if u["name"] == user:
uId = u["id"]
if uId == None:
raise RuntimeError("User %s not found in workspace %s" % (user, workspace))
return uId
def getUserMailById(self, userID, workspace):
mail = None
users = self.getUsers(workspace)
for u in users:
if u["id"] == userID:
mail = u["email"]
if mail == None:
raise RuntimeError("User ID %s not found in workspace %s" % (userID, workspace))
return mail
def getUserIDByMail(self, email, workspace):
uId = None
users = self.getUsers(workspace)
for u in users:
if u["email"] == email:
uId = u["id"]
if uId == None:
raise RuntimeError("User %s not found in workspace %s" % (email, workspace))
return uId
def addProject(self, name, client, workspace, isPublic=False, billable=False,
color="#f44336", memberships=None, hourlyRate=None, manager=""):
curUser = self._loadedUserEmail
if manager == "":
if isPublic == False:
admin = self._adminEmail
self.logger.warning("no manager found for project %s, making %s as manager" % (name, admin))
self._loadAdmin()
else:
self._loadUser(manager)
wsId = self.getWorkspaceID(workspace)
clId = None
if not client is None:
clId = self.getClientID(client, workspace)
url = self.url + "/workspaces/%s/projects" % wsId
params = {"name": name, "isPublic": isPublic,
"billable": billable, "color": color}
if not clId is None:
params["clientId"] = clId
if memberships != None:
params["memberships"] = memberships.getData()
if hourlyRate != None:
params["hourlyRate"] = hourlyRate.rate
rv = self._request(url, body=params, typ="POST")
if rv.status_code == 201:
self._syncProjects = True
rv = RetVal.OK
elif rv.status_code == 400:
rv = RetVal.EXISTS
elif rv.status_code == 403:
rv = RetVal.FORBIDDEN
else:
self.logger.warning("Error adding project %s, status code=%d, msg=%s" % (name, rv.status_code, rv.reason))
rv = RetVal.ERR
self._loadUser(curUser)
return rv
# using Working API entry point
def addGroupsToProject(self, wsName, wsId, pId, wsGroupIds, pGroups):
# API fields to POST: {userIds = [], userGroupIds = []}
# From: https://clockify.github.io/clockify_api_docs/#operation--workspaces--workspaceId--projects--projectId--team-post
url = self.urlWorking + "/workspaces/%s/projects/%s/team" % (wsId, pId)
userIds = []
userGroupIds = []
pUsers = self.getUsersInProject(wsId, pId)
if pUsers == None:
userIds = []
else:
for pUser in pUsers:
# try for errors?
userIds.append(pUser["id"])
for pGroup in pGroups:
try:
pg = wsGroupIds.index(pGroup["group_id"])
except Exception as e:
self.logger.warning("Group id %d not found in toggl workspace, msg=%s" % (pGroup["group_id"], str(e)))
break
for pGroup in pGroups:
# try for errors?
gId = self.getUserGroupID(pGroup["name"], wsName)
userGroupIds.append(gId)
params = {"userIds": userIds,
"userGroupIds": userGroupIds}
rv = self._request(url, body=params, typ="POST")
if (rv.status_code == 201) or (rv.status_code == 200):
rv = RetVal.OK
elif rv.status_code == 400:
rv = RetVal.EXISTS
elif rv.status_code == 403:
rv = RetVal.FORBIDDEN
else:
self.logger.warning("Error adding Groups to Project, status code=%d, msg=%s" % (rv.status_code, rv.reason))
rv = RetVal.ERR
return rv
# using Working API entry point
def getUserGroups(self, workspace):
if self._syncGroups == True:
curUser = self._loadedUserEmail
self._loadAdmin()
self.userGroups = []
wsId = self.getWorkspaceID(workspace)
url = self.urlWorking + "/workspaces/%s/userGroups" % wsId
self.userGroups = self.multiGetRequest(url)
self._syncGroups = False
self.logger.info("Finished getting clockify groups, saving results to clockify_groups.json")
f = open("clockify_groups.json", "w")
f.write(json.dumps(self.userGroups, indent=2))
f.close()
self._loadUser(curUser)
return self.userGroups
# using Working API entry point
def addUserGroup(self, groupName, workspace):
curUser = self._loadedUserEmail
self._loadAdmin()
wsId = self.getWorkspaceID(workspace)
url = self.urlWorking + "/workspaces/%s/userGroups/" % wsId
params = {"name": groupName}
rv = self._request(url, body=params, typ="POST")
if rv.status_code == 201:
self._syncGroups = True
rv = RetVal.OK
elif rv.status_code == 400:
rv = RetVal.EXISTS
else:
self.logger.warning(
"Error adding group %s, status code=%d, msg=%s" % (groupName, rv.status_code, rv.reason))
rv = RetVal.ERR
self._loadUser(curUser)
return rv
def getUserGroupName(self, userGroupID, workspace):
uName = None
userGroups = self.getUserGroups(workspace)
for u in userGroups:
if u["id"] == userGroupID:
uName = u["name"]
if uName == None:
raise RuntimeError("User Group %s not found in workspace %s" % (userGroupID, workspace))
return uName
def getUserGroupID(self, userGroupName, workspace):
uId = None
userGroups = self.getUserGroups(workspace)
for u in userGroups:
if u["name"] == userGroupName:
uId = u["id"]
if uId == None:
raise RuntimeError("User Group %s not found in workspace %s" % (userGroupName, workspace))
return uId
def getTags(self, workspace):
if self._syncTags == True:
curUser = self._loadedUserEmail
self._loadAdmin()
self.tags = []
wsId = self.getWorkspaceID(workspace)
url = self.url + "/workspaces/%s/tags" % wsId
self.tags = self.multiGetRequest(url)
self._syncTags = False
self.logger.info("Finished getting clockify tags, saving results to clockify_tags.json")
f = open("clockify_tags.json", "w")
f.write(json.dumps(self.tags, indent=2))
f.close()
self._loadUser(curUser)
return self.tags
def addTag(self, tagName, workspace):
curUser = self._loadedUserEmail
self._loadAdmin()
wsId = self.getWorkspaceID(workspace)
url = self.url + "/workspaces/%s/tags" % wsId
params = {"name": tagName}
rv = self._request(url, body=params, typ="POST")
if rv.status_code == 201:
self._syncTags = True
rv = RetVal.OK
elif rv.status_code == 400:
rv = RetVal.EXISTS
else:
self.logger.warning("Error adding tag %s, status code=%d, msg=%s" % (tagName, rv.status_code, rv.reason))
rv = RetVal.ERR
self._loadUser(curUser)
return rv
def getTagName(self, tagID, workspace):
tName = None
tags = self.getTags(workspace)
for t in tags:
if t["id"] == tagID:
tName = t["name"]
if tName == None:
raise RuntimeError("TagID %s not found in workspace %s" % (tagID, workspace))
return tName
def getTagID(self, tagName, workspace):
tId = None
tags = self.getTags(workspace)
for t in tags:
if t["name"] == tagName:
tId = t["id"]
if tId == None:
raise RuntimeError("Tag %s not found in workspace %s" % (tagName, workspace))
return tId
def addTask(self, wsId, name, projectId, estimate):
curUser = self._loadedUserEmail
self._loadAdmin()
# wsId = self.getWorkspaceID(workspace)
url = self.url + "/workspaces/%s/projects/%s/tasks/" % (wsId, projectId)
params = {
"name": name,
"projectId": projectId,
"estimate": estimate
}
rv = self._request(url, body=params, typ="POST")
if rv.status_code == 201:
self._syncTasks = True
rv = RetVal.OK
elif rv.status_code == 400:
rv = RetVal.EXISTS
else:
self.logger.warning("Error adding task %s, status code=%d, msg=%s" % (name, rv.status_code, rv.reason))
rv = RetVal.ERR
self._loadUser(curUser)
return rv
def addEntry(self, start, description, projectName, userMail, workspace,
timeZone="Z", end=None, billable=False, tagNames=None, taskName=None):
rv = self._loadUser(userMail)
data = None
if rv == RetVal.OK:
wsId = self.getWorkspaceID(workspace)
url = self.url + "/workspaces/%s/time-entries" % wsId
if projectName != None:
projectId = self.getProjectID(projectName, workspace, skipPrjQuery=self._syncProjects)
if taskName != None:
pTasks = self.getTasksOnProject(workspace, projectName)
taskId = self.getTaskIdFromTasks(taskName, pTasks)
self.logger.info("Found task %s in project %s" % (taskName, projectName))
else:
taskId = None
else:
taskId = None
self.logger.info("no project in entry %s" % description)
startTime = start.strftime('%Y-%m-%dT%H:%M:%SZ')
if end != None:
end_plus = (end + datetime.timedelta(hours=3)).strftime('%Y-%m-%dT%H:%M:%SZ')
end = end.strftime('%Y-%m-%dT%H:%M:%SZ')
params = {
"start": startTime,
"billable": billable,
"description": description
}
if projectName != None:
params["projectId"] = projectId
if taskId != None:
params["taskId"] = taskId
if end != None:
params["end"] = end
if tagNames != None:
tagIDs = []
for tag in tagNames:
tid = self.getTagID(tag, workspace)
tagIDs.append(tid)
params["tagIds"] = tagIDs
rv, entr = self.getTimeEntryForUser(userMail, workspace, description, projectName,
start, timeZone=timeZone, end=end_plus)
if rv == RetVal.OK:
if entr != []:
# filter data
filteredData = []
for d in entr:
anyDiff = False
if params["start"] != d['timeInterval']["start"]:
anyDiff = True
# self.logger.info("entry diff @start: %s %s"%(str(params["start"]), str(d['timeInterval']["start"])))
if params["end"] != d['timeInterval']["end"]:
anyDiff = True
if 'projectId' in params:
if params["projectId"] != d['projectId']:
anyDiff = True
# self.logger.info("entry diff @projectID: %s %s"%(str(params["projectId"]), str(d['projectId'])))
if params["description"] != d["description"]:
anyDiff = True
# self.logger.info("entry diff @desc: %s %s"%(str(params["description"]), str(d['description'])))
if self.userID != d["userId"]:
anyDiff = True
# self.logger.info("entry diff @userID: %s %s"%(str(self.userID), str(d['userId'])))
if tagNames != None:
tagIdsRcv = d["tagIds"]
tagIdsRcv = tagIdsRcv if tagIdsRcv != None else []
tagNamesRcv = []
for tagID in tagIdsRcv:
tagNamesRcv.append(self.getTagName(tagID, workspace))
if set(tagNames) != set(tagNamesRcv):
# self.logger.info("entry diff @tagNames: %s %s"%(str(set(tagNames)), str(set(tagNamesRcv))))
anyDiff = True
if anyDiff == False:
filteredData.append(d)
entr = filteredData
if entr == []:
rv = self._request(url, body=params, typ="POST")
self.logger.info("Adding entry: %s" % (json.dumps(params, indent=2)))
if rv.ok:
data = rv.json()
rv = RetVal.OK
else:
self.logger.warning(
"Error adding time entrs, status code=%d, msg=%s" % (rv.status_code, rv.text))
rv = RetVal.ERR
else:
rv = RetVal.EXISTS
else:
rv = RetVal.ERR
return rv, data
def getTimeEntryForUser(self, userMail, workspace, description,
projectName, start, timeZone="Z", end=None):
data = None
rv = self._loadUser(userMail)
if rv == RetVal.OK:
wsId = self.getWorkspaceID(workspace)
uId = self.userID
if projectName != None:
prjID = self.getProjectID(projectName, workspace)
if start != None:
start = start.strftime('%Y-%m-%dT%H:%M:%SZ')
url = self.url + "/workspaces/%s/user/%s/time-entries" % (wsId, uId)
params = {"description": description}
if start != None:
params["start"] = start
if projectName != None:
params["project"] = prjID
if end:
params["end"] = end
rv = self._request(url, body=params, typ="GET")
if rv.ok:
data = rv.json()
rv = RetVal.OK
else:
self.logger.warning("Error getTimeEntryForUser, status code=%d, msg=%s" % (rv.status_code, rv.reason))
rv = RetVal.ERR
return rv, data
def archiveProject(self, projectName, workspace, skipPrjQuery=False):
wsId = self.getWorkspaceID(workspace)
pID = self.getProjectID(projectName, workspace, skipPrjQuery=skipPrjQuery)
url = "https://api.clockify.me/api/workspaces/%s/projects/%s/archive" % (wsId, pID)
rv = self._request(url, typ="GET")
if rv.status_code == 200:
rv = RetVal.OK
else:
self.logger.warning(
"Archiving project %s failed, status code=%d, msg=%s" % (projectName, rv.status_code, rv.reason))
rv = RetVal.ERR
return rv
def deleteEntriesOfUser(self, userMail, workspace, start=None):
while True:
rv, entries = self.getTimeEntryForUser(userMail, workspace, "", None, start, "")
numEntries = 0
if rv == RetVal.OK:
curUser = self._loadedUserEmail
rv = self._loadAdmin()
if rv == RetVal.OK:
numEntries = len(entries)
idx = 0
for e in entries:
msg = "deleting entry %d of %d" % (idx + 1, numEntries)
self.logger.info(msg)
rv = self.deleteEntry(e["id"], workspace)
if rv == RetVal.OK:
self.logger.info("...ok")
idx += 1
self._loadUser(curUser)
if numEntries == 0:
break
return numEntries
def deleteEntry(self, entryID, workspace):
wsId = self.getWorkspaceID(workspace)
url = self.url + "/workspaces/%s/time-entries/%s" % (wsId, entryID)
rv = self._request(url, typ="DELETE")
if rv.ok:
return RetVal.OK
else:
self.logger.warning("Error deleteEntry, status code=%d, msg=%s" % (rv.status_code, rv.reason))
return RetVal.ERR
def deleteProject(self, projectName, workspace, skipPrjQuery=False):
wsId = self.getWorkspaceID(workspace)
projectID = self.getProjectID(projectName, workspace, skipPrjQuery)
url = self.url + "/workspaces/%s/projects/%s" % (wsId, projectID)
rv = self._request(url, typ="DELETE")
if rv.ok:
self._syncProjects = True
return RetVal.OK
else:
self.logger.warning("Error deleteProject, status code=%d, msg=%s" % (rv.status_code, rv.reason))
return RetVal.ERR
def deleteAllProjects(self, workspace):
curUser = self._loadedUserEmail
for user in self._APIusers:
self._loadUser(user["email"])
self.logger.info("Deleting all project from user %s" % user["email"])
prjs = self.getProjects(workspace)
idx = 0
numProjects = len(prjs)
for p in prjs:
msg = "deleting project %s (%d of %d)" % (p["name"], idx + 1, numProjects)
self.logger.info(msg)
self.deleteProject(p["name"], workspace, skipPrjQuery=True)
idx += 1
self._loadUser(curUser)
def wipeOutWorkspace(self, workspace):
curUser = self._loadedUserEmail
for user in self._APIusers:
self.logger.info("Deleting all entries from user %s" % user["email"])
self.deleteEntriesOfUser(user["email"], workspace)
self.deleteAllProjects(workspace)
self.deleteAllClients(workspace)
self._loadUser(curUser)
def deleteClient(self, clientName, workspace, skipCliQuery=False):
wsId = self.getWorkspaceID(workspace)
clId = self.getClientID(clientName, workspace, skipCliQuery)
url = "https://api.clockify.me/api/workspaces/%s/clients/%s" % (wsId, clId)
rv = self._request(url, typ="DELETE")
if rv.ok:
self._syncClients = True
return RetVal.OK
else:
self.logger.warning("Error deleteClient, status code=%d, msg=%s" % (rv.status_code, rv.reason))
return RetVal.ERR
def deleteAllClients(self, workspace):
curUser = self._loadedUserEmail
for user in self._APIusers:
self._loadUser(user["email"])
self.logger.info("Deleting all clients from user %s" % user["email"])
clis = self.getClients(workspace)
idx = 0
numClients = len(clis)
for c in clis:
msg = "deleting client %s (%d of %d)" % (c["name"], idx + 1, numClients)
self.logger.info(msg)
self.deleteClient(c["name"], workspace, skipCliQuery=True)
idx += 1
self._loadUser(curUser)