Example #1
0
 def createCategory(self, name):
     if ' -> ' in name:
         parentName, childName = name.rsplit(' -> ', 1)
         parent = self.categoryList.findCategoryByName(parentName)
         if not parent:
             parent = self.createCategory(parentName)
         newCategory = Category(subject=childName)
         parent.addChild(newCategory)
         newCategory.setParent(parent)
     else:
         newCategory = Category(subject=name)
     self.categoryList.append(newCategory)
     return newCategory
    def setUp(self):
        self.monitor = ChangeMonitor()
        self.monitor.monitorClass(CategorizableCompositeObject)

        self.obj = CategorizableCompositeObject(subject=u'Object')
        self.list = ObservableList()
        self.monitor.monitorCollection(self.list)
        self.list.append(self.obj)

        self.cat1 = Category(subject=u'Cat #1')
        self.cat2 = Category(subject=u'Cat #2')
        self.catList = ObservableList()
        self.catList.append(self.cat1)
        self.catList.append(self.cat2)
Example #3
0
    def doResolveConflict(self, task, local, result):
        resolved = self.callback.resolveTaskConflict(result, local, task)

        if resolved.has_key('subject'):
            local.setSubject(resolved['subject'])
        if resolved.has_key('description'):
            local.setDescription(resolved['description'])
        if resolved.has_key('startDateTime'):
            local.setStartDateTime(resolved['startDateTime'])
        if resolved.has_key('dueDateTime'):
            local.setDueDateTime(resolved['dueDateTime'])
        if resolved.has_key('priority'):
            local.setPriority(resolved['priority'])
        if resolved.has_key('completionDateTime'):
            local.setCompletionDateTime(resolved['completionDateTime'])
        if resolved.has_key('categories'):
            # Ahah,      tricky       part.      This      is      why
            # callback.resolvedXXXConflict return dictionaries instead
            # of Task object.

            for category in local.categories().copy():
                category.removeCategorizable(local)
                local.removeCategory(category)

            for category in resolved['categories'].split(','):
                categoryObject = self.categoryList.findCategoryByName(category)
                if categoryObject is None:
                    categoryObject = Category(category)
                    self.categoryList.extend([categoryObject])
                local.addCategory(categoryObject)

            for category in local.categories():
                category.addCategorizable(local)

        return local
Example #4
0
    def handleNewObject(self, args):
        if self.version < 3:
            name = args
            parentId = None
        else:
            name, parentId = args
            self.disp().log(_('New category (parent: %s)'), parentId)

        if parentId is None or not self.categoryMap.has_key(parentId):
            category = Category(name)
        else:
            category = self.categoryMap[parentId].newChild(name)

        self.disp().window.addIPhoneCategory(category)

        self.categoryMap[category.id()] = category
        self.pack('s', category.id())
Example #5
0
    def handleNewObject(self, args):
        if self.version < 3:
            name = args
            parentId = None
        else:
            name, parentId = args
            self.disp().log(_('New category (parent: %s)'), parentId)

        if parentId is None or not self.categoryMap.has_key(parentId):
            category = Category(name)
        else:
            category = self.categoryMap[parentId].newChild(name)

        self.disp().window.addIPhoneCategory(category)

        self.categoryMap[category.id()] = category
        self.pack('s', category.id())
Example #6
0
    def handleNewObject(self, args):
        if self.version < 3:
            name = args
            parentId = None
        else:
            name, parentId = args

        if parentId is None:
            category = Category(name)
        else:
            category = self.categoryMap[parentId].newChild(name)

        self.disp().window.addIPhoneCategory(category)

        self.pack('s', category.id())
        self.categoryMap[category.id()] = category

        self.count += 1
        self.ui.SetProgress(self.count, self.total)
Example #7
0
    def handleNewObject(self, args):
        if self.version < 3:
            name = args
            parentId = None
        else:
            name, parentId = args

        if parentId is None:
            category = Category(name)
        else:
            category = self.categoryMap[parentId].newChild(name)

        self.disp().window.addIPhoneCategory(category)

        self.pack('s', category.id())
        self.categoryMap[category.id()] = category

        self.count += 1
        self.ui.SetProgress(self.count, self.total)
class MonitorCategorizableTest(test.TestCase):
    def setUp(self):
        self.monitor = ChangeMonitor()
        self.monitor.monitorClass(CategorizableCompositeObject)

        self.obj = CategorizableCompositeObject(subject=u'Object')
        self.list = ObservableList()
        self.monitor.monitorCollection(self.list)
        self.list.append(self.obj)

        self.cat1 = Category(subject=u'Cat #1')
        self.cat2 = Category(subject=u'Cat #2')
        self.catList = ObservableList()
        self.catList.append(self.cat1)
        self.catList.append(self.cat2)

    def tearDown(self):
        self.monitor.unmonitorClass(CategorizableCompositeObject)
        self.monitor.unmonitorCollection(self.list)

    def testAddCategory(self):
        self.monitor.resetAllChanges()
        self.obj.addCategory(self.cat1)
        self.assertEqual(self.monitor.getChanges(self.obj),
                         set(['__add_category:%s' % self.cat1.id()]))

    def testRemoveCategory(self):
        self.obj.addCategory(self.cat1)
        self.monitor.resetAllChanges()
        self.obj.removeCategory(self.cat1)
        self.assertEqual(self.monitor.getChanges(self.obj),
                         set(['__del_category:%s' % self.cat1.id()]))

    def testRemoveBadCategory(self):
        self.obj.addCategory(self.cat1)
        self.monitor.resetAllChanges()
        self.obj.removeCategory(self.cat2)
        self.assertEqual(self.monitor.getChanges(self.obj), set())
    def setUp(self):
        self.monitor = ChangeMonitor()
        self.monitor.monitorClass(CategorizableCompositeObject)

        self.obj = CategorizableCompositeObject(subject=u'Object')
        self.list = ObservableList()
        self.monitor.monitorCollection(self.list)
        self.list.append(self.obj)

        self.cat1 = Category(subject=u'Cat #1')
        self.cat2 = Category(subject=u'Cat #2')
        self.catList = ObservableList()
        self.catList.append(self.cat1)
        self.catList.append(self.cat2)
Example #10
0
    def _parseObject(self, item):
        parser = ical.VCalendarParser()
        parser.parse(map(lambda x: x.rstrip('\r'), item.data.split('\n')))

        categories = parser.tasks[0].pop('categories', [])

        kwargs = dict([(k, v) for k, v in parser.tasks[0].items() if k in inspect.getargspec(Task.__init__)[0]])
        task = Task(**kwargs)

        for category in categories:
            categoryObject = self.categoryList.findCategoryByName(category)
            if categoryObject is None:
                categoryObject = Category(category)
                self.categoryList.extend([categoryObject])
            task.addCategory(categoryObject)

        return task
Example #11
0
 def createCategory(self, name):
     if ' -> ' in name:
         parentName, childName = name.rsplit(' -> ', 1)
         parent = self.categoryList.findCategoryByName(parentName)
         if not parent:
             parent = self.createCategory(parentName)
         newCategory = Category(subject=childName)
         parent.addChild(newCategory)
         newCategory.setParent(parent)
     else:
         newCategory = Category(subject=name)
     self.categoryList.append(newCategory)
     return newCategory
Example #12
0
    def _parseObject(self, item):
        parser = ical.VCalendarParser()
        parser.parse(
            map(lambda x: x.rstrip('\r'),
                item.data.strip().split('\n')))
        categories = parser.notes[0].pop('categories', [])

        kwargs = dict([(k, v) for k, v in parser.notes[0].items()
                       if k in ['subject', 'description', 'id']])
        note = Note(**kwargs)

        for category in categories:
            categoryObject = self.categoryList.findCategoryByName(category)
            if categoryObject is None:
                categoryObject = Category(category)
                self.categoryList.extend([categoryObject])
            note.addCategory(categoryObject)

        return note
Example #13
0
    def _parseObject(self, item):
        # Horde doesn't seem to give a f**k about the supported types we send it.
        if item.dataType == 'text/plain':
            lines = map(lambda x: x.rstrip('\r'), item.data.split('\n'))
            kwargs = dict(subject=lines[0], description='\n'.join(lines[1:])) if lines else dict()
            categories = list()
        else:
            parser = ical.VCalendarParser()
            parser.parse(map(lambda x: x.rstrip('\r'), item.data.strip().split('\n')))
            categories = parser.notes[0].pop('categories', [])

            kwargs = dict([(k, v) for k, v in parser.notes[0].items() if k in ['subject', 'description', 'id']])

        note = Note(**kwargs)
        for category in categories:
            categoryObject = self.categoryList.findCategoryByName(category)
            if categoryObject is None:
                categoryObject = Category(category)
                self.categoryList.extend([categoryObject])
            note.addCategory(categoryObject)
        return note
Example #14
0
    def read(self, **kwargs):
        fp = tempfile.TemporaryFile()
        fp.write(file(kwargs['filename'], 'rb').read().decode(kwargs['encoding']).encode('UTF-8'))
        fp.seek(0)

        rx1 = re.compile(r'^(\d+):(\d+)$')
        rx2 = re.compile(r'^(\d+):(\d+):(\d+)$')

        # When fields are associated with categories, create a top-level category for the
        # field and a subcategory for each possible value.

        toplevelCategories = dict()
        for idx, headerName in enumerate(kwargs['fields']):
            if kwargs['mappings'][idx] == _('Category'):
                category = Category(subject=headerName)
                toplevelCategories[headerName] = (category, dict())
                self.categoryList.append(category)

        reader = csv.reader(fp, dialect=kwargs['dialect'])
        if kwargs['hasHeaders']:
            reader.next()

        tasksById = dict()
        tasks = []

        for index, line in enumerate(reader):
            if kwargs['importSelectedRowsOnly'] and index not in kwargs['selectedRows']:
                continue
            subject = _('No subject')
            id_ = None
            description = StringIO.StringIO()
            categories = []
            priority = 0
            startDate = None
            dueDate = None
            completionDate = None
            budget = TimeDelta()
            fixedFee = 0.0
            hourlyFee = 0.0

            for idx, fieldValue in enumerate(line):
                if kwargs['mappings'][idx] == _('ID'):
                    id_ = fieldValue.decode('UTF-8')
                elif kwargs['mappings'][idx] == _('Subject'):
                    subject = fieldValue.decode('UTF-8')
                elif kwargs['mappings'][idx] == _('Description'):
                    description.write(fieldValue.decode('UTF-8'))
                    description.write(u'\n')
                elif kwargs['mappings'][idx] == _('Category') and fieldValue:
                    name = fieldValue.decode('UTF-8')
                    parent, cats = toplevelCategories[kwargs['fields'][idx]]
                    if name in cats:
                        theCat = cats[name]
                    else:
                        theCat = Category(subject=name)
                        parent.addChild(theCat)
                        cats[name] = theCat
                        self.categoryList.append(theCat)
                    categories.append(theCat)
                    toplevelCategories[kwargs['fields'][idx]] = (parent, cats)
                elif kwargs['mappings'][idx] == _('Priority'):
                    try:
                        priority = int(fieldValue)
                    except ValueError:
                        pass
                elif kwargs['mappings'][idx] == _('Start date'):
                    if fieldValue != '':
                        try:
                            startDate = dparser.parse(fieldValue.decode('UTF-8'), fuzzy=True).replace(tzinfo=None)
                            startDate = DateTime(startDate.year, startDate.month, startdate.day, 0, 0, 0)
                        except:
                            pass
                elif kwargs['mappings'][idx] == _('Due date'):
                    if fieldValue != '':
                        try:
                            dueDate = dparser.parse(fieldValue.decode('UTF-8'), fuzzy=True).replace(tzinfo=None)
                            dueDate = DateTime(dueDate.year, dueDate.month, dueDate.day, 23, 59, 0)
                        except:
                            pass
                elif kwargs['mappings'][idx] == _('Completion date'):
                    if fieldValue != '':
                        try:
                            completionDate = dparser.parse(fieldValue.decode('UTF-8'), fuzzy=True).replace(tzinfo=None)
                            completionDate = DateTime(completionDate.year, completionDate.month, completionDate.day, 12, 0, 0)
                        except:
                            pass
                elif kwargs['mappings'][idx] == _('Budget'):
                    try:
                        value = float(fieldValue)
                        hours = int(math.floor(value))
                        minutes = int(60 * (value - hours))
                        budget = TimeDelta(hours=hours, minutes=minutes, seconds=0)
                    except ValueError:
                        mt = rx1.search(fieldValue)
                        if mt:
                            budget = TimeDelta(hours=int(mt.group(1)), minutes=int(mt.group(2)), seconds=0)
                        else:
                            mt = rx2.search(fieldValue)
                            if mt:
                                budget = TimeDelta(hours=int(mt.group(1)), minutes=int(mt.group(2)), seconds=int(mt.group(3)))
                elif kwargs['mappings'][idx] == _('Fixed fee'):
                    try:
                        fixedFee = float(fieldValue)
                    except ValueError:
                        pass
                elif kwargs['mappings'][idx] == _('Hourly fee'):
                    try:
                        hourlyFee = float(fieldValue)
                    except ValueError:
                        pass

            task = Task(subject=subject,
                        description=description.getvalue(),
                        priority=priority,
                        startDateTime=startDate,
                        dueDateTime=dueDate,
                        completionDateTime=completionDate,
                        budget=budget,
                        fixedFee=fixedFee,
                        hourlyFee=hourlyFee)

            if id_ is not None:
                tasksById[id_] = task

            for category in categories:
                category.addCategorizable(task)
                task.addCategory(category)

            tasks.append(task)

        # OmniFocus uses the task's ID to keep track of hierarchy: 1 => 1.1 and 1.2, etc...

        if tasksById:
            ids = []
            for id_, task in tasksById.items():
                try:
                    ids.append(tuple(map(int, id_.split('.'))))
                except ValueError:
                    self.taskList.append(task)

            ids.sort()
            ids.reverse()

            for id_ in ids:
                sid = '.'.join(map(str, id_))
                if len(id_) >= 2:
                    pid = '.'.join(map(str, id_[:-1]))
                    if pid in tasksById:
                        tasksById[pid].addChild(tasksById[sid])
                else:
                    self.taskList.append(tasksById[sid])
        else:
            self.taskList.extend(tasks)
class MonitorCategorizableTest(test.TestCase):
    def setUp(self):
        self.monitor = ChangeMonitor()
        self.monitor.monitorClass(CategorizableCompositeObject)

        self.obj = CategorizableCompositeObject(subject=u'Object')
        self.list = ObservableList()
        self.monitor.monitorCollection(self.list)
        self.list.append(self.obj)

        self.cat1 = Category(subject=u'Cat #1')
        self.cat2 = Category(subject=u'Cat #2')
        self.catList = ObservableList()
        self.catList.append(self.cat1)
        self.catList.append(self.cat2)

    def tearDown(self):
        self.monitor.unmonitorClass(CategorizableCompositeObject)
        self.monitor.unmonitorCollection(self.list)

    def testAddCategory(self):
        self.monitor.resetAllChanges()
        self.obj.addCategory(self.cat1)
        self.assertEqual(self.monitor.getChanges(self.obj), set(['__add_category:%s' % self.cat1.id()]))

    def testRemoveCategory(self):
        self.obj.addCategory(self.cat1)
        self.monitor.resetAllChanges()
        self.obj.removeCategory(self.cat1)
        self.assertEqual(self.monitor.getChanges(self.obj), set(['__del_category:%s' % self.cat1.id()]))

    def testRemoveBadCategory(self):
        self.obj.addCategory(self.cat1)
        self.monitor.resetAllChanges()
        self.obj.removeCategory(self.cat2)
        self.assertEqual(self.monitor.getChanges(self.obj), set())