-
Notifications
You must be signed in to change notification settings - Fork 4
/
gcalcli
executable file
·2652 lines (2167 loc) · 96.2 KB
/
gcalcli
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
# ** The MIT License **
#
# Copyright (c) 2007 Eric Davis (aka Insanum)
#
# 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.
#
# Dude... just buy us a beer. :-)
#
# XXX Todo/Cleanup XXX
# threading is currently broken when getting event list
# if threading works then move pageToken processing from GetAllEvents to thread
# support different types of reminders plus multiple ones (popup, sms, email)
# add caching, should be easy (dump all calendar JSON data to file)
# add support for multiline description input in the 'add' and 'edit' commands
# maybe add support for freebusy ?
#############################################################################
# #
# ( ( ( #
# ( ( ( )\ ) ( )\ ) )\ ) #
# )\ ) )\ )\ (()/( )\ (()/( (()/( #
# (()/( (((_)((((_)( /(_))(((_) /(_)) /(_)) #
# /(_))_ )\___ )\ _ )\ (_)) )\___ (_)) (_)) #
# (_)) __|((/ __|(_)_\(_)| | ((/ __|| | |_ _| #
# | (_ | | (__ / _ \ | |__ | (__ | |__ | | #
# \___| \___|/_/ \_\ |____| \___||____||___| #
# #
# Author: Eric Davis <http://www.insanum.com> #
# Brian Hartvigsen <http://github.com/tresni> #
# Home: https://github.com/insanum/gcalcli #
# #
# Requirements: #
# - Python 2 #
# http://www.python.org #
# - Google APIs Client Library for Python 2 #
# https://developers.google.com/api-client-library/python #
# - dateutil Python 2 module #
# http://www.labix.org/python-dateutil #
# #
# Optional: #
# - vobject Python module (needed for importing ics/vcal files) #
# http://vobject.skyhouseconsulting.com #
# - parsedatetime Python module (needed for fuzzy date parsing) #
# https://github.com/bear/parsedatetime #
# #
# Everything you need to know (Google API Calendar v3): http://goo.gl/HfTGQ #
# #
#############################################################################
__program__ = 'gcalcli'
__version__ = 'v3.4.0'
__author__ = 'Eric Davis, Brian Hartvigsen'
__doc__ = '''
Usage:
%s [options] command [command args or options]
Commands:
list list all calendars
search <text> [start] [end]
search for events within an optional time period
- case insensitive search terms to find events that
match these terms in any field, like traditional
Google search with quotes, exclusion, etc.
- for example to get just games: "soccer -practice"
- [start] and [end] use the same formats as agenda
agenda [start] [end] get an agenda for a time period
- start time default is 12am today
- end time default is 5 days from start
- example time strings:
'9/24/2007'
'24/09/2007'
'24/9/07'
'Sep 24 2007 3:30pm'
'2007-09-24T15:30'
'2007-09-24T15:30-8:00'
'20070924T15'
'8am'
calw <weeks> [start] get a week based agenda in a nice calendar format
- weeks is the number of weeks to display
- start time default is beginning of this week
- note that all events for the week(s) are displayed
calm [start] get a month agenda in a nice calendar format
- start time default is the beginning of this month
- note that all events for the month are displayed
and only one month will be displayed
quick <text> quick add an event to a calendar
- a single --calendar must specified
- the "--details url" option will show the event link
- example text:
'Dinner with Eric 7pm tomorrow'
'5pm 10/31 Trick or Treat'
add add a detailed event to a calendar
- a single --calendar must specified
- the "--details url" option will show the event link
- example:
gcalcli --calendar 'Eric Davis'
--title 'Analysis of Algorithms Final'
--where UCI
--when '12/14/2012 10:00'
--who '[email protected]'
--who '[email protected]'
--duration 60
--description 'It is going to be hard!'
--reminder 30
add
delete <text> [start] [end]
delete event(s) within the optional time period
- case insensitive search terms to find and delete
events, just like the 'search' command
- deleting is interactive
use the --iamaexpert option to auto delete
THINK YOU'RE AN EXPERT? USE AT YOUR OWN RISK!!!
- use the --details options to show event details
- [start] and [end] use the same formats as agenda
edit <text> edit event(s)
- case insensitive search terms to find and edit
events, just like the 'search' command
- editing is interactive
import [file] import an ics/vcal file to a calendar
- a single --calendar must specified
- if a file is not specified then the data is read
from standard input
- if -v is given then each event in the file is
displayed and you're given the option to import
or skip it, by default everything is imported
quietly without any interaction
- if -d is given then each event in the file is
displayed and is not imported, a --calendar does
not need to be specified for this option
remind <mins> <command> execute command if event occurs within <mins>
minutes time ('%%s' in <command> is replaced with
event start time and title text)
- <mins> default is 10
- default command:
'notify-send -u critical -a gcalcli %%s'
'''
__API_CLIENT_ID__ = '232867676714.apps.googleusercontent.com'
__API_CLIENT_SECRET__ = '3tZSxItw6_VnZMezQwC8lUqy'
# These are standard libraries and should never fail
import sys
import os
import re
import shlex
import time
import calendar
import locale
import textwrap
import signal
import json
import random
from datetime import datetime, timedelta, date
from unicodedata import east_asian_width
# Required 3rd party libraries
try:
from dateutil.tz import tzlocal
from dateutil.parser import parse
import gflags
import httplib2
from apiclient.discovery import build
from apiclient.errors import HttpError
from oauth2client.file import Storage
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.tools import run
except ImportError as e:
print("ERROR: Missing module - %s" % e.args[0])
sys.exit(1)
import sys
if sys.version_info[0] >= 3:
unicode = str
# cPickle is a standard library, but in case someone did something really
# dumb, fall back to pickle. If that's not their, your python is fucked
try:
import cPickle as pickle
except ImportError:
import pickle
# If they have parsedatetime, we'll use it for fuzzy datetime comparison. If
# not, we just return a fake failure every time and use only dateutil.
try:
from parsedatetime import parsedatetime
except:
class parsedatetime:
class Calendar:
def parse(self, string):
return ([], 0)
#locale.setlocale(locale.LC_ALL, "")
def stringToUnicode(string):
# if string:
if isinstance(string, str):
return string
else:
return u''
def stringFromUnicode(string):
return string.encode(locale.getlocale()[1] or
locale.getpreferredencoding(False) or
"UTF-8", "replace")
def Version():
sys.stdout.write(__program__ + ' ' + __version__ + ' (' + __author__ + ')\n')
sys.exit(1)
def Usage(expanded=False):
sys.stdout.write(__doc__ % sys.argv[0])
if expanded:
print(FLAGS.MainModuleHelp())
sys.exit(1)
class CLR:
useColor = True
conky = False
def __str__(self):
return self.color if self.useColor else ""
class CLR_NRM(CLR):
color = "\033[0m"
class CLR_BLK(CLR):
color = "\033[0;30m"
class CLR_BRBLK(CLR):
color = "\033[30;1m"
class CLR_RED(CLR):
color = "\033[0;31m"
class CLR_BRRED(CLR):
color = "\033[31;1m"
class CLR_GRN(CLR):
color = "\033[0;32m"
class CLR_BRGRN(CLR):
color = "\033[32;1m"
class CLR_YLW(CLR):
color = "\033[0;33m"
class CLR_BRYLW(CLR):
color = "\033[33;1m"
class CLR_BLU(CLR):
color = "\033[0;34m"
class CLR_BRBLU(CLR):
color = "\033[34;1m"
class CLR_MAG(CLR):
color = "\033[0;35m"
class CLR_BRMAG(CLR):
color = "\033[35;1m"
class CLR_CYN(CLR):
color = "\033[0;36m"
class CLR_BRCYN(CLR):
color = "\033[36;1m"
class CLR_WHT(CLR):
color = "\033[0;37m"
class CLR_BRWHT(CLR):
color = "\033[37;1m"
def SetConkyColors():
# XXX these colors should be configurable
CLR.conky = True
CLR_NRM.color = ""
CLR_BLK.color = "${color black}"
CLR_BRBLK.color = "${color black}"
CLR_RED.color = "${color red}"
CLR_BRRED.color = "${color red}"
CLR_GRN.color = "${color green}"
CLR_BRGRN.color = "${color green}"
CLR_YLW.color = "${color yellow}"
CLR_BRYLW.color = "${color yellow}"
CLR_BLU.color = "${color blue}"
CLR_BRBLU.color = "${color blue}"
CLR_MAG.color = "${color magenta}"
CLR_BRMAG.color = "${color magenta}"
CLR_CYN.color = "${color cyan}"
CLR_BRCYN.color = "${color cyan}"
CLR_WHT.color = "${color white}"
CLR_BRWHT.color = "${color white}"
class ART:
useArt = True
fancy = ''
plain = ''
def __str__(self):
return self.fancy if self.useArt else self.plain
class ART_HRZ(ART):
fancy = '\033(0\x71\033(B'
plain = '-'
class ART_VRT(ART):
fancy = '\033(0\x78\033(B'
plain = '|'
class ART_LRC(ART):
fancy = '\033(0\x6A\033(B'
plain = '+'
class ART_URC(ART):
fancy = '\033(0\x6B\033(B'
plain = '+'
class ART_ULC(ART):
fancy = '\033(0\x6C\033(B'
plain = '+'
class ART_LLC(ART):
fancy = '\033(0\x6D\033(B'
plain = '+'
class ART_CRS(ART):
fancy = '\033(0\x6E\033(B'
plain = '+'
class ART_LTE(ART):
fancy = '\033(0\x74\033(B'
plain = '+'
class ART_RTE(ART):
fancy = '\033(0\x75\033(B'
plain = '+'
class ART_BTE(ART):
fancy = '\033(0\x76\033(B'
plain = '+'
class ART_UTE(ART):
fancy = '\033(0\x77\033(B'
plain = '+'
def PrintErrMsg(msg):
PrintMsg(CLR_BRRED(), msg)
def PrintMsg(color, msg):
if isinstance(msg, unicode):
msg = stringFromUnicode(msg)
if CLR.useColor:
sys.stdout.write(str(color))
sys.stdout.write(msg)
sys.stdout.write(str(CLR_NRM()))
else:
sys.stdout.write(msg)
def DebugPrint(msg):
return
PrintMsg(CLR_YLW(), msg)
def dprint(obj):
try:
from pprint import pprint
pprint(obj)
except ImportError:
print(obj)
class DateTimeParser:
def __init__(self):
self.pdtCalendar = parsedatetime.Calendar()
def fromString(self, eWhen):
defaultDateTime = datetime.now(tzlocal()).replace(hour=0,
minute=0,
second=0,
microsecond=0)
try:
eTimeStart = parse(eWhen, default=defaultDateTime)
except:
struct, result = self.pdtCalendar.parse(eWhen)
if not result:
raise ValueError("Date and time is invalid")
eTimeStart = datetime.fromtimestamp(time.mktime(struct), tzlocal())
return eTimeStart
def DaysSinceEpoch(dt):
# Because I hate magic numbers
__DAYS_IN_SECONDS__ = 24 * 60 * 60
return calendar.timegm(dt.timetuple()) / __DAYS_IN_SECONDS__
def GetTimeFromStr(eWhen, eDuration=0):
dtp = DateTimeParser()
try:
eTimeStart = dtp.fromString(eWhen)
except:
PrintErrMsg('Date and time is invalid!\n')
sys.exit(1)
if FLAGS.allday:
try:
eTimeStop = eTimeStart + timedelta(days=float(eDuration))
except:
PrintErrMsg('Duration time (days) is invalid\n')
sys.exit(1)
sTimeStart = eTimeStart.date().isoformat()
sTimeStop = eTimeStop.date().isoformat()
else:
try:
eTimeStop = eTimeStart + timedelta(minutes=float(eDuration))
except:
PrintErrMsg('Duration time (minutes) is invalid\n')
sys.exit(1)
sTimeStart = eTimeStart.isoformat()
sTimeStop = eTimeStop.isoformat()
return sTimeStart, sTimeStop
def ParseReminder(rem):
matchObj = re.match(r'^(\d+)([wdhm]?)(?:\s+(popup|email|sms))?$', rem)
if not matchObj:
PrintErrMsg('Invalid reminder: ' + rem + '\n')
sys.exit(1)
n = int(matchObj.group(1))
t = matchObj.group(2)
m = matchObj.group(3)
if t == 'w':
n = n * 7 * 24 * 60
elif t == 'd':
n = n * 24 * 60
elif t == 'h':
n = n * 60
if not m:
m = 'popup'
return n, m
class gcalcli:
cache = {}
allCals = []
allEvents = []
cals = []
now = datetime.now(tzlocal())
agendaLength = 5
maxRetries = 5
authHttp = None
calService = None
urlService = None
command = 'notify-send -u critical -a gcalcli %s'
dateParser = DateTimeParser()
ACCESS_OWNER = 'owner'
ACCESS_WRITER = 'writer'
ACCESS_READER = 'reader'
ACCESS_FREEBUSY = 'freeBusyReader'
UNIWIDTH = {'W': 2, 'F': 2, 'N': 1, 'Na': 1, 'H': 1, 'A': 1}
def __init__(self,
calNames=[],
calNameColors=[],
military=False,
detailCalendar=False,
detailLocation=False,
detailAttendees=False,
detailAttachments=False,
detailLength=False,
detailReminders=False,
detailDescr=False,
detailDescrWidth=80,
detailUrl=None,
detailEmail=False,
ignoreStarted=False,
ignoreDeclined=False,
calWidth=10,
calMonday=False,
calOwnerColor=CLR_CYN(),
calWriterColor=CLR_GRN(),
calReaderColor=CLR_MAG(),
calFreeBusyColor=CLR_NRM(),
dateColor=CLR_YLW(),
nowMarkerColor=CLR_BRRED(),
borderColor=CLR_WHT(),
tsv=False,
refreshCache=False,
useCache=True,
configFolder=None,
client_id=__API_CLIENT_ID__,
client_secret=__API_CLIENT_SECRET__,
defaultReminders=False,
allDay=False):
self.military = military
self.ignoreStarted = ignoreStarted
self.ignoreDeclined = ignoreDeclined
self.calWidth = calWidth
self.calMonday = calMonday
self.tsv = tsv
self.refreshCache = refreshCache
self.useCache = useCache
self.defaultReminders = defaultReminders
self.allDay = allDay
self.detailCalendar = detailCalendar
self.detailLocation = detailLocation
self.detailLength = detailLength
self.detailReminders = detailReminders
self.detailDescr = detailDescr
self.detailDescrWidth = detailDescrWidth
self.detailUrl = detailUrl
self.detailAttendees = detailAttendees
self.detailAttachments = detailAttachments
self.detailEmail = detailEmail
self.calOwnerColor = calOwnerColor
self.calWriterColor = calWriterColor
self.calReaderColor = calReaderColor
self.calFreeBusyColor = calFreeBusyColor
self.dateColor = dateColor
self.nowMarkerColor = nowMarkerColor
self.borderColor = borderColor
self.configFolder = configFolder
self.client_id = client_id
self.client_secret = client_secret
self._GetCached()
if len(calNames):
# Changing the order of this and the `cal in self.allCals` loop
# is necessary for the matching to actually be sane (ie match
# supplied name to cached vs matching cache against supplied names)
for i in range(len(calNames)):
matches = []
for cal in self.allCals:
# For exact match, we should match only 1 entry and accept
# the first entry. Should honor access role order since
# it happens after _GetCached()
if calNames[i] == cal['summary']:
# This makes sure that if we have any regex matches
# that we toss them out in favor of the specific match
matches = [cal]
cal['colorSpec'] = calNameColors[i]
break
# Otherwise, if the calendar matches as a regex, append
# it to the list of potential matches
elif re.search(calNames[i], cal['summary'], flags=re.I):
matches.append(cal)
cal['colorSpec'] = calNameColors[i]
# Add relevant matches to the list of calendars we want to
# operate against
self.cals += matches
else:
self.cals = self.allCals
@staticmethod
def _LocalizeDateTime(dt):
if not hasattr(dt, 'tzinfo'):
return dt
if dt.tzinfo is None:
return dt.replace(tzinfo=tzlocal())
else:
return dt.astimezone(tzlocal())
def _RetryWithBackoff(self, method):
for n in range(0, self.maxRetries):
try:
return method.execute()
except(HttpError, e):
error = json.loads(e.content)
if error.get('code') == '403' and \
error.get('errors')[0].get('reason') \
in ['rateLimitExceeded', 'userRateLimitExceeded']:
time.sleep((2 ** n) + random.random())
else:
raise
return None
def _GoogleAuth(self):
if not self.authHttp:
if self.configFolder:
storage = Storage(os.path.expanduser("%s/oauth" %
self.configFolder))
else:
storage = Storage(os.path.expanduser('~/.gcalcli_oauth'))
credentials = storage.get()
if credentials is None or credentials.invalid:
credentials = run(
OAuth2WebServerFlow(
client_id=self.client_id,
client_secret=self.client_secret,
scope=['https://www.googleapis.com/auth/calendar',
'https://www.googleapis.com/auth/urlshortener'],
user_agent=__program__ + '/' + __version__),
storage)
self.authHttp = credentials.authorize(httplib2.Http())
return self.authHttp
def _CalService(self):
if not self.calService:
self.calService = \
build(serviceName='calendar',
version='v3',
http=self._GoogleAuth())
return self.calService
def _UrlService(self):
if not self.urlService:
self._GoogleAuth()
self.urlService = \
build(serviceName='urlshortener',
version='v1',
http=self._GoogleAuth())
return self.urlService
def _GetCached(self):
if self.configFolder:
cacheFile = os.path.expanduser("%s/cache" % self.configFolder)
else:
cacheFile = os.path.expanduser('~/.gcalcli_cache')
if self.refreshCache:
try:
os.remove(cacheFile)
except OSError:
pass
# fall through
self.cache = {}
self.allCals = []
if self.useCache:
# note that we need to use pickle for cache data since we stuff
# various non-JSON data in the runtime storage structures
try:
with open(cacheFile, 'rb') as _cache_:
self.cache = pickle.load(_cache_)
self.allCals = self.cache['allCals']
# XXX assuming data is valid, need some verification check here
return
except IOError:
pass
# fall through
calList = self._RetryWithBackoff(
self._CalService().calendarList().list())
while True:
for cal in calList['items']:
self.allCals.append(cal)
pageToken = calList.get('nextPageToken')
if pageToken:
calList = self._RetryWithBackoff(
self._CalService().calendarList().list(pageToken=pageToken))
else:
break
# gcalcli defined way to order calendars
order = {self.ACCESS_OWNER: 1,
self.ACCESS_WRITER: 2,
self.ACCESS_READER: 3,
self.ACCESS_FREEBUSY: 4}
self.allCals.sort(lambda x, y:
cmp(order[x['accessRole']],
order[y['accessRole']]))
if self.useCache:
self.cache['allCals'] = self.allCals
with open(cacheFile, 'wb') as _cache_:
pickle.dump(self.cache, _cache_)
def _ShortenURL(self, url):
if self.detailUrl != "short":
return url
# Note that when authenticated to a google account different shortUrls
# can be returned for the same longUrl. See: http://goo.gl/Ya0A9
shortUrl = self._RetryWithBackoff(
self._UrlService().url().insert(body={'longUrl': url}))
return shortUrl['id']
def _CalendarColor(self, cal):
if cal is None:
return CLR_NRM()
elif 'colorSpec' in cal and cal['colorSpec'] is not None:
return cal['colorSpec']
elif cal['accessRole'] == self.ACCESS_OWNER:
return self.calOwnerColor
elif cal['accessRole'] == self.ACCESS_WRITER:
return self.calWriterColor
elif cal['accessRole'] == self.ACCESS_READER:
return self.calReaderColor
elif cal['accessRole'] == self.ACCESS_FREEBUSY:
return self.calFreeBusyColor
else:
return CLR_NRM()
def _ValidTitle(self, event):
if 'summary' in event and event['summary'].strip():
return event['summary']
else:
return "(No title)"
def _IsAllDay(self, event):
return event['s'].hour == 0 and event['s'].minute == 0 and \
event['e'].hour == 0 and event['e'].minute == 0
def _GetWeekEventStrings(self, cmd, curMonth,
startDateTime, endDateTime, eventList):
weekEventStrings = ['', '', '', '', '', '', '']
nowMarkerPrinted = False
if self.now < startDateTime or self.now > endDateTime:
# now isn't in this week
nowMarkerPrinted = True
for event in eventList:
if cmd == 'calm' and curMonth != event['s'].strftime("%b"):
continue
dayNum = int(event['s'].strftime("%w"))
if self.calMonday:
dayNum -= 1
if dayNum < 0:
dayNum = 6
if event['s'] >= startDateTime and event['s'] < endDateTime:
forceEventColorAsMarker = False
allDay = self._IsAllDay(event)
if not nowMarkerPrinted:
if (DaysSinceEpoch(self.now) <
DaysSinceEpoch(event['s'])):
nowMarkerPrinted = True
weekEventStrings[dayNum - 1] += \
("\n" +
str(self.nowMarkerColor) +
(self.calWidth * '-'))
elif self.now <= event['s']:
# add a line marker before next event
nowMarkerPrinted = True
weekEventStrings[dayNum] += \
("\n" +
str(self.nowMarkerColor) +
(self.calWidth * '-'))
# We don't want to recolor all day events, but ignoring
# them leads to issues where the "now" marker misprints
# into the wrong day. This resolves the issue by skipping
# all day events for specific coloring but not for previous
# or next events
elif self.now >= event['s'] and \
self.now <= event['e'] and \
not allDay:
# line marker is during the event (recolor event)
nowMarkerPrinted = True
forceEventColorAsMarker = True
if allDay:
tmpTimeStr = ''
elif self.military:
tmpTimeStr = event['s'].strftime("%H:%M")
else:
tmpTimeStr = \
event['s'].strftime("%I:%M").lstrip('0') + \
event['s'].strftime('%p').lower()
if forceEventColorAsMarker:
eventColor = self.nowMarkerColor
else:
eventColor = self._CalendarColor(event['gcalcli_cal'])
# newline and empty string are the keys to turn off coloring
weekEventStrings[dayNum] += \
"\n" + \
stringToUnicode(str(eventColor)) + \
stringToUnicode(tmpTimeStr.strip()) + \
" " + \
self._ValidTitle(event).strip()
return weekEventStrings
def _PrintLen(self, string):
# We need to treat everything as unicode for this to actually give
# us the info we want. Date string were coming in as `str` type
# so we convert them to unicode and then check their size. Fixes
# the output issues we were seeing around non-US locale strings
if not isinstance(string, unicode):
string = stringToUnicode(string)
printLen = 0
for tmpChar in string:
printLen += self.UNIWIDTH[east_asian_width(tmpChar)]
return printLen
# return print length before cut, cut index, and force cut flag
def _NextCut(self, string, curPrintLen):
idx = 0
printLen = 0
if not isinstance(string, unicode):
string = stringToUnicode(string)
for tmpChar in string:
if (curPrintLen + printLen) >= self.calWidth:
return (printLen, idx, True)
if tmpChar in (' ', '\n'):
return (printLen, idx, False)
idx += 1
printLen += self.UNIWIDTH[east_asian_width(tmpChar)]
return (printLen, -1, False)
def _GetCutIndex(self, eventString):
printLen = self._PrintLen(eventString)
if printLen <= self.calWidth:
if '\n' in eventString:
idx = eventString.find('\n')
printLen = self._PrintLen(eventString[:idx])
else:
idx = len(eventString)
DebugPrint("------ printLen=%d (end of string)\n" % idx)
return (printLen, idx)
cutWidth, cut, forceCut = self._NextCut(eventString, 0)
DebugPrint("------ cutWidth=%d cut=%d \"%s\"\n" %
(cutWidth, cut, eventString))
if forceCut:
DebugPrint("--- forceCut cutWidth=%d cut=%d\n" % (cutWidth, cut))
return (cutWidth, cut)
DebugPrint("--- looping\n")
while cutWidth < self.calWidth:
DebugPrint("--- cutWidth=%d cut=%d \"%s\"\n" %
(cutWidth, cut, eventString[cut:]))
while cut < self.calWidth and \
cut < printLen and \
eventString[cut] == ' ':
DebugPrint("-> skipping space <-\n")
cutWidth += 1
cut += 1
DebugPrint("--- cutWidth=%d cut=%d \"%s\"\n" %
(cutWidth, cut, eventString[cut:]))
nextCutWidth, nextCut, forceCut = \
self._NextCut(eventString[cut:], cutWidth)
if forceCut:
DebugPrint("--- forceCut cutWidth=%d cut=%d\n" % (cutWidth,
cut))
break
cutWidth += nextCutWidth
cut += nextCut
if eventString[cut] == '\n':
break
DebugPrint("--- loop cutWidth=%d cut=%d\n" % (cutWidth, cut))
return (cutWidth, cut)
def _GraphEvents(self, cmd, startDateTime, count, eventList):
# ignore started events (i.e. events that start previous day and end
# start day)
while (len(eventList) and eventList[0]['s'] < startDateTime):
eventList = eventList[1:]
dayWidthLine = (self.calWidth * str(ART_HRZ()))
topWeekDivider = (str(self.borderColor) +
str(ART_ULC()) + dayWidthLine +
(6 * (str(ART_UTE()) + dayWidthLine)) +
str(ART_URC()) + str(CLR_NRM()))
midWeekDivider = (str(self.borderColor) +
str(ART_LTE()) + dayWidthLine +
(6 * (str(ART_CRS()) + dayWidthLine)) +
str(ART_RTE()) + str(CLR_NRM()))
botWeekDivider = (str(self.borderColor) +
str(ART_LLC()) + dayWidthLine +
(6 * (str(ART_BTE()) + dayWidthLine)) +
str(ART_LRC()) + str(CLR_NRM()))
empty = self.calWidth * ' '
# Get the localized day names... January 1, 2001 was a Monday
dayNames = [date(2001, 1, i + 1).strftime('%A') for i in range(7)]
dayNames = dayNames[6:] + dayNames[:6]
dayHeader = str(self.borderColor) + str(ART_VRT()) + str(CLR_NRM())
for i in range(7):
if self.calMonday:
if i == 6: