Esempio n. 1
0
    def _parseObject(self, item):
        parser = vcal.VCalendarParser()
        parser.parse(map(lambda x: x.rstrip('\r'), item.data.split('\n')))

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

        task = Task(**parser.tasks[0])

        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
Esempio n. 2
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
Esempio n. 3
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)
Esempio n. 4
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+)$')

        reader = self.createReader(fp, kwargs['dialect'], kwargs['hasHeaders'])
        dayfirst = kwargs['dayfirst']
        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
            actualStartDateTime = None
            plannedStartDateTime = None
            dueDateTime = None
            completionDateTime = None
            reminderDateTime = None
            budget = TimeDelta()
            fixedFee = 0.0
            hourlyFee = 0.0
            percentComplete = 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')
                    if name.startswith('(') and name.endswith(')'):
                        continue  # Skip categories of subitems
                    cat = self.categoryList.findCategoryByName(name)
                    if not cat:
                        cat = self.createCategory(name)
                    categories.append(cat)
                elif kwargs['mappings'][idx] == _('Priority'):
                    try:
                        priority = int(fieldValue)
                    except ValueError:
                        pass
                elif kwargs['mappings'][idx] == _('Actual start date'):
                    actualStartDateTime = self.parseDateTime(fieldValue, dayfirst=dayfirst)
                elif kwargs['mappings'][idx] == _('Planned start date'):
                    plannedStartDateTime = self.parseDateTime(fieldValue, dayfirst=dayfirst)
                elif kwargs['mappings'][idx] == _('Due date'):
                    dueDateTime = self.parseDateTime(fieldValue, 23, 59, 59, dayfirst=dayfirst) 
                elif kwargs['mappings'][idx] == _('Completion date'):
                    completionDateTime = self.parseDateTime(fieldValue, 12, 0, 0, dayfirst=dayfirst) 
                elif kwargs['mappings'][idx] == _('Reminder date'):
                    reminderDateTime = self.parseDateTime(fieldValue, dayfirst=dayfirst)
                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
                elif kwargs['mappings'][idx] == _('Percent complete'):
                    try:
                        percentComplete = max(0, min(100, int(fieldValue)))
                    except ValueError:
                        pass

            task = Task(subject=subject,
                        description=description.getvalue(),
                        priority=priority,
                        actualStartDateTime=actualStartDateTime,
                        plannedStartDateTime=plannedStartDateTime,
                        dueDateTime=dueDateTime,
                        completionDateTime=completionDateTime,
                        reminder=reminderDateTime,
                        budget=budget,
                        fixedFee=fixedFee,
                        hourlyFee=hourlyFee,
                        percentageComplete=percentComplete)

            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)
Esempio n. 5
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+)$')

        reader = self.createReader(fp, kwargs['dialect'], kwargs['hasHeaders'])
        dayfirst = kwargs['dayfirst']
        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
            actualStartDateTime = None
            plannedStartDateTime = None
            dueDateTime = None
            completionDateTime = None
            reminderDateTime = None
            budget = TimeDelta()
            fixedFee = 0.0
            hourlyFee = 0.0
            percentComplete = 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')
                    if name.startswith('(') and name.endswith(')'):
                        continue  # Skip categories of subitems
                    cat = self.categoryList.findCategoryByName(name)
                    if not cat:
                        cat = self.createCategory(name)
                    categories.append(cat)
                elif kwargs['mappings'][idx] == _('Priority'):
                    try:
                        priority = int(fieldValue)
                    except ValueError:
                        pass
                elif kwargs['mappings'][idx] == _('Actual start date'):
                    actualStartDateTime = self.parseDateTime(fieldValue,
                                                             dayfirst=dayfirst)
                elif kwargs['mappings'][idx] == _('Planned start date'):
                    plannedStartDateTime = self.parseDateTime(
                        fieldValue, dayfirst=dayfirst)
                elif kwargs['mappings'][idx] == _('Due date'):
                    dueDateTime = self.parseDateTime(fieldValue,
                                                     23,
                                                     59,
                                                     59,
                                                     dayfirst=dayfirst)
                elif kwargs['mappings'][idx] == _('Completion date'):
                    completionDateTime = self.parseDateTime(fieldValue,
                                                            12,
                                                            0,
                                                            0,
                                                            dayfirst=dayfirst)
                elif kwargs['mappings'][idx] == _('Reminder date'):
                    reminderDateTime = self.parseDateTime(fieldValue,
                                                          dayfirst=dayfirst)
                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
                elif kwargs['mappings'][idx] == _('Percent complete'):
                    try:
                        percentComplete = max(0, min(100, int(fieldValue)))
                    except ValueError:
                        pass

            task = Task(subject=subject,
                        description=description.getvalue(),
                        priority=priority,
                        actualStartDateTime=actualStartDateTime,
                        plannedStartDateTime=plannedStartDateTime,
                        dueDateTime=dueDateTime,
                        completionDateTime=completionDateTime,
                        reminder=reminderDateTime,
                        budget=budget,
                        fixedFee=fixedFee,
                        hourlyFee=hourlyFee,
                        percentageComplete=percentComplete)

            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)