Example #1
0
 def events(self):
     store = CalCalendarStore.defaultCalendarStore()
     # Pull all events starting now from all calendars in the CalendarStore
     allEventsPredicate = (
         CalCalendarStore.eventPredicateWithStartDate_endDate_calendars_(
             NSDate.date(), NSDate.distantFuture(), store.calendars()))
     return store.eventsWithPredicate_(allEventsPredicate)
Example #2
0
    def didEndSheet_returnCode_contextInfo_(self, sheet, returnCode, contextInfo):

        # Find out which calendar was selected for the new event/task
        # We do this using the calendarData array controller which is bound to
        # the calendar popups in the sheet
        selectedCalendar = None
        count = len(self.calendarData.selectedObjects())
        if count > 0:
            selectedCalendarUID = self.calendarData.selectedObjects()[0].uid()
            selectedCalendar = CalCalendarStore.defaultCalendarStore(
                    ).calendarWithUID_(selectedCalendarUID)

        # Create an event/task based on which sheet was used
        if sheet is self.taskCreationDialog:
            if self._.calItemTitle is None:
                self._.calItemTitle = "My Task"

            self.createNewTaskWithCalendar_title_priority_dueDate_(
                    selectedCalendar, self._.calItemTitle,
                    self.priorityPopup.selectedTag(),
                    self._.calItemStartDate)

        else:
            if self._.calItemTitle is None:
                self._.calItemTitle = "My Event"

            self.createNewEventWithCalendar_title_startDate_endDate_(
                    selectedCalendar, self._.calItemTitle,
                    self._.calItemStartDate, self._.calItemEndDate)

        # Dismiss the sheet
        sheet.orderOut_(self)
Example #3
0
def fetch_events(request_from_server=False):
    global memory_cache
    logger.info('fetch_events: called')

    if memory_cache:
        logger.info('fetch_events: checking memory cache')
    else:
        logger.info('fetch_events: checking disk cache')
        memory_cache = cache.fetch(config.CALENDAR_CACHE_PATH)

    content = cache.content(memory_cache, config.CALENDAR_CACHE_LIFETIME,
                            request_from_server)
    if content:
        return content

    store = CalCalendarStore.defaultCalendarStore()
    cals = []
    for cal in store.calendars():
        if cal.title() in config.CALENDAR_CALENDARS:
            cals.append(cal)
        logger.info(cal.title())

    cst = tz.gettz('America/Chicago')
    today = datetime.now().date()
    start_dt = datetime(today.year, today.month, today.day, tzinfo=cst)
    end_dt = start_dt + timedelta(180)

    start_int = int(start_dt.strftime("%s"))
    end_int = int(end_dt.strftime("%s"))
    start = NSDate.dateWithTimeIntervalSince1970_(start_int)
    end = NSDate.dateWithTimeIntervalSince1970_(end_int)

    formatted_results = {}

    for cal in cals:
        events = []
        pred = CalCalendarStore.eventPredicateWithStartDate_endDate_calendars_(
            start, end, [cal])
        for event in store.eventsWithPredicate_(pred):
            s = event._.startDate.timeIntervalSince1970()
            e = event._.endDate.timeIntervalSince1970()
            events.append({'name': event._.title, 'start': s, 'end': e})
        formatted_results[cal.title()] = events

    memory_cache = cache.save(formatted_results, config.CALENDAR_CACHE_PATH)
    return formatted_results
Example #4
0
def main():
    startDate = date(year=now.year, month=now.month, day=now.day - BEFORE)
    endDate = date(year=now.year, month=now.month, day=now.day + AFTER)
    #Getting events is a teired system in CalCalndar
    #instead of onelining it I am breaking it out to show process
    store = CalCalendarStore.defaultCalendarStore()
    calendars = store.calendars()
    predicate = \
        CalCalendarStore.eventPredicateWithStartDate_endDate_calendars_(
        startDate, endDate, calendars)
    events = store.eventsWithPredicate_(predicate)

    dayCache = None

    print("AGENDA:")

    for event in events:
        startedDate = datetime.fromtimestamp(
            event.startDate().timeIntervalSince1970())
        endsDate = datetime.fromtimestamp(
            event.endDate().timeIntervalSince1970())
        #Display DAY MONTH and DATE then each event
        if dayCache != None and startedDate.day != dayCache:
            print("")
        if startedDate.day != dayCache:
            print(startedDate.strftime("- %A %B %d").upper())
        #Lets give it some cute unicode status marks
        #Check for has started
        if endsDate.date() < now:
            print("  ✓", end="")
        #Star for happening now
        if startedDate.date() < now and endsDate.date() > now:
            print("  ☆", end="")
        #Indent all events
        print("\t", end="")
        #Print the time if it's not an all day event
        if not event.isAllDay():
            print(startedDate.strftime("%R") + "-" + endsDate.strftime("%R") +
                " - ", end="")
        #Manually encode to ascii with backslash and replace with apostrophy
        # because python 2.6 and ObjC fight during the encoding.
        #Python3 should obsolete this
        print(event.title().encode('ascii', 'backslashreplace').replace(
            '\u2019', "'"))

        dayCache = startedDate.day
Example #5
0
    def _check_status(self, sender):
        # Check if on vacation
        store = CalCalendarStore.defaultCalendarStore()

        for calendar in store.calendars():
            if calendar._.title in self.config['vacation_calendars']:
                pred = CalCalendarStore.\
                    eventPredicateWithStartDate_endDate_calendars_(
                        NSDate.date(), NSDate.date(), [calendar])
                event = store.eventsWithPredicate_(pred)
                if event:
                    self.set_vacation(None, event._.title[0])
                    return

        # Check if in a meeting
        for calendar in store.calendars():
            if calendar._.title in self.config['work_calendars']:
                pred = CalCalendarStore.\
                    eventPredicateWithStartDate_endDate_calendars_(
                        NSDate.date(), NSDate.date(), [calendar])
                event = store.eventsWithPredicate_(pred)
                if event:
                    self.set_meeting(None, event._.title[0])
                    return

        # Check if working remotely
        wifi_client = CoreWLAN.CWWiFiClient.sharedWiFiClient()
        for interface in wifi_client.interfaces():
            if interface.ssid() is not None:
                if interface.ssid() == self.config['work_ssid']:
                    self.unset_status(None)
                else:
                    self.set_remote(None, interface.ssid())
                break

        # Check if screen is locked or asleep
        session = Quartz.CGSessionCopyCurrentDictionary()
        if session and session.get('CGSSessionScreenIsLocked', 0):
            self.set_presence_away(None)
        else:
            self.set_presence_auto(None)
Example #6
0
    def createNewTaskWithCalendar_title_priority_dueDate_(
            self, calendar, title, priority, dueDate):

        # Create a new CalTask object
        newTask = CalTask.task()

        # Set the calendar, title, priority and due date on the new task
        # using the parameters passed to this method
        newTask._.calendar = calendar
        newTask._.title = title
        newTask._.priority = priority
        newTask._.dueDate = dueDate

        # Save the new task to the calendar store (CalCalendarStore) and
        # return it
        res, err = CalCalendarStore.defaultCalendarStore().saveTask_error_(newTask, None)
        if res:
            return newTask

        NSLog("error:%@", err.localizedDescription())
        return None
Example #7
0
    def createNewEventWithCalendar_title_startDate_endDate_(
            self, calendar, title, startDate, endDate):

        # Create a new CalEvent object
        newEvent = CalEvent.event()

        # Set the calendar, title, start date and end date on the new event
        # using the parameters passed to this method
        newEvent._.calendar = calendar
        newEvent._.title = title
        newEvent._.startDate = startDate
        newEvent._.endDate = endDate

        # Save the new event to the calendar store (CalCalendarStore) and
        # return it
        res, err = CalCalendarStore.defaultCalendarStore(
        ).saveEvent_span_error_(newEvent, 0, None)
        if res:
            return newEvent

        NSLog("error:%@", err.localizedDescription())
        return None
Example #8
0
    def createNewEventWithCalendar_title_startDate_endDate_(
                self, calendar, title, startDate, endDate):

        # Create a new CalEvent object
        newEvent = CalEvent.event()

        # Set the calendar, title, start date and end date on the new event
        # using the parameters passed to this method
        newEvent._.calendar = calendar;
        newEvent._.title = title;
        newEvent._.startDate = startDate;
        newEvent._.endDate = endDate;

        # Save the new event to the calendar store (CalCalendarStore) and
        # return it
        res, err = CalCalendarStore.defaultCalendarStore().saveEvent_span_error_(
                newEvent, 0, None)
        if res:
            return newEvent

        NSLog("error:%@", err.localizedDescription())
        return None
Example #9
0
def createEvent(title,
                start_time,
                stop_time,
                calendar_name=u"项目",
                note='',
                url='',
                location=''):
    """
    createEvent("Python事件", "2018-10-28 10:00:00 +0800", "2018-10-28 12:00:00 +0800")
    """
    store = CalCalendarStore.defaultCalendarStore()
    for cal in store.calendars():
        if cal._.title == calendar_name:
            event = CalEvent.event()
            event._.calendar = cal
            event._.title = title
            event._.notes = textwrap.dedent(note)
            if url:
                event._.url = NSURL.URLWithString_(url)
            if location:
                event._.location = location
            event._.isAllDay = False
            start = NSDate.dateWithString_(start_time)
            stop = NSDate.dateWithString_(stop_time)
            event._.startDate = start
            event._.endDate = stop
            res, err = store.saveEvent_span_error_(event, 0, None)
            if not res:
                print("添加日历事件失败", err.localizedDescription())
                break
            else:
                print("添加日历事件成功: %s" % res)
                break
    else:
        print("没有找到合适的日历")
        for cal in store.calendars():
            print(cal._.title)
Example #10
0
"""
Adds WWDC 2007 to the 'Work' calendar
"""
from __future__ import print_function
from CalendarStore import CalCalendarStore, CalEvent
from Foundation import NSURL, NSDate
import textwrap

store = CalCalendarStore.defaultCalendarStore()
for cal in store.calendars():
    if cal._.title == "Work":
        event = CalEvent.event()
        event._.calendar = cal
        event._.title = "WWDC 2009"
        event._.notes = textwrap.dedent(
            """\
                This June, the center of the Mac universe will be at Moscone
                West in downtown San Francisco, as developers and IT
                professionals from around the globe come together for the
                Apple Worldwide Developers Conference.

                Don't miss this opportunity to connect with Apple engineers,
                get a firsthand look at the latest technology, and spend a
                week getting the kind of inspiration you won't find anywhere
                else.
                """
        )
        event._.url = NSURL.URLWithString_("http://www.apple.com/wwdc/")
        event._.location = "Moscone West, San Francisco, CA, USA"
        event._.isAllDay = True
        start = NSDate.dateWithString_("2009-06-8 00:00:00 +0600")
Example #11
0
 def tasks(self):
     store = CalCalendarStore.defaultCalendarStore()
     # Pull all uncompleted tasks from all calendars in the CalendarStore
     return store.tasksWithPredicate_(
             CalCalendarStore.taskPredicateWithUncompletedTasks_(
                 store.calendars()))
Example #12
0
 def calendars(self):
     return CalCalendarStore.defaultCalendarStore().calendars()
"""
Adds WWDC 2007 to the 'Work' calendar
"""
from __future__ import print_function
from CalendarStore import CalCalendarStore, CalEvent
from Foundation import NSURL, NSDate
import textwrap

store = CalCalendarStore.defaultCalendarStore()
for cal in store.calendars():
    if cal._.title == "Work":
        event = CalEvent.event()
        event._.calendar = cal
        event._.title = "WWDC 2009"
        event._.notes = textwrap.dedent('''\
                This June, the center of the Mac universe will be at Moscone
                West in downtown San Francisco, as developers and IT
                professionals from around the globe come together for the
                Apple Worldwide Developers Conference.

                Don't miss this opportunity to connect with Apple engineers,
                get a firsthand look at the latest technology, and spend a
                week getting the kind of inspiration you won't find anywhere
                else.
                ''')
        event._.url = NSURL.URLWithString_('http://www.apple.com/wwdc/')
        event._.location = "Moscone West, San Francisco, CA, USA"
        event._.isAllDay = True
        start = NSDate.dateWithString_("2009-06-8 00:00:00 +0600")
        stop = NSDate.dateWithString_("2009-06-12 23:59:59 +0600")
        event._.startDate = start