GCalCLI

Python

MIT License

Google Calendar CLI

Download (right click, save as, rename as appropriate)

Embed

Tags:

python
  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
#!/usr/bin/python

# $Id: gcalcli 21 2007-10-01 22:58:04Z insanum $

# ** 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.


#
# Home: http://code.google.com/p/gcalcli
#
# Author: Eric Davis <insanum@gmail.com> <http://www.insanum.com>
#
# Requirements:
#  - Python - http://www.python.org
#  - Google's GData Python module - http://code.google.com/p/gdata-python-client
#  - dateutil Python module - http://www.labix.org/python-dateutil
#
# TODO:
#  - import meeting.ics Outlook events ("gcalcli import <file|stdin>")
#  - calendar selection (perform operation against a single calendar)
#  - add (non-quick) events with ability to set reminders, repeat, guests, etc
#  - configurable 'remind' reminders (i.e. 30 mins before event every 5 mins)
#  - daemon mode for 'remind' reminders (working from cached data)
#  - more agenda output formats
#  - cache calendar information (serialize calendar info to file)
#  - rc file support for default colors, login info, etc
#

__username__ = 'shane.mitchell@gmail.com'
__password__ = 'ecfWVwLC21Feb78&'

__program__ = 'gcalcli'
__version__ = 'v1.2'
__author__  = 'Insanum'

import inspect

import sys, os, re, urllib, getopt, shlex, codecs, locale
from gdata.calendar.service import *
from datetime import *
from dateutil.tz import *
from dateutil.parser import *


# for unicode support
sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout);
sys.stdin = codecs.getreader(locale.getpreferredencoding())(sys.stdin);


def Usage():
    sys.stdout.write('''
Usage:

gcalcli [options] command [command args]

 Options:

  --help                    this usage text

  --user <username>         google username

  --pw <password>           password

  --cals=[all,              calendars to work with (default is all calendars)
          default,          - default (your default main calendar)
          owner,            - owner (your owned calendars)
          read,             - read (read only calendars)
          freebusy,         - freebusy (only free/busy info visible)
          contributor]      - contributor (non-owner but able to edit)

  --details                 show all event details (i.e. length, location,
                            reminders, contents)

  --nc                      don't use color sequences

 Commands:

  list                      list all calendars

  search <text>             search for events
                            - only matches whole words

  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'
                               'Sep 24 2007 3:30pm'
                               '2007-09-24T15:30'
                               '2007-09-24T15:30-8:00'
                               '20070924T15'
                               '8am'

  quick <text>              quick add an event to default calendar
                            - example:
                               'Dinner with Eric 7pm tomorrow'
                               '5pm 10/31 Trick or Treat'

  remind <mins> <command>   execute command if event occurs within <mins>
                            minutes time ('%s' in <command> is replaced with
                            event start time and title text)
                            - <minutes> default is 10
                            - default command:
                               'gxmessage -display :0 -center \\
                                          -title "Ding, Ding, Ding!" %s'

''')
    sys.exit(1)


class CLR:

    useColor = True

    def __str__(self):
        if self.useColor: return self.color
        else: return ""

class CLR_NRM(CLR):   color = ""
class CLR_BLK(CLR):   color = ""
class CLR_BRBLK(CLR): color = ""
class CLR_RED(CLR):   color = ""
class CLR_BRRED(CLR): color = ""
class CLR_GRN(CLR):   color = ""
class CLR_BRGRN(CLR): color = ""
class CLR_YLW(CLR):   color = ""
class CLR_BRYLW(CLR): color = ""
class CLR_BLU(CLR):   color = ""
class CLR_BRBLU(CLR): color = ""
class CLR_MAG(CLR):   color = ""
class CLR_BRMAG(CLR): color = ""
class CLR_CYN(CLR):   color = ""
class CLR_BRCYN(CLR): color = ""
class CLR_WHT(CLR):   color = ""
class CLR_BRWHT(CLR): color = ""

class CAL_OWN_CLR(CLR_CYN): pass
class CAL_READ_CLR(CLR_MAG): pass
class CAL_DEFAULT_CLR(CLR_NRM): pass


def PrintErrMsg(msg):
    if CLR.useColor:
        sys.stdout.write(str(CLR_BRRED()))
        sys.stdout.write(msg)
        sys.stdout.write(str(CLR_NRM()))
    else:
        sys.stdout.write(msg)


def PrintMsg(color, msg):
    if CLR.useColor:
        sys.stdout.write(str(color))
        sys.stdout.write(msg)
        sys.stdout.write(str(CLR_NRM()))
    else:
        sys.stdout.write(msg)


class GoogleCalendar:

    gcal         = None
    cals         = None
    now          = datetime.now(tzlocal())
    feedPrefix   = 'http://www.google.com/calendar/feeds/'
    agendaLength = 5
    username     = ''
    password     = ''
    access       = ''
    details      = False
    command      = 'gxmessage -display :0 -center -title "Ding, Ding, Ding!" %s'

    ACCESS_ALL      = 'all'      # non-google access level
    ACCESS_DEFAULT  = 'default'  # non-google access level
    ACCESS_NONE     = 'none'
    ACCESS_READ     = 'read'
    ACCESS_FREEBUSY = 'freebusy'
    ACCESS_CONTRIB  = 'contributor'
    ACCESS_OWNER    = 'owner'


    def _CalendarAccessCmp(self, x, y):

        order = { self.ACCESS_OWNER:1,
                  self.ACCESS_CONTRIB:2,
                  self.ACCESS_READ:3,
                  self.ACCESS_FREEBUSY:4,
                  self.ACCESS_NONE:5 }

        return cmp(order[x.access_level.value], order[y.access_level.value])


    def __init__(self, username, password, access, details):

        self.gcal     = CalendarService()
        self.username = username
        self.password = password
        self.access   = access
        self.details  = details

        # authenticate and login to google calendar
        try:
            self.gcal.ClientLogin(
                            username=self.username,
                            password=self.password,
                            service='cl',
                            source=__author__+'-'+__program__+'-'+__version__)
        except:
            PrintErrMsg("Error: Failed to authenticate with Google Calendar!\n")
            sys.exit(1)

        # get the list of calendars
        self.cals = self.gcal.GetAllCalendarsFeed()

        self.cals.entry.sort(self._CalendarAccessCmp)

        for cal in self.cals.entry:
            cal.gcalcli_altLink = cal.GetAlternateLink().href
            match = re.match('^' + self.feedPrefix + '(.*?)/(.*?)/(.*)$',
                             cal.gcalcli_altLink)
            cal.gcalcli_username    = urllib.unquote(match.group(1))
            cal.gcalcli_visibility  = urllib.unquote(match.group(2))
            cal.gcalcli_projection  = urllib.unquote(match.group(3))


    def _CalendarWithinAccess(self, cal):

        if (self.access == self.ACCESS_ALL):

            return True

        elif ((self.access == self.ACCESS_DEFAULT) and
              (cal.gcalcli_username != self.username)):

            return False

        elif (self.access != cal.access_level.value):

            return False

        return True


    def _CalendarColor(self, cal):

        if (cal == None):
            return CAL_DEFAULT_CLR()

        if (cal.access_level.value == self.ACCESS_OWNER):
            clr = CAL_OWN_CLR()
        elif (cal.access_level.value == self.ACCESS_READ):
            clr = CAL_READ_CLR()
        else:
            clr = CAL_DEFAULT_CLR()

        return clr


    def _PrintEvents(self, defaultDatetime, eventList):

        if (len(eventList) == 0):
            PrintMsg(CLR_YLW(), "\nNo Events Found...\n")
            return

        eventList.sort(lambda x, y:
                       cmp(x.when[0].start_time, y.when[0].start_time))

        timeFormat = '%l:%M%P'
        dayFormat = '\n%a %b %d' # 10 chars for day
        indent = '          ' # 10 spaces
        detailsIndent = '                   '    # 19 spaces
        day = ''

        for event in eventList:
            startDayTime = parse(event.when[0].start_time,
                                 default=defaultDatetime).astimezone(tzlocal())
            tmpDayStr  = startDayTime.strftime(dayFormat)
            tmpTimeStr = startDayTime.strftime(timeFormat)
            prefix = indent
            if (tmpDayStr != day): day = prefix = tmpDayStr
            PrintMsg(CLR_GRN(), prefix)
            PrintMsg(self._CalendarColor(event.gcalcli_cal),
                     '  %-7s  %s\n' % (tmpTimeStr, event.title.text))

            if self.details:

                clr = CLR_NRM()

                if event.where[0].value_string:
                    str = "%s  Location: %s\n" % (detailsIndent,
                                                 event.where[0].value_string)
                    PrintMsg(clr, str)

                if event.when[0].end_time:
                    endDayTime = parse(event.when[0].end_time,
                                  default=defaultDatetime).astimezone(tzlocal())
                    diffDayTime = (endDayTime - startDayTime)
                    str = "%s  Length: %s\n" % (detailsIndent, diffDayTime)
                    PrintMsg(clr, str)

                # XXX Why does accessing event.when[0].reminder[0] fail?
                for rem in event.when[0].reminder:
                    remStr = ''
                    if rem.days:
                        remStr += "%s Days" % (rem.days)
                    if rem.hours:
                        if (remStr != ''):
                            remStr += ' '
                        remStr += "%s Hours" % (rem.hours)
                    if rem.minutes:
                        if (remStr != ''):
                            remStr += ' '
                        remStr += "%s Minutes" % (rem.minutes)
                    str = "%s  Reminder: %s\n" % (detailsIndent, remStr)
                    PrintMsg(clr, str)

                if event.content.text:
                    str = "%s  Content: %s\n" % (detailsIndent,
                                                event.content.text)
                    PrintMsg(clr, str)


    def _GetAllEvents(self, cal, feed):

        eventList = []

        while 1:
            next = feed.GetNextLink()

            for event in feed.entry:
                event.gcalcli_cal = cal
                eventList.append(event)

            if not next:
                break

            feed = self.gcal.GetCalendarEventFeed(next.href)

        return eventList


    def ListAllCalendars(self):

        accessLen = 0

        for cal in self.cals.entry:
            length = len(cal.access_level.value)
            if (length > accessLen): accessLen = length

        if (accessLen < len('Access')): accessLen = len('Access')

        format = ' %02s  %0' + str(accessLen) + 's  %s\n'

        PrintMsg(CLR_BRYLW(), "\n" + format % ('ID', 'Access', 'Title'))
        PrintMsg(CLR_BRYLW(), format % ('--', '------', '-----'))

        for i, cal in zip(xrange(len(self.cals.entry)), self.cals.entry):
            PrintMsg(self._CalendarColor(cal),
                     format % (i, cal.access_level.value, cal.title.text))


    def TextQuery(self, searchText=''):

        PrintMsg(CLR_BRYLW(), "\nCurrent Time: %s\n" % (self.now.ctime()))

        # the empty string would get *ALL* events...
        if (searchText == ''):
            return

        PrintMsg(CLR_BRWHT(),
                 '\nSearching calendar events for: "%s"\n' % (searchText))

        eventList = []

        for cal in self.cals.entry:

            if not self._CalendarWithinAccess(cal):
                continue

            query = CalendarEventQuery(cal.gcalcli_username,
                                       cal.gcalcli_visibility,
                                       cal.gcalcli_projection,
                                       searchText)
            query.singleevents = 'true'
            # we sort later after getting events from all calendars
            #query.orderby = 'starttime'
            #query.sortorder = 'ascending'
            feed = self.gcal.CalendarQuery(query)

            eventList.extend(self._GetAllEvents(cal, feed))

        self._PrintEvents(self.now, eventList)


    def DateQuery(self, startText='', endText=''):

        PrintMsg(CLR_BRYLW(), "\nCurrent Time: %s\n" % (self.now.ctime()))

        # convert now to midnight this morning and use for default
        now = self.now.replace(hour=0, minute=0, second=0, microsecond=0)

        if (startText == ''):
            start = now
        else:
            try:
                start = parse(startText, default=now)
            except:
                PrintErrMsg('\nError: failed to parse start time\n')
                return

        if (endText == ''):
            end = (start + timedelta(days=self.agendaLength))
        else:
            try:
                end = parse(endText, default=now)
            except:
                PrintErrMsg('\nError: failed to parse end time\n')
                return

        PrintMsg(CLR_BRWHT(),
                 '\nAgenda for [ %s <-> %s ]\n' % (start.ctime(), end.ctime()))

        eventList = []

        for cal in self.cals.entry:

            if not self._CalendarWithinAccess(cal):
                continue

            # see http://code.google.com/apis/calendar/reference.html#Parameters
            query = CalendarEventQuery(cal.gcalcli_username,
                                       cal.gcalcli_visibility,
                                       cal.gcalcli_projection)
            query.start_min = start.isoformat()
            query.start_max = end.isoformat()
            query.singleevents = 'true'
            # we sort later after getting events from all calendars
            #query.orderby = 'starttime'
            #query.sortorder = 'ascending'
            feed = self.gcal.CalendarQuery(query)

            eventList.extend(self._GetAllEvents(cal, feed))

        self._PrintEvents(now, eventList)


    def QuickAdd(self, eventText):

        if (eventText == ''):
            return

        quickEvent = gdata.calendar.CalendarEventEntry()
        quickEvent.content = atom.Content(text=eventText)
        quickEvent.quick_add = gdata.calendar.QuickAdd(value='true')

        self.gcal.InsertEvent(quickEvent,
                              '/calendar/feeds/default/private/full')


    def Remind(self, minutes=10, command=None):

        # default calendar only for now...

        if (command == None):
            command = self.command

        # perform a date query for now + minutes + slip
        start = self.now
        end   = (start + timedelta(minutes=(minutes + 5)))

        # see http://code.google.com/apis/calendar/reference.html#Parameters
        query = CalendarEventQuery(self.username, 'private', 'full')
        query.start_min = start.isoformat()
        query.start_max = end.isoformat()
        query.singleevents = 'true'
        query.orderby = 'starttime'
        query.sortorder = 'ascending'
        feed = self.gcal.CalendarQuery(query)

        eventList = self._GetAllEvents(None, feed)

        message = ''

        for event in eventList:
            tmpDayTime = parse(event.when[0].start_time,
                               default=self.now).astimezone(tzlocal())

            # skip this event if it already started
            # XXX maybe add a 2+ minute grace period here...
            if (tmpDayTime < self.now):
                continue

            tmpTimeStr = tmpDayTime.strftime('%l:%M%P')
            message += '%s  %s\n' % (tmpTimeStr, event.title.text)

        if (message == ''):
            return

        message = "Google Calendar Reminder:\n" + message

        cmd = shlex.split(command)

        for i, a in zip(xrange(len(cmd)), cmd):
            if (a == '%s'):
                cmd[i] = message

        pid = os.fork()
        if not pid:
            os.execvp(cmd[0], cmd)


def DoooooItHippieMonster():

    try:
        opts, args = getopt.getopt(sys.argv[1:], "",
                                   ["user=",
                                    "pw=",
                                    "cals=",
                                    "details",
                                    "nc"])
    except getopt.error, msg:
        Usage()

    usr     = __username__
    pwd     = __password__
    details = False
    access  = 'all'

    # Process options
    for opt, arg in opts:
        if (opt == "--help"): Usage()
        elif (opt == "--user"): usr = arg
        elif (opt == "--pw"): pwd = arg
        elif (opt == "--cals"): access = arg
        elif (opt == "--details"): details = True
        elif (opt == "--nc"): CLR.useColor = False

    if ((usr == '') or (pwd == '')):
        PrintErrMsg('\nError: must specify username and password\n')
        Usage()

    if (len(args) == 0):
        PrintErrMsg('\nError: no command\n')
        Usage()

    if (args[0] == 'list'):
        GoogleCalendar(usr, pwd, access, details).ListAllCalendars()

    elif (args[0] == 'search'):
        if (len(args) != 2):
            PrintErrMsg('\nError: invalid search string\n')
            Usage()
        # allow unicode strings for input
        uniArg = unicode(args[1], locale.getpreferredencoding())
        GoogleCalendar(usr, pwd, access, details).TextQuery(uniArg)

    elif (args[0] == 'agenda'):
        if (len(args) == 3):   # start and end
            GoogleCalendar(usr, pwd, access, details).DateQuery(args[1],
                                                                args[2])
        elif (len(args) == 2): # start
            GoogleCalendar(usr, pwd, access, details).DateQuery(args[1])
        elif (len(args) == 1): # defaults
            GoogleCalendar(usr, pwd, access, details).DateQuery()
        else:
            PrintErrMsg('\nError: invalid agenda arguments\n')
            Usage()

    elif (args[0] == 'quick'):
        if (len(args) != 2):
            PrintErrMsg('\nError: invalid event text\n')
            Usage()
        # allow unicode strings for input
        uniArg = unicode(args[1], locale.getpreferredencoding())
        GoogleCalendar(usr, pwd, access, details).QuickAdd(uniArg)
        return

    elif (args[0] == 'remind'):
        if (len(args) == 3):   # minutes and command
            GoogleCalendar(usr, pwd, access, details).Remind(int(args[1]),
                                                             args[2])
        elif (len(args) == 2): # minutes
            GoogleCalendar(usr, pwd, access, details).Remind(int(args[1]))
        elif (len(args) == 1): # defaults
            GoogleCalendar(usr, pwd, access, details).Remind()
        else:
            PrintErrMsg('\nError: invalid remind arguments\n')
            Usage()
        return

    else:
        PrintErrMsg('\nError: unknown command\n')
        Usage()

    sys.stdout.write('\n')


if __name__ == '__main__':
    DoooooItHippieMonster()