forked from AuHau/toggl-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtoggl.py
More file actions
executable file
·1348 lines (1176 loc) · 47.7 KB
/
toggl.py
File metadata and controls
executable file
·1348 lines (1176 loc) · 47.7 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
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
#!/usr/bin/env python
"""
toggl.py
The MIT License (MIT)
Copyright (c) 2014 D. Robert Adams
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Modified for toggl API v8 by Beau Raines
ASCII art from http://patorjk.com/software/taag/#p=display&c=bash&f=Standard
"""
# This file is divided into three main parts.
# 1. Utility Classes - generic support code
# 2. Toggl Models - Toggl-specific data classes
# 3. Command Line Interface - CLI
import datetime
import dateutil.parser
import iso8601
import json
import optparse
import os
import pytz
import requests
import sys
import time
import six
from six.moves import urllib
from six.moves import configparser as ConfigParser
TOGGL_URL = "https://www.toggl.com/api/v8"
VERBOSE = False # verbose output?
Parser = None # OptionParser initialized by main()
VISIT_WWW_COMMAND = "open http://www.toggl.com/app/timer"
#############################################################################
# _ _ _ _ _ _ _ ____ _
# | | | | |_(_) (_) |_ _ _ / ___| | __ _ ___ ___ ___ ___
# | | | | __| | | | __| | | | | | | |/ _` / __/ __|/ _ \/ __|
# | |_| | |_| | | | |_| |_| | | |___| | (_| \__ \__ \ __/\__ \
# \___/ \__|_|_|_|\__|\__, | \____|_|\__,_|___/___/\___||___/
# |___/
#############################################################################
#----------------------------------------------------------------------------
# Singleton
#----------------------------------------------------------------------------
class Singleton(type):
"""
Defines a way to implement the singleton pattern in Python.
From: http://stackoverflow.com/questions/31875/is-there-a-simple-elegant-way-to-define-singletons-in-python/33201#33201
To use, simply put the following line in your class definition:
__metaclass__ = Singleton
"""
def __init__(cls, name, bases, dict):
super(Singleton, cls).__init__(name, bases, dict)
cls.instance = None
def __call__(cls,*args,**kw):
if cls.instance is None:
cls.instance = super(Singleton, cls).__call__(*args, **kw)
return cls.instance
#----------------------------------------------------------------------------
# Config
#----------------------------------------------------------------------------
class Config(object):
"""
Singleton. toggl configuration data, read from ~/.togglrc.
Properties:
auth - (username, password) tuple.
"""
__metaclass__ = Singleton
def __init__(self):
"""
Reads configuration data from ~/.togglrc.
"""
self.cfg = ConfigParser.ConfigParser({'continue_creates': 'false'})
if self.cfg.read(os.path.expanduser('~/.togglrc')) == []:
self._create_empty_config()
raise IOError("Missing ~/.togglrc. A default has been created for editing.")
def _create_empty_config(self):
"""
Creates a blank ~/.togglrc.
"""
cfg = ConfigParser.RawConfigParser()
cfg.add_section('auth')
cfg.set('auth', 'username', 'user@example.com')
cfg.set('auth', 'password', 'toggl_password')
cfg.set('auth', 'api_token', 'your_api_token')
cfg.add_section('options')
cfg.set('options', 'timezone', 'UTC')
cfg.set('options', 'time_format', '%I:%M%p')
cfg.set('options', 'prefer_token', 'true')
cfg.set('options', 'continue_creates', 'true')
with open(os.path.expanduser('~/.togglrc'), 'w') as cfgfile:
cfg.write(cfgfile)
os.chmod(os.path.expanduser('~/.togglrc'), 0o600)
def get(self, section, key):
"""
Returns the value of the configuration variable identified by the
given key within the given section of the configuration file. Raises
ConfigParser exceptions if the section or key are invalid.
"""
return self.cfg.get(section, key).strip()
def get_auth(self):
if self.get('options', 'prefer_token').lower() == 'true':
return requests.auth.HTTPBasicAuth(self.get('auth', 'api_token'),
'api_token')
else:
return requests.auth.HTTPBasicAuth(self.get('auth', 'username'),
self.get('auth', 'password'))
#----------------------------------------------------------------------------
# DateAndTime
#----------------------------------------------------------------------------
class DateAndTime(object):
"""
Singleton date and time functions. Mostly utility functions. All
the timezone and datetime functionality is localized here.
"""
__metaclass__ = Singleton
def __init__(self):
self.tz = pytz.timezone( Config().get('options', 'timezone') )
def duration_since_epoch(self, dt):
"""
Converts the given localized datetime object to the number of
seconds since the epoch.
"""
return (dt.astimezone(pytz.UTC) - datetime.datetime(1970,1,1,tzinfo=pytz.UTC)).total_seconds()
def duration_str_to_seconds(self, duration_str):
"""
Parses a string of the form [[Hours:]Minutes:]Seconds and returns
the total time in seconds.
"""
elements = duration_str.split(':')
duration = 0
if len(elements) == 3:
duration += int(elements[0]) * 3600
elements = elements[1:]
if len(elements) == 2:
duration += int(elements[0]) * 60
elements = elements[1:]
duration += int(elements[0])
return duration
def elapsed_time(self, seconds, suffixes=['y','w','d','h','m','s'], add_s=False, separator=''):
"""
Takes an amount of seconds and turns it into a human-readable amount
of time.
From http://snipplr.com/view.php?codeview&id=5713
"""
# the formatted time string to be returned
time = []
# the pieces of time to iterate over (days, hours, minutes, etc)
# - the first piece in each tuple is the suffix (d, h, w)
# - the second piece is the length in seconds (a day is 60s * 60m * 24h)
parts = [(suffixes[0], 60 * 60 * 24 * 7 * 52),
(suffixes[1], 60 * 60 * 24 * 7),
(suffixes[2], 60 * 60 * 24),
(suffixes[3], 60 * 60),
(suffixes[4], 60),
(suffixes[5], 1)]
# for each time piece, grab the value and remaining seconds, and add it to
# the time string
for suffix, length in parts:
value = seconds // length
if value > 0:
seconds = seconds % length
time.append('%s%s' % (str(value),
(suffix, (suffix, suffix + 's')[value > 1])[add_s]))
if seconds < 1:
break
return separator.join(time)
def format_time(self, time):
"""
Formats the given datetime object according to the strftime() options
from the configuration file.
"""
format = Config().get('options', 'time_format')
return time.strftime(format)
def last_minute_today(self):
"""
Returns 23:59:59 today as a localized datetime object.
"""
return datetime.datetime.now(self.tz) \
.replace(hour=23, minute=59, second=59, microsecond=0)
def now(self):
"""
Returns "now" as a localized datetime object.
"""
return self.tz.localize( datetime.datetime.now() )
def parse_local_datetime_str(self, datetime_str):
"""
Parses a local datetime string (e.g., "2:00pm") and returns
a localized datetime object.
"""
return self.tz.localize( dateutil.parser.parse(datetime_str) )
def parse_iso_str(self, iso_str):
"""
Parses an ISO 8601 datetime string and returns a localized datetime
object.
"""
return iso8601.parse_date(iso_str).astimezone(self.tz)
def start_of_today(self):
"""
Returns 00:00:00 today as a localized datetime object.
"""
return self.tz.localize(
datetime.datetime.combine( datetime.date.today(), datetime.time.min)
)
def start_of_yesterday(self):
"""
Returns 00:00:00 yesterday as a localized datetime object.
"""
return self.tz.localize(
datetime.datetime.combine( datetime.date.today(), datetime.time.min) -
datetime.timedelta(days=1) # subtract one day from today at midnight
)
#----------------------------------------------------------------------------
# Logger
#----------------------------------------------------------------------------
class Logger(object):
"""
Custom logger class. Created because I got tired of seeing logging message
from all the modules imported here. There's no easy way to limit logging
to this file only.
"""
# Logging levels.
NONE = 0
INFO = 1
DEBUG = 2
# Current level.
level = NONE
@staticmethod
def debug(msg, end="\n"):
"""
Prints msg if the current logging level >= DEBUG.
"""
if Logger.level >= Logger.DEBUG:
print("%s%s" % (msg, end)),
@staticmethod
def info(msg, end="\n"):
"""
Prints msg if the current logging level >= INFO.
"""
if Logger.level >= Logger.INFO:
print("%s%s" % (msg, end)),
#----------------------------------------------------------------------------
# toggl
#----------------------------------------------------------------------------
def toggl(url, method, data=None, headers={'content-type' : 'application/json'}):
"""
Makes an HTTP request to toggl.com. Returns the raw text data received.
"""
try:
if method == 'delete':
r = requests.delete(url, auth=Config().get_auth(), data=data, headers=headers)
elif method == 'get':
r = requests.get(url, auth=Config().get_auth(), data=data, headers=headers)
elif method == 'post':
r = requests.post(url, auth=Config().get_auth(), data=data, headers=headers)
elif method == 'put':
r = requests.post(url, auth=Config().get_auth(), data=data, headers=headers)
else:
raise NotImplementedError('HTTP method "%s" not implemented.' % method)
r.raise_for_status() # raise exception on error
return r.text
except Exception as e:
print('Sent: %s' % data)
print(e)
print(r.text)
#sys.exit(1)
#############################################################################
# _ _ __ __ _ _
# | |_ ___ __ _ __ _| | | \/ | ___ __| | ___| |___
# | __/ _ \ / _` |/ _` | | | |\/| |/ _ \ / _` |/ _ \ / __|
# | || (_) | (_| | (_| | | | | | | (_) | (_| | __/ \__ \
# \__\___/ \__, |\__, |_| |_| |_|\___/ \__,_|\___|_|___/
# |___/ |___/
#############################################################################
#----------------------------------------------------------------------------
# ClientList
#----------------------------------------------------------------------------
class ClientList(object):
"""
A singleton list of clients. A "client object" is a set of properties
as documented at
https://github.com/toggl/toggl_api_docs/blob/master/chapters/clients.md
"""
__metaclass__ = Singleton
def __init__(self):
"""
Fetches the list of clients from toggl.
"""
result = toggl("%s/clients" % TOGGL_URL, 'get')
self.client_list = json.loads(result)
def __iter__(self):
"""
Start iterating over the clients.
"""
self.iter_index = 0
return self
def next(self):
"""
Returns the next client.
"""
if self.iter_index >= len(self.client_list):
raise StopIteration
else:
self.iter_index += 1
return self.client_list[self.iter_index-1]
def find_by_name(self, client_name, workspace_name=''):
"""
Check if client exists in workspace
"""
workspace = WorkspaceList().find_by_name(workspace_name)
if(workspace):
for client in self.client_list:
if client['name'] == client_name and client['wid'] == workspace['id']:
return client
return None
def find_by_id(self, cid, workspace_name=''):
"""
Check if client exists in workspace
"""
workspace = WorkspaceList().find_by_name(workspace_name)
if(workspace):
for client in self.client_list:
if client['id'] == cid and client['wid'] == workspace['id']:
return client
return None
def add(self, client_name, workspace_name):
"""
Adds a new client to workspace.
"""
workspace = WorkspaceList().find_by_name(workspace_name)
if(workspace):
wid = workspace['id']
data = {'client':{ 'name': client_name, 'wid': wid }}
toggl("%s/clients" % TOGGL_URL, "post", json.dumps(data))
self.__init__()
def __str__(self):
"""
Formats the list of clients as a string.
"""
s = ""
for client in self.client_list:
s = s + "%s\n" % client['name']
return s.rstrip().encode('utf-8') # strip trailing \n
#----------------------------------------------------------------------------
# WorkspaceList
#----------------------------------------------------------------------------
class WorkspaceList(six.Iterator):
"""
A singleton list of workspace. A workspace object is a dictionary as
documented at
https://github.com/toggl/toggl_api_docs/blob/master/chapters/workspaces.md
"""
__metaclass__ = Singleton
def __init__(self):
"""
Fetches the list of workspaces from toggl.
"""
result = toggl("%s/workspaces" % TOGGL_URL, "get")
self.workspace_list = json.loads(result)
def find_by_id(self, wid):
"""
Returns the workspace object with the given id, or None.
"""
for workspace in self:
if workspace['id'] == wid:
return workspace
return None
def find_by_name(self, name_prefix):
"""
Returns the workspace object with the given name (or prefix), or None.
"""
for workspace in self:
if workspace['name'].startswith(name_prefix):
return workspace
return None
def __iter__(self):
"""
Start iterating over the workspaces.
"""
self.iter_index = 0
return self
def __next__(self):
"""
Returns the next workspace.
"""
if self.iter_index >= len(self.workspace_list):
raise StopIteration
else:
self.iter_index += 1
return self.workspace_list[self.iter_index-1]
def __str__(self):
"""Formats the project list as a string."""
s = ""
for workspace in self:
s = s + ":%s\n" % workspace['name']
return s.rstrip() # strip trailing \n
#----------------------------------------------------------------------------
# ProjectList
#----------------------------------------------------------------------------
class ProjectList(six.Iterator):
"""
A singleton list of projects. A "project object" is a dictionary as
documented at
https://github.com/toggl/toggl_api_docs/blob/master/chapters/projects.md
"""
__metaclass__ = Singleton
def __init__(self, workspace_name = None):
self.fetch(workspace_name)
def fetch(self, workspace_name = None):
"""
Fetches the list of projects from toggl.
"""
wid = None
if workspace_name is not None:
self.workspace = WorkspaceList().find_by_name(workspace_name)
if self.workspace is not None:
wid = self.workspace["id"]
if wid is None:
wid = User().get('default_wid')
self.workspace = WorkspaceList().find_by_id(wid)
self.fetch_by_wid(wid)
def fetch_by_wid(self, wid):
result = toggl("%s/workspaces/%s/projects" % (TOGGL_URL, wid), 'get')
self.project_list = json.loads(result)
def find_by_id(self, pid):
"""
Returns the project object with the given id, or None.
"""
for project in self:
if project['id'] == pid:
return project
return None
def find_by_name(self, name_prefix):
"""
Returns the project object with the given name (or prefix), or None.
"""
for project in self:
if project['name'].startswith(name_prefix):
return project
return None
def __iter__(self):
"""
Start iterating over the projects.
"""
self.iter_index = 0
return self
def __next__(self):
"""
Returns the next project.
"""
if self.iter_index >= len(self.project_list):
raise StopIteration
else:
self.iter_index += 1
return self.project_list[self.iter_index-1]
def add(self, project_name, client_name):
"""
Adds a new project for a client.
"""
client = ClientList().find_by_name(client_name, self.workspace['name'])
if(client):
wid = self.workspace['id']
cid = client['id']
data = {'project':{
'name': project_name,
'wid': wid,
'cid': cid
}
}
toggl("%s/projects" % TOGGL_URL, "post", json.dumps(data))
self.fetch_by_wid(wid)
def delete(self, pid):
"""
Delete a project from the server.
"""
url = "%s/projects/%s" % (TOGGL_URL, pid)
toggl(url, 'delete')
def __str__(self):
"""Formats the project list as a string."""
s = ""
clients = ClientList()
for project in self:
client_name = ''
if 'cid' in project:
for client in clients:
if project['cid'] == client['id']:
client_name = " - %s" % client['name']
s = s + ":%s @%s%s\n" % (self.workspace['name'], project['name'], client_name)
return s.rstrip() # strip trailing \n
#----------------------------------------------------------------------------
# TimeEntry
#----------------------------------------------------------------------------
class TimeEntry(object):
"""
Represents a single time entry.
NB: If duration is negative, it represents the amount of elapsed time
since the epoch. It's not well documented, but toggl expects this duration
to be in UTC.
"""
def __init__(self, description=None, start_time=None, stop_time=None,
duration=None, workspace_name = None, project_name=None,
data_dict=None):
"""
Constructor. None of the parameters are required at object creation,
but the object is validated before data is sent to toggl.
* description(str) is the optional time entry description.
* start_time(datetime) is the optional time this entry started.
* stop_time(datetime) is the optional time this entry ended.
* duration(int) is the optional duration, in seconds.
* project_name(str) is the optional name of the project without
the '@' prefix.
* data_dict is an optional dictionary created from a JSON-encoded time
entry from toggl. If this parameter is used to initialize the object,
its values will supercede any other constructor parameters.
"""
# All toggl data is stored in the "data" dictionary.
self.data = {}
if description is not None:
self.data['description'] = description
if start_time is not None:
self.data['start'] = start_time.isoformat()
if stop_time is not None:
self.data['stop'] = stop_time.isoformat()
if workspace_name is not None:
workspace = WorkspaceList().find_by_name(workspace_name)
if workspace == None:
raise RuntimeError("Workspace '%s' not found." % workspace_name)
self.data['wid'] = workspace['id']
if project_name is not None:
project = ProjectList(workspace_name).find_by_name(project_name)
if project == None:
raise RuntimeError("Project '%s' not found." % project_name)
self.data['pid'] = project['id']
if duration is not None:
self.data['duration'] = duration
# If we have a dictionary of data, use it to initialize this.
if data_dict is not None:
self.data = data_dict
self.data['created_with'] = 'toggl-cli'
self.localized_start_datetime = DateAndTime().parse_iso_str(self.get('start'))
self.workspace = WorkspaceList().find_by_id(self.data['wid'])
if self.data and self.data.has_key('pid'):
self.project = ProjectList(self.workspace['name']).find_by_id(self.data['pid'])
else:
self.project = None
self.duration = datetime.timedelta(seconds=int(self.data['duration']))
def add(self):
"""
Adds this time entry as a completed entry.
"""
self.validate()
toggl("%s/time_entries" % TOGGL_URL, "post", self.json())
def continue_entry(self, continued_at=None):
"""
Continues an existing entry.
"""
create = Config().get('options', 'continue_creates').lower() == 'true'
# Was the entry started today or earlier than today?
start_time = DateAndTime().parse_iso_str( self.get('start') )
if create or start_time <= DateAndTime().start_of_today():
# Entry was from a previous day. Create a new entry from this
# one, resetting any identifiers or time data.
new_entry = TimeEntry()
new_entry.data = self.data.copy()
new_entry.set('at', None)
new_entry.set('created_with', 'toggl-cli')
new_entry.set('duration', None)
new_entry.set('duronly', False)
new_entry.set('guid', None)
new_entry.set('id', None)
if (continued_at):
new_entry.set('start', continued_at.isoformat())
else:
new_entry.set('start', None)
new_entry.set('stop', None)
new_entry.set('uid', None)
new_entry.start()
else:
# To continue an entry from today, set duration to
# 0 - (current_time - duration).
now = DateAndTime().duration_since_epoch( DateAndTime().now() )
duration = ((continued_at or DateAndTime().now()) - DateAndTime().now()).total_seconds()
self.data['duration'] = 0 - (now - int(self.data['duration'])) - duration
self.data['duronly'] = True # ignore start/stop times from now on
toggl("%s/time_entries/%s" % (TOGGL_URL, self.data['id']), 'put', data=self.json())
Logger.debug('Continuing entry %s' % self.json())
def delete(self):
"""
Deletes this time entry from the server.
"""
if not self.has('id'):
raise Exception("Time entry must have an id to be deleted.")
url = "%s/time_entries/%s" % (TOGGL_URL, self.get('id'))
toggl(url, 'delete')
def get(self, prop):
"""
Returns the given toggl time entry property as documented at
https://github.com/toggl/toggl_api_docs/blob/master/chapters/time_entries.md
or None, if the property isn't set.
"""
if prop in self.data:
return self.data[prop]
else:
return None
def has(self, prop):
"""
Returns True if this time entry has the given property and it's not
None, False otherwise.
"""
return prop in self.data and self.data[prop] is not None
def json(self):
"""
Returns a JSON dump of this entire object as toggl payload.
"""
return '{"time_entry": %s}' % json.dumps(self.data)
def normalized_duration(self):
"""
Returns a "normalized" duration. If the native duration is positive,
it is simply returned. If negative, we return current_time + duration
(the actual amount of seconds this entry has been running). If no
duration is set, raises an exception.
"""
if 'duration' not in self.data:
raise Exception('Time entry has no "duration" property')
if self.data['duration'] > 0:
return int(self.data['duration'])
else:
return time.time() + int(self.data['duration'])
def set(self, prop, value):
"""
Sets the given toggl time entry property to the given value. If
value is None, the property is removed from this time entry.
Properties are documented at
https://github.com/toggl/toggl_api_docs/blob/master/chapters/time_entries.md
"""
if value is not None:
self.data[prop] = value
elif prop in self.data:
self.data.pop(prop)
def start(self):
"""
Starts this time entry by telling toggl. If this entry doesn't have
a start time yet, it is set to now. duration is set to
0-start_time.
"""
if self.has('start'):
start_time = DateAndTime().parse_iso_str(self.get('start'))
self.set('duration', 0-DateAndTime().duration_since_epoch(start_time))
self.validate()
toggl("%s/time_entries" % TOGGL_URL, "post", self.json())
else:
# 'start' is ignored by 'time_entries/start' endpoint. We define it
# to keep consinstency with toggl server
self.data['start'] = DateAndTime().now().isoformat()
toggl("%s/time_entries/start" % TOGGL_URL, "post", self.json())
Logger.debug('Started time entry: %s' % self.json())
def stop(self, stop_time=None):
"""
Stops this entry. Sets the stop time at the datetime given, calculates
a duration, then updates toggl.
stop_time(datetime) is an optional datetime when this entry stopped. If
not given, then stops the time entry now.
"""
Logger.debug('Stopping entry %s' % self.json())
self.validate(['description'])
if int(self.data['duration']) >= 0:
raise Exception("toggl: time entry is not currently running.")
if 'id' not in self.data:
raise Exception("toggl: time entry must have an id.")
if stop_time is None:
stop_time = DateAndTime().now()
self.set('stop', stop_time.isoformat())
self.set('duration', \
DateAndTime().duration_since_epoch(stop_time) + int(self.get('duration')))
toggl("%s/time_entries/%d" % (TOGGL_URL, self.get('id')), 'put', self.json())
def __str__(self):
"""
Returns a human-friendly string representation of this time entry.
"""
if self.data['duration'] > 0:
is_running = ' '
else:
is_running = '* '
if 'pid' in self.data:
project = ProjectList().find_by_id(self.data['pid'])
if project is not None:
project_name = " @%s " % project['name']
elif 'wid' in self.data:
ProjectList().fetch_by_wid(self.data['wid']);
project_name = " @%s " % ProjectList().find_by_id(self.data['pid'])['name']
else:
project_name = " "
else:
project_name = " "
s = "%s%s%s%s" % (is_running, self.data.get('description'), project_name,
DateAndTime().elapsed_time(int(self.normalized_duration())) \
)
if VERBOSE:
s += " [%s]" % self.data['id']
return s
def validate(self, exclude=[]):
"""
Ensure this time entry contains the minimum information required
by toggl, as well as passing some basic sanity checks. If not,
an exception is raised.
* toggl requires start, duration, and created_with.
* toggl doesn't require a description, but we do.
"""
required = [ 'start', 'duration', 'description', 'created_with' ];
for prop in required:
if not self.has(prop) and prop not in exclude:
Logger.debug(self.json())
raise Exception("toggl: time entries must have a '%s' property." % prop)
return True
#----------------------------------------------------------------------------
# TimeEntryList
#----------------------------------------------------------------------------
class TimeEntryList(object):
"""
A singleton list of recent TimeEntry objects.
"""
__metaclass__ = Singleton
def __init__(self, start_date=None, end_date=None):
"""
Fetches time entry data from toggl.
"""
# Default period 00:00:00 yesterday to 23:59:59 today.
self.start_date = DateAndTime().start_of_yesterday()
self.end_date = DateAndTime().last_minute_today()
# User specified period
if start_date:
self.start_date = DateAndTime().parse_iso_str(start_date)
if end_date:
self.end_date = DateAndTime().parse_iso_str(end_date)
self.reload()
def __iter__(self):
"""
Start iterating over the time entries.
"""
self.iter_index = 0
return self
def find_by_description(self, description):
"""
Searches the list of entries for the one matching the given
description, or return None. If more than one entry exists
with a matching description, the most recent one is
returned.
"""
for entry in reversed(self.time_entries):
if entry.get('description') == description:
return entry
return None
def get_latest(self):
"""
Returns the latest entry
"""
if len(self.time_entries) == 0:
return None
return self.time_entries[len(self.time_entries)-1]
def next(self):
"""
Returns the next time entry object.
"""
if self.iter_index >= len(self.time_entries):
raise StopIteration
else:
self.iter_index += 1
return self.time_entries[self.iter_index-1]
def now(self):
"""
Returns the current time entry object or None.
"""
for entry in self:
if int(entry.get('duration')) < 0:
return entry
return None
def reload(self):
"""
Force reloading time entry data from the server. Returns self for
method chaining.
"""
# Fetch time entries.
url = "%s/time_entries?start_date=%s&end_date=%s" % \
(TOGGL_URL, urllib.parse.quote(self.start_date.isoformat('T')), \
urllib.parse.quote(self.end_date.isoformat('T')))
Logger.debug(url)
entries = json.loads( toggl(url, 'get') )
# Build a list of entries.
self.time_entries = []
for entry in entries:
te = TimeEntry(data_dict=entry)
Logger.debug(te.json())
Logger.debug('---')
self.time_entries.append(te)
# Sort the list by start time.
sorted(self.time_entries, key=lambda entry: entry.data['start'])
return self
def __str__(self):
"""
Returns a human-friendly list of recent time entries.
"""
# Sort the time entries into buckets based on "Month Day" of the entry.
days = { }
for entry in self.time_entries:
start_time = DateAndTime().parse_iso_str(entry.get('start')).strftime("%Y-%m-%d")
if start_time not in days:
days[start_time] = []
days[start_time].append(entry)
# For each day, print the entries, and sum the times.
s = ""
for date in sorted(days.keys()):
s += date + "\n"
duration = 0
for entry in days[date]:
s += str(entry) + "\n"
duration += entry.normalized_duration()
s += " (%s)\n" % DateAndTime().elapsed_time(int(duration))
return s.rstrip() # strip trailing \n
#----------------------------------------------------------------------------
# User
#----------------------------------------------------------------------------
class User(object):
"""
Singleton toggl user data.
"""
__metaclass__ = Singleton
def __init__(self):
"""
Fetches user data from toggl.
"""
result = toggl("%s/me" % TOGGL_URL, 'get')
result_dict = json.loads(result)
# Results come back in two parts. 'since' is how long the user has
# had their toggl account. 'data' is a dictionary of all the other
# user data.
self.data = result_dict['data']
self.data['since'] = result_dict['since']
def get(self, prop):
"""
Return the given toggl user property. User properties are
documented at https://github.com/toggl/toggl_api_docs/blob/master/chapters/users.md
"""
return self.data[prop]
#############################################################################
# ____ _ _ _
# / ___|___ _ __ ___ _ __ ___ __ _ _ __ __| | | | (_)_ __ ___
# | | / _ \| '_ ` _ \| '_ ` _ \ / _` | '_ \ / _` | | | | | '_ \ / _ \
# | |__| (_) | | | | | | | | | | | (_| | | | | (_| | | |___| | | | | __/
# \____\___/|_| |_| |_|_| |_| |_|\__,_|_| |_|\__,_| |_____|_|_| |_|\___|
#
#############################################################################
#----------------------------------------------------------------------------