example.py
author Ali Rantakari
Wed Oct 13 03:24:12 2010 +0300 (19 months ago)
changeset 13 489a6dc6a8cf
parent 12 356d55f1e4a2
permissions -rwxr-xr-x
Format the code according to the PEP 8 style guide.
     1 #!/usr/bin/python
     2 # 
     3 # The MIT License
     4 # 
     5 # Copyright (c) 2010 Ali Rantakari - http://hasseg.org
     6 # 
     7 # Permission is hereby granted, free of charge, to any person obtaining a copy
     8 # of this software and associated documentation files (the "Software"), to deal
     9 # in the Software without restriction, including without limitation the rights
    10 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    11 # copies of the Software, and to permit persons to whom the Software is
    12 # furnished to do so, subject to the following conditions:
    13 # 
    14 # The above copyright notice and this permission notice shall be included in
    15 # all copies or substantial portions of the Software.
    16 # 
    17 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    18 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    19 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    20 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    21 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    22 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    23 # THE SOFTWARE.
    24 
    25 import sys
    26 import datetime
    27 from CalStoreHelper import *
    28 from CalendarStore import *
    29 
    30 
    31 c = CalStoreHelper()
    32 
    33 # List of calendars to query (use None for all calendars)
    34 #calendar_names = ['Home','Work']
    35 calendar_names = None
    36 
    37 # Start and end dates to get events between
    38 start_date = datetime.datetime.now()
    39 delta = datetime.timedelta(days=10)
    40 end_date = start_date + delta
    41 
    42 # Let's create Cocoa date formatters for the NSDate objects
    43 # we get as task/event property values. We'll use the medium
    44 # system formats defined by the user in System Preferences.
    45 df_datetime = NSDateFormatter.new()
    46 df_datetime.setDateStyle_(NSDateFormatterMediumStyle)
    47 df_datetime.setTimeStyle_(NSDateFormatterMediumStyle)
    48 df_onlydate = NSDateFormatter.new()
    49 df_onlydate.setDateStyle_(NSDateFormatterMediumStyle)
    50 df_onlydate.setTimeStyle_(NSDateFormatterNoStyle)
    51 
    52 
    53 def printHeader(h):
    54     print '\n%s\n-----------------------------' % h
    55 
    56 
    57 def example_getEvents():
    58     # Example: get events
    59     printHeader('Events from %s to %s' % (start_date, end_date))
    60     events = c.getEvents(calendar_names, start_date, end_date)
    61     for event in events:
    62         print event.calendar().title(), ':', event.title()
    63 
    64 
    65 def example_getEventsByCalendar():
    66     # Example: get events separated by calendar
    67     printHeader('Events by Calendar from %s to %s' % (start_date, end_date))
    68     by_cals_list = c.getEvents(calendar_names, start_date, end_date,
    69                                by_calendar=True)
    70     for i in by_cals_list:
    71         cal = i['calendar']
    72         events = i['items']
    73         print cal.title()
    74         for event in events:
    75             print '  - ' + event.title()
    76 
    77 
    78 def example_getUncompletedTasks():
    79     # Example: get uncompleted tasks
    80     printHeader('Uncompleted Tasks')
    81     tasks = c.getUncompletedTasks(calendar_names)
    82     for task in tasks:
    83         print task.calendar().title(), ':', task.title()
    84 
    85 
    86 def example_getUncompletedTasksDueBefore():
    87     # Example: get uncompleted tasks due before a certain date
    88     db_date = datetime.date.today() + datetime.timedelta(days=10)
    89     printHeader('Uncompleted Tasks due before ' + str(db_date))
    90     tasks = c.getUncompletedTasks(calendar_names, due_before_date=db_date)
    91     for task in tasks:
    92         print task.calendar().title(), ':', task.title(),\
    93               '(due: %s)' % df_onlydate.stringFromDate_(task.dueDate())
    94 
    95 
    96 def example_getUncompletedTasksByCalendar():
    97     # Example: get uncompleted tasks separated by calendar
    98     printHeader('Uncompleted Tasks by Calendar')
    99     by_cals_list = c.getUncompletedTasks(calendar_names, by_calendar=True)
   100     for i in by_cals_list:
   101         cal = i['calendar']
   102         tasks = i['items']
   103         print cal.title()
   104         for task in tasks:
   105             print '  - ' + task.title()
   106 
   107 
   108 def example_XML():
   109     # Example: get events separated by calendar + XML formatting/markup
   110     printHeader('Events by Calendar from %s to %s\nWith XML Formatting/Markup'
   111                 % (start_date, end_date))
   112     by_cals_list = c.getEvents(calendar_names, start_date, end_date,
   113                                by_calendar=True)
   114     import cgi
   115     
   116     def wrapInXMLTag(tag, s):
   117         return '<%s>%s</%s>' % (tag, cgi.escape(s), tag)
   118     for i in by_cals_list:
   119         cal = i['calendar']
   120         events = i['items']
   121         
   122         print '<calendar>'
   123         print '  ' + wrapInXMLTag('title', cal.title())
   124         print '  <events>'
   125         for event in events:
   126             print '    <event>'
   127             print '      ' + wrapInXMLTag('title', event.title())
   128             print '      ' + wrapInXMLTag('startdate',
   129                                 df_datetime.stringFromDate_(event.startDate()))
   130             print '      ' + wrapInXMLTag('enddate',
   131                                 df_datetime.stringFromDate_(event.endDate()))
   132             print '    </event>'
   133         print '  </events>'
   134         print '</calendar>'
   135 
   136 
   137 def example_TeX():
   138     # Example: get uncompleted tasks separated by calendar + (La)TeX
   139     #          formatting/markup
   140     printHeader('Uncompleted Tasks by Calendar \n'
   141                 'With (La)TeX Formatting/Markup')
   142     by_cals_list = c.getUncompletedTasks(calendar_names, by_calendar=True)
   143     
   144     def wrapInTexTag(tag, s):
   145         return '\\%s{ %s }' % (tag, s)
   146     
   147     for i in by_cals_list:
   148         cal = i['calendar']
   149         tasks = i['items']
   150         
   151         print '\\subsubsection*{%s}' % cal.title()
   152         print '\\begin{compactitem}'
   153         for task in tasks:
   154             if task.priority() == CalPriorityHigh:
   155                 print '  \item ' + wrapInTexTag('highpriority', task.title())
   156             elif task.priority() == CalPriorityMedium:
   157                 print '  \item ' + wrapInTexTag('mediumpriority', task.title())
   158             elif task.priority() == CalPriorityLow:
   159                 print '  \item ' + wrapInTexTag('lowpriority', task.title())
   160             else:
   161                 print '  \item ' + task.title()
   162             
   163             if task.dueDate() != None:
   164                 print '  due: ' + df_onlydate.stringFromDate_(task.dueDate())
   165         print '\\end{compactitem}'
   166 
   167 
   168 def example_CSV():
   169     # Example: get events + CSV formatting
   170     printHeader('Events from %s to %s\nWith CSV Formatting'
   171                 % (start_date, end_date))
   172     events = c.getEvents(calendar_names, start_date, end_date)
   173     from UnicodeCSV import UnicodeWriter
   174     csv_writer = UnicodeWriter(open('/dev/stdout', 'wb'))
   175     for event in events:
   176         csv_writer.writerow([
   177             event.calendar().title(),
   178             event.title(),
   179             event.location(),
   180             event.startDate().descriptionWithCalendarFormat_timeZone_locale_(
   181                                 None, None, None),
   182             event.endDate().descriptionWithCalendarFormat_timeZone_locale_(
   183                                 None, None, None),
   184             event.notes()
   185             ])
   186 
   187 
   188 examples = [
   189     {'name':'Get Events',
   190      'function': example_getEvents},
   191     {'name':'Get Events by Calendar',
   192      'function': example_getEventsByCalendar},
   193     {'name':'Get Uncompleted Tasks',
   194      'function': example_getUncompletedTasks},
   195     {'name':'Get Uncompleted Tasks Due Before',
   196      'function': example_getUncompletedTasksDueBefore},
   197     {'name':'Get Uncompleted Tasks by Calendar',
   198      'function': example_getUncompletedTasksByCalendar},
   199     {'name':'XML Formatting',
   200      'function': example_XML},
   201     {'name':'(La)TeX Formatting',
   202      'function': example_TeX},
   203     {'name':'CSV Formatting',
   204      'function': example_CSV}
   205     ]
   206 
   207 while 1 == 1:
   208     print '## Input number of example to run, or Q to quit:'
   209     print
   210     for i in range(0, len(examples)):
   211         print '[%i]: %s' % (i, examples[i]['name'])
   212     print
   213     while 1 == 1:
   214         r = raw_input(':')
   215         if r.lower() == 'q':
   216             sys.exit(0)
   217         try:
   218             s = int(r)
   219         except:
   220             continue
   221         if s < 0 or len(examples) <= s:
   222             continue
   223         break
   224     examples[s]['function']()
   225     print
   226 
   227 
   228 
   229 
   230 
   231 
   232 
   233