def importFile(self):
        fullpath = self.filechooser.GetValue()
        (dir, filename) = os.path.split(fullpath)

        coll = targetCollection = self.choices[self.chooser.GetSelection()]
        filterAttributes = set(key for key, val in self.options.iteritems()
                               if not val.IsChecked())

        # set the preference for importing collections into new collections
        prefs = schema.ns("osaf.sharing", self.view).prefs
        prefs.import_as_new = targetCollection is None
        prefs.import_dir = dir

        activity = Activity("Import %s" % filename)
        self.listener = Listener(activity=activity,
                                 callback=self.updateCallback)

        try:
            activity.started()
            collection = importICalendarFile(fullpath, self.view, coll,
                                             filterAttributes, activity, None,
                                             logger)
            if coll == None and not self.mine.IsChecked():
                mineCollections = schema.ns('osaf.pim', self.view).mine
                mineCollections.sources.add(collection)

        except ICalendarImportError, e:
            activity.failed(exception=e)
            self.fail(unicode(e))
            self.listener.unregister()
            return False
    def processRequest(self, view, request):

        if view is None:
            view = self._repository.createView(self.getName(), pruneSize=50)

        view.refresh()

        try:
            data, path = request
            dir, filename = path.split('/', 1)

            events, name = ICalendar.itemsFromVObject(view, data)
            if name is None:
                name = filename

            c = SmartCollection(itsView=view, displayName=name)
            schema.ns("osaf.app", view).sidebarCollection.add(c)
            for event in events:
                c.add(event.getMaster().itsItem)

            view.commit()

        except Exception, e:
            print traceback.format_exc()
            view.cancel()
Esempio n. 3
0
def reindexFloatingEvents(view, tzinfo):
    """
    When the user's default timezone changes, datetime values with a floating
    timezone may compare differently with non-floating datetimes than before.
    So, we need to resort some indexes if they did comparison of floating
    datetimes. At the moment, the only way we let floating datetimes creep into
    indexes is via C{EventStamp.startTime}, C{EventStamp.recurrenceEnd} and
    C{ContentItem.displayDate} (the latter being computed in some cases from
    the first).
    """
    pim_ns = schema.ns("osaf.pim", view)
    EventStamp = pim_ns.EventStamp

    attrs = (EventStamp.startTime.name, EventStamp.recurrenceEnd.name,
            'displayDate')

    # Ask the view to trigger reindexing for all the above attributes, for
    # all floating events. This should cover the cases above.
    floatingEvents = pim_ns.floatingEvents
    if view.isRefreshing():
        floatingEvents = [item for item in view.dirtyItems()
                          if item in floatingEvents]
    if floatingEvents:
        view.reindex(floatingEvents, *attrs)

    # [Bug 8688] Re-calculate until based on new (non-floating) timezone
    ruleClass = schema.ns("osaf.pim.calendar.Recurrence", view).RecurrenceRule
    for uuid in ruleClass.getKind(view).iterKeys():
        until = view.findValue(uuid, 'until', None)

        if until is not None:
            view[uuid].until = until.replace(tzinfo=tzinfo)
def installParcel(parcel, version=None):

    toolsMenu = schema.ns('osaf.views.main', parcel).ToolsMenu
    sharingMenu = schema.ns('osaf.views.main', parcel).ShareTestMenu

    MenuItem.update(parcel,
                    None,
                    blockName='_debug_separator_0',
                    menuItemKind='Separator',
                    parentBlock=toolsMenu)

    makeTestMenu(parcel, toolsMenu)
    makeDebugMenu(parcel, toolsMenu)

    MenuItem.update(parcel,
                    None,
                    blockName='_debug_separator_1',
                    menuItemKind='Separator',
                    parentBlock=sharingMenu)

    makeMeMenu(parcel, sharingMenu)

    MenuItem.update(parcel,
                    None,
                    blockName='_debug_separator_2',
                    menuItemKind='Separator',
                    parentBlock=sharingMenu)

    makeSharingMenu(parcel, sharingMenu)

    schema.parcel_for_module("debug.scripts", parcel.itsView)
Esempio n. 5
0
def installParcel(parcel, version=None):

    blocks = schema.ns('osaf.framework.blocks', parcel)
    main   = schema.ns('osaf.views.main', parcel)

    # Add an event for creating new EVDB collections
    NewEVDBCollectionEvent = AddEVDBCollectionEvent.update(
        parcel, 'NewEVDBCollectionEvent',
        blockName = 'newEVDBCollectionEvent')

    # Add a separator to the "Experimental" menu ...
    evdbMenu = blocks.Menu.update(parcel, 'EVDBDemoMenu',
                                  blockName = 'EVDBDemoMenu',
                                  title = _(u'&EVDB'),
                                  helpString = _(u'Download EVDB Events'),
                                  childrenBlocks = [ ],
                                  parentBlock = main.ExperimentalMenu)

    # ... and, below it, a menu item to subscribe to an EVDB
    # calendar.
    blocks.MenuItem.update(parcel, "NewEVDBCollection",
        blockName = "NewEVDBCollectionMenu",
        title = _(u"&Subscribe to EVDB calendar..."),
        event = NewEVDBCollectionEvent,
        eventsForNamedLookup = [NewEVDBCollectionEvent],
        parentBlock = evdbMenu,
    )

    # The periodic task that sets the EVDB's API key
    LicenseTask.update(parcel, "licenseTask",
                       run_at_startup=True,
                       interval=timedelta(days=1))
Esempio n. 6
0
def installParcel(parcel, version=None):

    toolsMenu = schema.ns('osaf.views.main', parcel).ToolsMenu
    sharingMenu = schema.ns('osaf.views.main', parcel).ShareTestMenu

    MenuItem.update(parcel, None,
                    blockName='_debug_separator_0',
                    menuItemKind='Separator',
                    parentBlock=toolsMenu)

    makeTestMenu(parcel, toolsMenu)
    makeDebugMenu(parcel, toolsMenu)

    MenuItem.update(parcel, None,
                    blockName='_debug_separator_1',
                    menuItemKind='Separator',
                    parentBlock=sharingMenu)

    makeMeMenu(parcel, sharingMenu)

    MenuItem.update(parcel, None,
                    blockName='_debug_separator_2',
                    menuItemKind='Separator',
                    parentBlock=sharingMenu)

    makeSharingMenu(parcel, sharingMenu)

    schema.parcel_for_module("debug.scripts", parcel.itsView)
Esempio n. 7
0
def reset(view):
    """
    Reset master password. Will clear all passwords as well.
    """
    view.refresh()

    try:
        # clear all passwords
        from osaf.framework import password
        for item in password.Password.iterItems(view):
            waitForDeferred(item.clear())

        # Turn off pref
        prefs = schema.ns("osaf.framework.MasterPassword",
                          view).masterPasswordPrefs
        prefs.masterPassword = False

        # set new dummy password
        prefs = schema.ns("osaf.framework.password",
                          view).passwordPrefs
        password = ''.join([string.printable[ord(c) % len(string.printable)] \
                            for c in os.urandom(16)])                  
        waitForDeferred(prefs.dummyPassword.encryptPassword(password, masterPassword=''))
    except:
        try:
            log.exception('Failed to reset master password')
            view.cancel()
        finally:
            raise
    
    view.commit()
    
    # clear the master password itself
    clear()
    def setUp(self):
        super(InOutCollectionTests, self).setUp()

        self.inCol = schema.ns('osaf.pim', self.view).inCollection
        self.outCol = schema.ns('osaf.pim', self.view).outCollection
        self.meCol = schema.ns("osaf.pim", self.view).meEmailAddressCollection

        self.m1 = MailMessage(itsView=self.view)
        self.m2 = MailMessage(itsView=self.view)
        self.m3 = MailMessage(itsView=self.view)
        self.m4 = MailMessage(itsView=self.view)
        self.m5 = MailMessage(itsView=self.view)
        self.m6 = MailMessage(itsView=self.view)
        self.m7 = MailMessage(itsView=self.view)

        self.e1 = EmailAddress.getEmailAddress(self.view, "*****@*****.**",
                                               uw("Test User1"))

        self.e2 = EmailAddress.getEmailAddress(self.view, u"*****@*****.**",
                                               uw("Test User2"))

        self.e3 = EmailAddress.getEmailAddress(self.view, u"*****@*****.**",
                                               uw("Test User3"))

        # (Differs from e3 only by case of the emailAddress)
        self.e4 = EmailAddress.getEmailAddress(self.view,
                                               self.e3.emailAddress.upper(),
                                               self.e3.fullName)

        self.imapAcct = IMAPAccount(itsView=self.view)
        self.smtpAcct = SMTPAccount(itsView=self.view)
Esempio n. 9
0
    def processRequest(self, view, request):

        if view is None:
            view = self._repository.createView(self.getName(),
                                               pruneSize=50)

        view.refresh()

        try:
            data, path = request
            dir, filename = path.split('/', 1)

            events, name = ICalendar.itemsFromVObject(view, data)
            if name is None:
                name = filename

            c = SmartCollection(itsView=view, displayName=name)
            schema.ns("osaf.app", view).sidebarCollection.add(c)
            for event in events:
                c.add(event.getMaster().itsItem)
        
            view.commit()

        except Exception, e:
            print traceback.format_exc()
            view.cancel()
Esempio n. 10
0
    def importFile(self):
        fullpath = self.filechooser.GetValue()
        (dir, filename) = os.path.split(fullpath)

        coll = targetCollection = self.choices[self.chooser.GetSelection()]
        filterAttributes = set(key for key, val in self.options.iteritems()
                               if not val.IsChecked())

        # set the preference for importing collections into new collections
        prefs = schema.ns("osaf.sharing", self.view).prefs
        prefs.import_as_new = targetCollection is None
        prefs.import_dir = dir

        activity = Activity("Import %s" % filename)
        self.listener = Listener(activity=activity, callback=self.updateCallback)

        try:
            activity.started()
            collection = importICalendarFile(fullpath, self.view, coll,
                                             filterAttributes, activity,
                                             None, logger)
            if coll == None and not self.mine.IsChecked():
                mineCollections = schema.ns('osaf.pim', self.view).mine
                mineCollections.sources.add(collection)

        except ICalendarImportError, e:
            activity.failed(exception=e)
            self.fail(unicode(e))
            self.listener.unregister()
            return False
Esempio n. 11
0
def reindexFloatingEvents(view, tzinfo):
    """
    When the user's default timezone changes, datetime values with a floating
    timezone may compare differently with non-floating datetimes than before.
    So, we need to resort some indexes if they did comparison of floating
    datetimes. At the moment, the only way we let floating datetimes creep into
    indexes is via C{EventStamp.startTime}, C{EventStamp.recurrenceEnd} and
    C{ContentItem.displayDate} (the latter being computed in some cases from
    the first).
    """
    pim_ns = schema.ns("osaf.pim", view)
    EventStamp = pim_ns.EventStamp

    attrs = (EventStamp.startTime.name, EventStamp.recurrenceEnd.name,
             'displayDate')

    # Ask the view to trigger reindexing for all the above attributes, for
    # all floating events. This should cover the cases above.
    floatingEvents = pim_ns.floatingEvents
    if view.isRefreshing():
        floatingEvents = [
            item for item in view.dirtyItems() if item in floatingEvents
        ]
    if floatingEvents:
        view.reindex(floatingEvents, *attrs)

    # [Bug 8688] Re-calculate until based on new (non-floating) timezone
    ruleClass = schema.ns("osaf.pim.calendar.Recurrence", view).RecurrenceRule
    for uuid in ruleClass.getKind(view).iterKeys():
        until = view.findValue(uuid, 'until', None)

        if until is not None:
            view[uuid].until = until.replace(tzinfo=tzinfo)
Esempio n. 12
0
    def setUp(self):
        super(InOutCollectionTests, self).setUp()

        self.inCol  = schema.ns('osaf.pim', self.view).inCollection
        self.outCol = schema.ns('osaf.pim', self.view).outCollection
        self.meCol  = schema.ns("osaf.pim", self.view).meEmailAddressCollection

        self.m1 = MailMessage(itsView=self.view)
        self.m2 = MailMessage(itsView=self.view)
        self.m3 = MailMessage(itsView=self.view)
        self.m4 = MailMessage(itsView=self.view)
        self.m5 = MailMessage(itsView=self.view)
        self.m6 = MailMessage(itsView=self.view)
        self.m7 = MailMessage(itsView=self.view)

        self.e1 = EmailAddress.getEmailAddress(self.view, "*****@*****.**", 
                                               uw("Test User1"))

        self.e2 = EmailAddress.getEmailAddress(self.view, u"*****@*****.**",
                                               uw("Test User2"))

        self.e3 = EmailAddress.getEmailAddress(self.view, u"*****@*****.**",
                                               uw("Test User3"))

        # (Differs from e3 only by case of the emailAddress)
        self.e4 = EmailAddress.getEmailAddress(self.view,
                                               self.e3.emailAddress.upper(),
                                               self.e3.fullName)

        self.imapAcct = IMAPAccount(itsView=self.view)
        self.smtpAcct = SMTPAccount(itsView=self.view)
Esempio n. 13
0
def installParcel(parcel, version=None):

    blocks = schema.ns('osaf.framework.blocks', parcel)
    main = schema.ns('osaf.views.main', parcel)

    # Add an event for creating new EVDB collections
    NewEVDBCollectionEvent = AddEVDBCollectionEvent.update(
        parcel, 'NewEVDBCollectionEvent', blockName='newEVDBCollectionEvent')

    # Add a separator to the "Experimental" menu ...
    evdbMenu = blocks.Menu.update(parcel,
                                  'EVDBDemoMenu',
                                  blockName='EVDBDemoMenu',
                                  title=_(u'&EVDB'),
                                  helpString=_(u'Download EVDB Events'),
                                  childrenBlocks=[],
                                  parentBlock=main.ExperimentalMenu)

    # ... and, below it, a menu item to subscribe to an EVDB
    # calendar.
    blocks.MenuItem.update(
        parcel,
        "NewEVDBCollection",
        blockName="NewEVDBCollectionMenu",
        title=_(u"&Subscribe to EVDB calendar..."),
        event=NewEVDBCollectionEvent,
        eventsForNamedLookup=[NewEVDBCollectionEvent],
        parentBlock=evdbMenu,
    )

    # The periodic task that sets the EVDB's API key
    LicenseTask.update(parcel,
                       "licenseTask",
                       run_at_startup=True,
                       interval=timedelta(days=1))
Esempio n. 14
0
    def doRoundTripRecurrenceCountTest(self, tzName):
        from osaf.pim.calendar.TimeZone import TimeZoneInfo

        tzinfo = TimeZoneInfo.get(self.view)
        tzPrefs = schema.ns('osaf.pim', self.view).TimezonePrefs

        saveTz = tzinfo.default
        saveShowUI = tzPrefs.showUI

        tzinfo.default = self.view.tzinfo.getInstance(tzName)

        try:

            self.Import(self.view, u'Recurrence.ics')
            event = pim.EventStamp(
                sharing.findUID(self.view,
                                '5B30A574-02A3-11DA-AA66-000A95DA3228'))
            third = event.getFirstOccurrence().getNextOccurrence(
            ).getNextOccurrence()
            self.assertEqual(third.summary, u'\u00FCChanged title')
            self.assertEqual(
                third.recurrenceID,
                datetime.datetime(2005,
                                  8,
                                  10,
                                  tzinfo=self.view.tzinfo.floating))
            # while were at it, test bug 3509, all day event duration is off by one
            self.assertEqual(event.duration, datetime.timedelta(0))
            # make sure we imported the floating EXDATE
            event = pim.EventStamp(
                sharing.findUID(self.view,
                                '07f3d6f0-4c04-11da-b671-0013ce40e90f'))
            self.assertEqual(
                event.rruleset.exdates[0],
                datetime.datetime(2005,
                                  12,
                                  6,
                                  12,
                                  30,
                                  tzinfo=self.view.tzinfo.floating))

            # test count export, no timezones
            vcalendar = getVObjectData(self.view, [event.itsItem])
            self.assertEqual(vcalendar.vevent.rruleset._rrule[0]._count, 10)

            # turn on timezones, putting event in Pacific time
            pacific = self.view.tzinfo.getInstance("America/Los_Angeles")
            TimeZoneInfo.get(self.view).default = pacific
            schema.ns('osaf.pim', self.view).TimezonePrefs.showUI = True
            self.assertEqual(event.startTime.tzinfo, pacific)

            # test count export, with timezones turned on
            vcalendar = getVObjectData(self.view, [event.itsItem])
            self.assertEqual(vcalendar.vevent.rruleset._rrule[0]._count, 10)

        finally:
            # Restore global settings
            tzPrefs.showUI = saveShowUI
            tzinfo.default = saveTz
Esempio n. 15
0
    def onToggleLoggingEvent (self, event):
        self.logging = not self.logging

        hooksListItem = schema.ns ('osaf.framework.blocks', self.itsView).BlockDispatchHookList
        dispatchHook = schema.ns (__name__, self.itsView).EventLoggingHook
        if self.logging:
            hooksListItem.hooks.insertItem (dispatchHook, None)
        else:
            hooksListItem.hooks.remove (dispatchHook)
Esempio n. 16
0
 def setUp(self):
     super(CommunicationStatusTestCase, self).setUp()
     self.address = Mail.EmailAddress(
                     itsView=self.view,
                     fullName=u"Mr. President",
                     emailAddress=u"*****@*****.**")
     #account = Mail.IMAPAccount(itsView=self.view,
     #                           replyToAddress=self.address)
     schema.ns('osaf.pim', self.view).meEmailAddressCollection.add(self.address)
     self.note = Note(itsView=self.view)
Esempio n. 17
0
    def onToggleLoggingEvent(self, event):
        self.logging = not self.logging

        hooksListItem = schema.ns('osaf.framework.blocks',
                                  self.itsView).BlockDispatchHookList
        dispatchHook = schema.ns(__name__, self.itsView).EventLoggingHook
        if self.logging:
            hooksListItem.hooks.insertItem(dispatchHook, None)
        else:
            hooksListItem.hooks.remove(dispatchHook)
Esempio n. 18
0
    def testExportFreeBusy(self):
        self.Import(self.view, u'AllDay.ics')
        schema.ns('osaf.pim', self.view).mine.addSource(self.importedCollection)

        start = datetime.datetime(2005,1,1, tzinfo=self.view.tzinfo.floating)
        end = start + datetime.timedelta(2)

        cal = ICalendar.itemsToFreeBusy(self.view, start, end)
        busy_start, busy_end = cal.vfreebusy.freebusy.value[0]
        self.assertEqual(busy_end - busy_start, datetime.timedelta(1))
Esempio n. 19
0
    def prepareTestData(self):

        # Make sure these are initialized, otherwise they won't be tracking
        # icalUIDs
        schema.ns('osaf.sharing', self.views[0]).uid_map
        schema.ns('osaf.sharing', self.views[1]).uid_map

        view = self.views[0]
        # create a sandbox root
        Item("sandbox", view, None)

        sandbox = view.findPath("//sandbox")
        coll = pim.ListCollection("testCollection",
                                  sandbox,
                                  displayName="Test Collection")

        names = [
            (u"Morgen", u"Sagen", u"*****@*****.**"),
            (u"Ted", u"Leung", u"*****@*****.**"),
            (u"Andi", u"Vajda", u"*****@*****.**"),
        ]

        contacts = []

        for name in names:
            c = pim.Contact(None, sandbox)
            c.contactName = pim.ContactName(None, sandbox)
            c.contactName.firstName = name[0]
            c.contactName.lastName = name[1]
            c.emailAddress = name[2]
            c.displayName = u"%s %s" % (name[0], name[1])
            contacts.append(c)

        events = [
            u"breakfast",
            u"lunch",
            u"dinner",
            u"meeting",
            u"movie",
            u'\u8fd1\u85e4\u6df3\u4e5f\u306e\u65b0\u30cd\u30c3\u30c8\u30b3\u30df\u30e5\u30cb\u30c6\u30a3\u8ad6',
        ]

        self.uuids = {}

        tzinfo = sandbox.itsView.tzinfo.default
        for i in xrange(6):
            c = pim.CalendarEvent(None, sandbox)
            c.summary = events[i % 6]
            c.organizer = contacts[0]
            c.participants = [contacts[1], contacts[2]]
            c.startTime = datetime.datetime(2005, 10, 31, 12, 0, 0, 0, tzinfo)
            c.duration = datetime.timedelta(minutes=60)
            c.anyTime = False
            self.uuids[c.itsItem.itsUUID] = c.summary
            coll.add(c.itsItem)
Esempio n. 20
0
    def testExportFreeBusy(self):
        self.Import(self.view, u'AllDay.ics')
        schema.ns('osaf.pim',
                  self.view).mine.addSource(self.importedCollection)

        start = datetime.datetime(2005, 1, 1, tzinfo=self.view.tzinfo.floating)
        end = start + datetime.timedelta(2)

        cal = ICalendar.itemsToFreeBusy(self.view, start, end)
        busy_start, busy_end = cal.vfreebusy.freebusy.value[0]
        self.assertEqual(busy_end - busy_start, datetime.timedelta(1))
Esempio n. 21
0
    def testTellAFriend(self):
        item = self.getItem(u"Tell a friend about Chandler")
        self.failUnlessEqual(item.triageStatus, pim.TriageEnum.now)
        self.checkStampness(item)
        self.failUnless(isinstance(item, pim.Note))
        self.failUnless(item.userReminderTime is None)
        self.failUnless(item in schema.ns("osaf.pim", self.view).allCollection)
        self.failUnlessEqual(len(list(item.appearsIn)), 1)

        self.failUnless(item in schema.ns("osaf.pim", self.view).allCollection)
        self.failUnlessEqual(len(list(item.appearsIn)), 1)
Esempio n. 22
0
 def testTellAFriend(self):
     item = self.getItem(u"Tell a friend about Chandler")
     self.failUnlessEqual(item.triageStatus, pim.TriageEnum.now)
     self.checkStampness(item)
     self.failUnless(isinstance(item, pim.Note))
     self.failUnless(item.userReminderTime is None)
     self.failUnless(item in schema.ns("osaf.pim", self.view).allCollection)
     self.failUnlessEqual(len(list(item.appearsIn)), 1)
            
     self.failUnless(item in schema.ns("osaf.pim", self.view).allCollection)
     self.failUnlessEqual(len(list(item.appearsIn)), 1)
Esempio n. 23
0
    def prepareTestData(self):

        # Make sure these are initialized, otherwise they won't be tracking
        # icalUIDs
        schema.ns('osaf.sharing', self.views[0]).uid_map
        schema.ns('osaf.sharing', self.views[1]).uid_map

        view = self.views[0]
        # create a sandbox root
        Item("sandbox", view, None)

        sandbox = view.findPath("//sandbox")
        coll = pim.ListCollection("testCollection", sandbox,
            displayName="Test Collection")

        names = [
            (u"Morgen", u"Sagen", u"*****@*****.**"),
            (u"Ted", u"Leung", u"*****@*****.**"),
            (u"Andi", u"Vajda", u"*****@*****.**"),
        ]

        contacts = []

        for name in names:
            c = pim.Contact(None, sandbox)
            c.contactName = pim.ContactName(None, sandbox)
            c.contactName.firstName = name[0]
            c.contactName.lastName = name[1]
            c.emailAddress = name[2]
            c.displayName = u"%s %s" % (name[0], name[1])
            contacts.append(c)

        events = [
            u"breakfast",
            u"lunch",
            u"dinner",
            u"meeting",
            u"movie",
            u'\u8fd1\u85e4\u6df3\u4e5f\u306e\u65b0\u30cd\u30c3\u30c8\u30b3\u30df\u30e5\u30cb\u30c6\u30a3\u8ad6',
        ]

        self.uuids = {}

        tzinfo = sandbox.itsView.tzinfo.default
        for i in xrange(6):
            c = pim.CalendarEvent(None, sandbox)
            c.summary = events[i % 6]
            c.organizer = contacts[0]
            c.participants = [contacts[1], contacts[2]]
            c.startTime=datetime.datetime(2005, 10, 31, 12, 0, 0, 0, tzinfo)
            c.duration=datetime.timedelta(minutes=60)
            c.anyTime=False
            self.uuids[c.itsItem.itsUUID] = c.summary
            coll.add(c.itsItem)
Esempio n. 24
0
def GetReadOnlyCollection(item, view):
    """Return the first read-only collection the item is in, or None."""
    app_ns = schema.ns('osaf.app', view)
    pim_ns = schema.ns('osaf.pim', view)
    allCollection = pim_ns.allCollection
    
    sidebarCollections = app_ns.sidebarCollection
    
    memberItem = getProxy(u'ui', item).getMembershipItem()
    for collection in [col for col in sidebarCollections if sharing.isReadOnly(col)]:
        if memberItem in collection:
            return collection
    return None
Esempio n. 25
0
    def testWelcomeEvent(self):

        # Look up the welcome event ...
        welcome = schema.ns("osaf.app", self.view).WelcomeEvent

        # Check its event-ness ...
        self.checkStampness(welcome, pim.EventStamp, pim.TaskStamp)

        # Check it's in the all collection
        self.failUnless(
            welcome in schema.ns("osaf.pim", self.view).allCollection)
        # ... and two other collections
        self.failUnless(len(list(welcome.appearsIn)), 3)
Esempio n. 26
0
    def testWelcomeEvent(self):
        
        # Look up the welcome event ...
        welcome = schema.ns("osaf.app", self.view).WelcomeEvent
        
        # Check its event-ness ...
        self.checkStampness(welcome, pim.EventStamp, pim.TaskStamp)

        # Check it's in the all collection
        self.failUnless(
            welcome in schema.ns("osaf.pim", self.view).allCollection)
        # ... and two other collections
        self.failUnless(len(list(welcome.appearsIn)), 3)
Esempio n. 27
0
 def doRoundTripRecurrenceCountTest(self, tzName):
     from osaf.pim.calendar.TimeZone import TimeZoneInfo
     
     tzinfo = TimeZoneInfo.get(self.view)
     tzPrefs = schema.ns('osaf.pim', self.view).TimezonePrefs
     
     saveTz = tzinfo.default
     saveShowUI = tzPrefs.showUI
     
     tzinfo.default = self.view.tzinfo.getInstance(tzName)
     
     try:
     
         self.Import(self.view, u'Recurrence.ics')
         event = pim.EventStamp(sharing.findUID(self.view,
                                     '5B30A574-02A3-11DA-AA66-000A95DA3228'))
         third = event.getFirstOccurrence().getNextOccurrence().getNextOccurrence()
         self.assertEqual(third.summary, u'\u00FCChanged title')
         self.assertEqual(
             third.recurrenceID,
             datetime.datetime(2005, 8, 10, tzinfo=self.view.tzinfo.floating)
         )
         # while were at it, test bug 3509, all day event duration is off by one
         self.assertEqual(event.duration, datetime.timedelta(0))
         # make sure we imported the floating EXDATE
         event = pim.EventStamp(sharing.findUID(self.view,
                                     '07f3d6f0-4c04-11da-b671-0013ce40e90f'))
         self.assertEqual(
             event.rruleset.exdates[0],
             datetime.datetime(2005, 12, 6, 12, 30, tzinfo=self.view.tzinfo.floating)
         )
         
         # test count export, no timezones
         vcalendar = getVObjectData(self.view, [event.itsItem])
         self.assertEqual(vcalendar.vevent.rruleset._rrule[0]._count, 10)
 
         # turn on timezones, putting event in Pacific time
         pacific = self.view.tzinfo.getInstance("America/Los_Angeles")
         TimeZoneInfo.get(self.view).default = pacific
         schema.ns('osaf.pim', self.view).TimezonePrefs.showUI = True
         self.assertEqual(event.startTime.tzinfo, pacific)
         
         # test count export, with timezones turned on
         vcalendar = getVObjectData(self.view, [event.itsItem])
         self.assertEqual(vcalendar.vevent.rruleset._rrule[0]._count, 10)
         
     finally:
         # Restore global settings
         tzPrefs.showUI = saveShowUI
         tzinfo.default = saveTz
    def showPyShell(self, withFilling=False):
        """
        A window with a python interpreter
        """
        from wx import py
        from tools import headless

        headless.view = view = self.itsView

        def run(scriptText):
            import osaf.framework.scripting as Scripting
            Scripting.run_script(scriptText, view)

        # Import helper methods/variables from headless, and also add
        # whatever other methods we want to the mix (such as the run method,
        # above).  locals will be passed to PyCrust/Shell to make those
        # symbols available to the developer
        locals = headless.getExports(run=run,
                                     view=view,
                                     schema=schema,
                                     app_ns=schema.ns('osaf.app', view),
                                     pim_ns=schema.ns('osaf.pim', view))

        if withFilling:
            browseableObjects = {
                "globals": Globals,
                "parcelsRoot": view.getRoot('parcels'),
                "repository": view.repository,
                "wxApplication": wx.GetApp(),
            }
            self.pyFrame = py.crust.CrustFrame(rootObject=browseableObjects,
                                               rootLabel="Chandler",
                                               locals=locals)
        else:
            self.pyFrame = py.shell.ShellFrame(locals=locals)

        self.pyFrame.SetSize((700, 700))
        self.pyFrame.Show(True)

        # Install a custom displayhook to keep Python from setting the global
        # _ (underscore) to the value of the last evaluated expression.  If
        # we don't do this, our mapping of _ to gettext can get overwritten.
        # This is useful in interactive debugging with PyShell.

        def _displayHook(obj):
            if obj is not None:
                print repr(obj)

        sys.displayhook = _displayHook
Esempio n. 29
0
    def showPyShell(self, withFilling=False):
        """
        A window with a python interpreter
        """
        from wx import py
        from tools import headless

        headless.view = view = self.itsView

        def run(scriptText):
            import osaf.framework.scripting as Scripting
            Scripting.run_script(scriptText, view)

        # Import helper methods/variables from headless, and also add
        # whatever other methods we want to the mix (such as the run method,
        # above).  locals will be passed to PyCrust/Shell to make those
        # symbols available to the developer
        locals = headless.getExports(run=run,
                                     view=view,
                                     schema=schema,
                                     app_ns=schema.ns('osaf.app', view),
                                     pim_ns=schema.ns('osaf.pim', view))

        if withFilling:
            browseableObjects = {
                "globals": Globals,
                "parcelsRoot": view.getRoot('parcels'),
                "repository": view.repository,
                "wxApplication": wx.GetApp(),
            }
            self.pyFrame = py.crust.CrustFrame(rootObject=browseableObjects,
                                               rootLabel="Chandler",
                                               locals=locals)
        else:
            self.pyFrame = py.shell.ShellFrame(locals=locals)

        self.pyFrame.SetSize((700, 700))
        self.pyFrame.Show(True)

        # Install a custom displayhook to keep Python from setting the global
        # _ (underscore) to the value of the last evaluated expression.  If 
        # we don't do this, our mapping of _ to gettext can get overwritten.
        # This is useful in interactive debugging with PyShell.

        def _displayHook(obj):
            if obj is not None:
                print repr(obj)

        sys.displayhook = _displayHook
Esempio n. 30
0
    def __init__(self, hostname, callback, reconnect, view):
        super(IncomingDiscovery, self).__init__(hostname, callback, reconnect, view)
        self.imapAccount = schema.ns('osaf.app', self.view).TestIMAPAccount
        self.popAccount = schema.ns('osaf.app', self.view).TestPOPAccount

        if hostname.lower().startswith(u"pop."):
            # If the hostname begins with pop
            # then chances are it is a POP3 server
            # so try the POP secure settings first
            # before trying IMAP secure settings
            self.SETTINGS = self.POP_SETTINGS
        else:
            # This is the default which is to
            # try IMAP secure settings first
            self.SETTINGS = self.IMAP_SETTINGS
def GetReadOnlyCollection(item, view):
    """Return the first read-only collection the item is in, or None."""
    app_ns = schema.ns('osaf.app', view)
    pim_ns = schema.ns('osaf.pim', view)
    allCollection = pim_ns.allCollection

    sidebarCollections = app_ns.sidebarCollection

    memberItem = getProxy(u'ui', item).getMembershipItem()
    for collection in [
            col for col in sidebarCollections if sharing.isReadOnly(col)
    ]:
        if memberItem in collection:
            return collection
    return None
Esempio n. 32
0
    def onNewItem(self):
        """
        Called to create a new Photo.
        """
        photo = None
        cmd, dir, filename = application.dialogs.Util.showFileDialog(
            None,
            _(u"Choose an image to import"),
            "",
            "",
            _(u"Images|*.gif;*.jpg;*.png;*.tiff|All files (*.*)|*.*"),
            wx.OPEN
        )

        theApp = wx.GetApp()
        if cmd == wx.ID_OK:
            path = os.path.join(dir, filename)

            # We'll us CallItemMethodAsync, which works from other repository
            # views, since this code should eventually be run in a background
            # thread with a non UI repository view. In the mean time we'll
            # call Yield.
            theApp.CallItemMethodAsync("MainView",
                                       'setStatusMessage',
                                       _(u"Importing %(filePath)s") % {'filePath': path})
            theApp.Yield(True)
            photo = Photo(itsView=self.itsView)
            photo.displayName = filename
            photo.creator = schema.ns("osaf.pim", self.itsView).currentContact.item
            photo.importFromFile(path)

        theApp.CallItemMethodAsync("MainView",
                                   'setStatusMessage',"")
        return photo
Esempio n. 33
0
    def onNewItem(self):
        """
        Called to create a new Photo.
        """
        photo = None
        cmd, dir, filename = application.dialogs.Util.showFileDialog(
            None, _(u"Choose an image to import"), "", "",
            _(u"Images|*.gif;*.jpg;*.png;*.tiff|All files (*.*)|*.*"), wx.OPEN)

        theApp = wx.GetApp()
        if cmd == wx.ID_OK:
            path = os.path.join(dir, filename)

            # We'll us CallItemMethodAsync, which works from other repository
            # views, since this code should eventually be run in a background
            # thread with a non UI repository view. In the mean time we'll
            # call Yield.
            theApp.CallItemMethodAsync(
                "MainView", 'setStatusMessage',
                _(u"Importing %(filePath)s") % {'filePath': path})
            theApp.Yield(True)
            photo = Photo(itsView=self.itsView)
            photo.displayName = filename
            photo.creator = schema.ns("osaf.pim",
                                      self.itsView).currentContact.item
            photo.importFromFile(path)

        theApp.CallItemMethodAsync("MainView", 'setStatusMessage', "")
        return photo
Esempio n. 34
0
    def getByline(self):
        lastModification = self.lastModification
        assert lastModification in self.BYLINE_FORMATS

        fmt, noUserFmt = self.BYLINE_FORMATS[lastModification]

        # fall back to createdOn
        view = self.itsView
        lastModified = (self.lastModified or getattr(self, 'createdOn', None)
                        or datetime.now(view.tzinfo.default))

        shortDateTimeFormat = schema.importString(
            "osaf.pim.shortDateTimeFormat")
        date = shortDateTimeFormat.format(view, lastModified)

        tzPrefs = schema.ns('osaf.pim', view).TimezonePrefs
        if tzPrefs.showUI:
            from calendar.TimeZone import shortTZ
            tzName = shortTZ(view, lastModified)
        else:
            tzName = u''

        user = self.lastModifiedBy
        if user:
            result = fmt % dict(user=user.getLabel(), date=date, tz=tzName)
        else:
            result = noUserFmt % dict(date=date, tz=tzName)
        return result.strip()
Esempio n. 35
0
    def _prepareToRemoveFromCollection(self, collection):
        """
        If the collection is a mine collection and the item doesn't exist in any
        other 'mine' collections, manually add it to 'all' to keep the item
        'mine'.

        We don't want to do this blindly though, or all's inclusions will get
        unnecessarily full.

        We also don't want to remove collection from mine.sources. That will
        cause a notification storm as items temporarily leave and re-enter
        being 'mine'.
        
        """
        pim_ns = schema.ns('osaf.pim', self.itsView)
        mine = pim_ns.mine
        allCollection = pim_ns.allCollection

        if collection in mine.sources:
            for otherCollection in self.appearsIn:
                if otherCollection is collection:
                    continue

                if otherCollection in mine.sources:
                    # we found it in another 'mine'
                    break
            else:
                # we didn't find it in a 'mine' Collection
                self.collections.add(allCollection)
Esempio n. 36
0
 def setUp(self):
     super(FloatingEventTestCase, self).setUp()
     self.tzprefs = schema.ns('osaf.pim', self.view).TimezonePrefs
     self.saveTzShowUI = self.tzprefs.showUI
     self.saveDefaultTz = self.view.tzinfo.default
     
     self.tzprefs.default = self.view.tzinfo.getInstance("America/Los_Angeles")
Esempio n. 37
0
def installParcel(parcel, version=None):

    main = schema.ns('osaf.views.main', parcel)
    handler = fuseHandler.update(parcel,
                                 '_fuse_fuseHandler',
                                 blockName='_fuse_fuseHandler')

    # Add an event for mount/umount
    mountEvent = BlockEvent.update(parcel,
                                   None,
                                   blockName='_fuse_Mount',
                                   dispatchEnum='SendToBlockByReference',
                                   destinationBlockReference=handler)

    # Add a separator to the "Experimental" menu ...
    MenuItem.update(parcel,
                    'menuSeparator',
                    blockName='_fuse_menuSeparator',
                    menuItemKind='Separator',
                    parentBlock=main.ExperimentalMenu)

    # Add a menu item to the "Experimental" menu to mount/umount
    MenuItem.update(parcel,
                    "MountMenuItem",
                    blockName="_fuse_LoginMenuItem",
                    title=_(u"Show Sidebar in Finder"),
                    event=mountEvent,
                    eventsForNamedLookup=[mountEvent],
                    parentBlock=main.ExperimentalMenu)
Esempio n. 38
0
def findUID(view, uid):
    """
    Return the master event whose icalUID matched uid, or None.
    """
    iCalendarItems = schema.ns("osaf.sharing", view).iCalendarItems
    return indexes.valueLookup(iCalendarItems, 'icalUID',
                                    pim.Note.icalUID.name, uid)
Esempio n. 39
0
    def __init__(self, hostname, callback, reconnect, view):
        super(IncomingDiscovery, self).__init__(hostname, callback, reconnect,
                                                view)
        self.imapAccount = schema.ns('osaf.app', self.view).TestIMAPAccount
        self.popAccount = schema.ns('osaf.app', self.view).TestPOPAccount

        if hostname.lower().startswith(u"pop."):
            # If the hostname begins with pop
            # then chances are it is a POP3 server
            # so try the POP secure settings first
            # before trying IMAP secure settings
            self.SETTINGS = self.POP_SETTINGS
        else:
            # This is the default which is to
            # try IMAP secure settings first
            self.SETTINGS = self.IMAP_SETTINGS
Esempio n. 40
0
    def render(self, request):

        session = request.getSession()

        if self.resourceItem.autoView:
            # Create our own view (for this resource) if it doesn't exist
            if not hasattr(self, 'myView'):
                repo = self.repositoryView.repository
                viewName = 'servlet_%s_view' % request.path
                self.myView = repo.createView(viewName)
                ## @@@MOR I wonder if I should have separate repository views
                ## per resource+user; is it dangerous to have different users
                ## share the same view?

            self.myView.refresh()
        else:
            self.myView = self.repositoryView


        args = request.args
        if args.has_key('command'):
            command = args['command'][0]
        else:
            command = None

        # See if the user is trying to log in
        if command == 'login':
            login = args['login'][0]
            password = args['password'][0]
            uuid = self.authenticate(login, password)
            if uuid is not None:
                session.user = uuid
                request.method = 'GET'
                request.args['command'] = ['default']

        elif command == 'logout':
            if hasattr(session, 'user'):
                del session.user
                # We'll get set to 'public' a few lines down...

        # Set user to 'public' if not set to something already
        public = schema.ns('osaf.webserver', self.myView).public.itsUUID
        session.user = getattr(session, 'user', public)
        user = self.resourceItem.itsView.findUUID(session.user)

        acl = self.resourceItem.getACL(default=None)
        if (not acl) or acl.verify(user, Access.Permissions.READ):
            method = getattr(self, 'render_' + request.method, None)
            if not method:
                raise server.Unsupported(getattr(self, 'allowedMethods', ()))

            output = method(request)

            if self.resourceItem.autoView:
                self.myView.commit()

            return output

        else:
            return self.loginPage(request)
    def ProcessNextItem(self):
        main_ns = schema.ns('osaf.views.main', self.view)

        while True:
            self.itemNumber += 1
            if self.itemNumber >= len(self.itemsAndStates):
                self.OnDone()
            else:
                item, state = self.itemsAndStates[self.itemNumber]

                # ignoring applyToAll for now
                if state == DELETE_DASHBOARD:
                    if (self.dashboardRemoveAll
                            or not main_ns.dashboardRemovalPref.askNextTime):
                        self.DeleteItem()
                        continue
                    else:
                        self.DeletePrompt()
                elif state == DELETE_LAST:
                    if (self.lastItemApplyAll or
                            not main_ns.lastCollectionRemovalPref.askNextTime):
                        self.DeleteItem()
                        continue
                    else:
                        self.DeletePrompt()
                elif state == IN_READ_ONLY_COLLECTION:
                    if self.readOnlyApplyAll:
                        continue
                    else:
                        self.ReadOnlyPrompt()
                else:
                    self.ReadOnlyPrompt()
            break
def ShowTurnOnTimezonesDialog(view=None,
                              state=IMPORT,
                              modal=False,
                              parent=None):

    if dialogShowing:
        return True

    # Check preferences before showing the dialog
    tzprefs = schema.ns('osaf.pim', view).TimezonePrefs
    if tzprefs.showUI or not tzprefs.showPrompt:
        return True

    filename = 'TurnOnTimezones.xrc'
    xrcFile = os.path.join(Globals.chandlerDirectory, 'application', 'dialogs',
                           filename)
    #[i18n] The wx XRC loading method is not able to handle raw 8bit paths
    #but can handle unicode
    xrcFile = unicode(xrcFile, sys.getfilesystemencoding())
    resources = wx.xrc.XmlResource(xrcFile)
    win = TurnOnTimezonesDialog(resources=resources,
                                view=view,
                                state=state,
                                modal=modal,
                                parent=parent)
    win.CenterOnScreen()
    if modal:
        return win.ShowModal()
    else:
        win.Show()
        return win
Esempio n. 43
0
def createHTTPFactory(host, port, username, password, useSSL, repositoryView):

    # See if the user has configured an HTTP proxy
    if repositoryView is not None and not useSSL:
        getProxy = schema.ns("osaf.sharing.accounts", repositoryView).getProxy
        
        proxy = getProxy(repositoryView, 'HTTP')
        if not proxy.appliesTo(host):
            proxy = None
    else:
        proxy = None
        
    if proxy is not None and proxy.active:
        proxyPassword = getattr(proxy, 'password', None)
        factory = ChandlerHTTPProxyClientFactory(
                      host=proxy.host,
                      port=proxy.port,
                      username=proxy.username,
                      password=waitForDeferred(proxyPassword.decryptPassword())
                  )
    else:
        factory = ChandlerHTTPClientFactory()

    factory.protocol = zanshin.webdav.WebDAVProtocol
    factory.startTLS = useSSL
    factory.host = host
    factory.port = port
    factory.username = username
    factory.password = password
    factory.retries = zanshin.webdav.DEFAULT_RETRIES
    factory.repositoryView = repositoryView
    factory.extraHeaders = { 'User-Agent' : Utility.getUserAgent() }
    #factory.extraHeaders = { 'Connection' : "close" }

    return factory
Esempio n. 44
0
 def setUp(self):
     super(TestEventIndexing, self).setUp()
     view = self.view
     self.tzInfoItem = TimeZoneInfo.get(view)
     # eventsInRange will treat all timezones as equivalent unless timezone
     # display is turned on
     self.tzprefs = schema.ns('osaf.pim', view).TimezonePrefs
     self.tzprefs.showUI = True
     
     self.pacific  = view.tzinfo.getInstance("US/Pacific")
     self.hawaii   = view.tzinfo.getInstance("US/Hawaii")
     self.eastern  = view.tzinfo.getInstance("US/Eastern")
     self.floating = view.tzinfo.floating
     
     self.midnight = datetime(2006, 9, 1, 0, 0, tzinfo=self.floating)
     
     self.easternEvent = self._createEvent(self.midnight.replace(tzinfo=
         self.eastern))
     self.pacificEvent = self._createEvent(self.midnight.replace(tzinfo=
         self.pacific))
     self.hawaiiEvent  = self._createEvent(self.midnight.replace(tzinfo=
         self.hawaii))
     
     self.floatingEvent = self._createEvent(datetime(2006, 9, 1, 1, 0,
                                                     tzinfo = self.floating))
Esempio n. 45
0
    def testSalsaClass(self):
        item = self.getItem(u"Salsa Class")
        self.checkStampness(item, pim.EventStamp)

        masterEvent = pim.EventStamp(item).getMaster()
        self.failIf(masterEvent.anyTime)
        self.failIf(masterEvent.allDay)
        self.failUnless(masterEvent.userReminderInterval is None)
        self.failIfEqual(item.body, u'')
        # Sundays at 2:30 PM
        self.failUnlessEqual(masterEvent.effectiveStartTime.weekday(), 6)
        self.failUnlessEqual(masterEvent.effectiveStartTime.time(),
                             time(14, 30))

        
        self.failUnless(item in self.getCollection(u"Home"))
        self.failUnless(item in self.getCollection(u"Fun"))
        self.failUnless(item in schema.ns("osaf.pim", self.view).allCollection)
        self.failUnlessEqual(len(list(item.appearsIn)), 3)
        
        rruleset = masterEvent.rruleset
        self.failUnlessEqual(len(list(rruleset.rrules)), 1)
        self.failUnlessEqual(rruleset.rrules.first().freq, 'weekly')
        self.failUnlessEqual(rruleset.rrules.first().interval, 1)

        # Should have 2 or 3 DONE modifications (in the past) and
        # one LATER or NOW
        events = sorted(masterEvent.modifications,
                        key=lambda item: pim.EventStamp(item).startTime)
        self.failUnless(len(events) in (3, 4))
        
        ts = [x.triageStatus for x in events]
        self.failUnless(ts[-1] in (pim.TriageEnum.later, pim.TriageEnum.now))
        self.failUnlessEqual(set(ts[:-1]), set([pim.TriageEnum.done]))
Esempio n. 46
0
    def testOrdering(self):
        def key(item):
            return (item._triageStatus, item._triageStatusChanged)

        items = sorted(schema.ns("osaf.pim", self.view).allCollection, key=key)
        
        displayNames = list(item.displayName for item in items
                            if pim.EventStamp(item).rruleset is None or
                               pim.EventStamp(item).occurrenceFor is not None)


        # Don't test exact item order, since the recurring events (plus
        # auto-triage) make the exact order complicated. Rather, check the
        # first few (non-recurring) items ...
        def failUnlessItemMatches(itemName, index):
            item = self.getItem(itemName)
            self.failUnlessEqual(displayNames[index], item.displayName)
            
        failUnlessItemMatches(u'Welcome to Chandler\u2122', 0)
        failUnlessItemMatches(u'Next dentist appointment?', 1)
        failUnlessItemMatches(u'Tell a friend about Chandler',  2)
        failUnlessItemMatches(u'Write-up...', 3)
        failUnlessItemMatches(u'Follow up with...on...', 4)
        failUnlessItemMatches(u'Start planning vacation', 5)

        # ... as well as the very last item
        failUnlessItemMatches(u'Download Chandler!', -1)
Esempio n. 47
0
    def stat(self, path):

        values = [0] * 10
        if path in ("", 'sidebar'):
            values[stat.ST_MODE] = stat.S_IFDIR | 0777
            values[stat.ST_NLINK] = 2
            return values

        if path.startswith('sidebar/'):
            if path.endswith('.ics'):
                if path in self.openFiles:
                    values[stat.ST_MODE] = stat.S_IFREG | 0666
                    values[stat.ST_NLINK] = 1
                    values[stat.ST_CTIME] = time.time()
                    return values
            else:
                self.view.refresh()
                store = self.view.store
                dir, name = path.split('/', 1)
                sidebar = schema.ns('osaf.app', self.view).sidebarCollection
                for c in sidebar:
                    if c.displayName == name:
                        then, x, x, x = store.getCommit(c.itsVersion)
                        values[stat.ST_MODE] = stat.S_IFREG | 0444
                        values[stat.ST_INO] = hash(c.itsUUID)
                        if path in self.openFiles:
                            values[stat.ST_SIZE] = len(self.openFiles[path][0])
                        else:
                            values[stat.ST_SIZE] = 256 * 1024
                        values[stat.ST_NLINK] = 1
                        values[stat.ST_MTIME] = then
                        return values

        return None
Esempio n. 48
0
def getAutoSyncInterval(rv):
    task = schema.ns('osaf.sharing', rv).sharingTask
    interval = task.interval
    if interval == datetime.timedelta(days=365):
        return None
    else:
        return interval.days * 1440 + interval.seconds / 60
Esempio n. 49
0
def createHTTPFactory(host, port, username, password, useSSL, repositoryView):

    # See if the user has configured an HTTP proxy
    if repositoryView is not None and not useSSL:
        getProxy = schema.ns("osaf.sharing.accounts", repositoryView).getProxy

        proxy = getProxy(repositoryView, 'HTTP')
        if not proxy.appliesTo(host):
            proxy = None
    else:
        proxy = None

    if proxy is not None and proxy.active:
        proxyPassword = getattr(proxy, 'password', None)
        factory = ChandlerHTTPProxyClientFactory(
            host=proxy.host,
            port=proxy.port,
            username=proxy.username,
            password=waitForDeferred(proxyPassword.decryptPassword()))
    else:
        factory = ChandlerHTTPClientFactory()

    factory.protocol = zanshin.webdav.WebDAVProtocol
    factory.startTLS = useSSL
    factory.host = host
    factory.port = port
    factory.username = username
    factory.password = password
    factory.retries = zanshin.webdav.DEFAULT_RETRIES
    factory.repositoryView = repositoryView
    factory.extraHeaders = {'User-Agent': Utility.getUserAgent()}
    #factory.extraHeaders = { 'Connection' : "close" }

    return factory
Esempio n. 50
0
def loadMailTests(view, datadir):
    try:
        sidebar = schema.ns("osaf.app", view).sidebarCollection

        for col in sidebar:
            if datadir == col.displayName:
                # We already imported these mail messages
                return

        files = pkg_resources.resource_listdir("debug", datadir)
        mCollection = SmartCollection(itsView=view)
        mCollection.displayName = unicode(datadir)

        for f in files:
            if not f.startswith("test_"):
                continue

            fp = pkg_resources.resource_stream("debug", "%s/%s" % (datadir, f))
            messageText = fp.read()
            fp.close()

            mailStamp = messageTextToKind(view, messageText)
            mCollection.add(mailStamp.itsItem)

        sidebar.add(mCollection)

    except:
        view.cancel()
        raise
Esempio n. 51
0
    def remove(self):
        item = self.itsItem
        stampClass = self.__class__
        stampCollection = schema.itemFor(stampClass, item.itsView).collection

        if not stampCollection in self.stampCollections:
            raise StampNotPresentError, \
                  "Item %r doesn't have stamp %r" % (item, self)

        addBack = None

        if not item.isProxy:

            # This is gross, and was in the old stamping code.
            # Some items, like Mail messages, end up in the
            # all collection by virtue of their stamp. So, we
            # explicitly re-add the item to all after unstamping
            # if necessary.
            all = schema.ns("osaf.pim", item.itsView).allCollection
            if item in all:
                addBack = all

            if not self.itsItem.hasLocalAttributeValue(
                    Stamp.stampCollections.name):
                self.stampCollections = list(self.stampCollections)

        self.stampCollections.remove(stampCollection)

        if addBack is not None and not item in addBack:
            addBack.add(item)
Esempio n. 52
0
def installParcel(parcel, oldVersion=None):

    repositoryView = parcel.itsView
    blocksParcel = schema.ns('osaf.framework.blocks', repositoryView)
    
    aePresentationStyle = blocks.ControlBlocks.PresentationStyle.update(
        parcel, 'presentationStyle',
        format = 'static')

    attributeEditorBlock = blocks.ControlBlocks.AEBlock.update(
        parcel, 'attributeEditorBlock',
        blockName = 'HeadlineBlock',
        alignmentEnum = 'alignTopCenter',
        viewAttribute = 'displayName',
        presentationStyle = aePresentationStyle)
    
    button = blocks.ControlBlocks.Button.update(
        parcel, 'button',
        minimumSize = SizeType (40, 20),
        alignmentEnum = 'alignTopLeft',
        stretchFactor = 0.0,
        title = u'Play')
        
    view = blocks.BoxContainer.update(
        parcel, 'HelloWorldBoxContainer',
        orientationEnum = 'Horizontal',
        eventBoundary = True,
        childBlocks=[button, attributeEditorBlock])
    
    blocks.BranchPoint.ViewableKind(MP3.getKind(repositoryView)).detailView = view

    song = MP3.update(parcel, "French Rock",
                      about = "French Rock")
Esempio n. 53
0
    def takeOnline(self):
        schema.ns("osaf.pim", self._view).MailPrefs.isOnline = True
        self._view.commit()

        for account in Mail.SMTPAccount.getActiveAccounts(self._view):
            if len(account.messageQueue):
                self.getSMTPInstance(account).takeOnline()
Esempio n. 54
0
    def testBiweeklyStatusReport(self):
        item = self.getItem(u"Bi-Weekly Status Report")
        self.checkStampness(item, pim.TaskStamp, pim.EventStamp)

        self.failUnless(item in self.getCollection(u"Work"))
        self.failUnless(item in schema.ns("osaf.pim", self.view).allCollection)
        self.failUnlessEqual(len(list(item.appearsIn)), 2)
        
        masterEvent = pim.EventStamp(item).getMaster()
        self.failUnless(masterEvent.anyTime)
        self.failIf(masterEvent.allDay)
        self.failUnless(masterEvent.userReminderInterval is None)
        firstOccurrence = masterEvent.getFirstOccurrence()
        self.failUnlessEqual(firstOccurrence.itsItem.triageStatus,
                             pim.TriageEnum.now)

        rruleset = masterEvent.rruleset
        self.failUnlessEqual(len(list(rruleset.rrules)), 1)
        self.failUnlessEqual(rruleset.rrules.first().freq, 'weekly')
        self.failUnlessEqual(rruleset.rrules.first().interval, 2)

        # Double-check the bi-weekly thing
        delta = (firstOccurrence.getNextOccurrence().effectiveStartTime - 
                 firstOccurrence.effectiveStartTime)
        self.failUnlessEqual(delta, timedelta(days=14))