Ejemplo n.º 1
0
 def parseDateTime(self, fieldValue, defaultHour=0, defaultMinute=0, 
                   defaultSecond=0, dayfirst=False):
     if not fieldValue:
         return None
     try:
         dateTime = dparser.parse(fieldValue.decode('UTF-8'), 
                                  dayfirst=dayfirst, fuzzy=True).replace(tzinfo=None)
         hour, minute, second = dateTime.hour, dateTime.minute, dateTime.second
         if 0 == hour == minute == second:
             hour = defaultHour
             minute = defaultMinute
             second = defaultSecond
         return DateTime(dateTime.year, dateTime.month, dateTime.day,
                         hour, minute, second)
     except:  # pylint: disable=W0702
         return None  
Ejemplo n.º 2
0
 def parseDateTime(self, fieldValue, defaultHour=0, defaultMinute=0, 
                   defaultSecond=0, dayfirst=False):
     if not fieldValue:
         return None
     try:
         dateTime = dparser.parse(fieldValue.decode('UTF-8'), 
                                  dayfirst=dayfirst, fuzzy=True).replace(tzinfo=None)
         hour, minute, second = dateTime.hour, dateTime.minute, dateTime.second
         if 0 == hour == minute == second:
             hour = defaultHour
             minute = defaultMinute
             second = defaultSecond
         return DateTime(dateTime.year, dateTime.month, dateTime.day,
                         hour, minute, second)
     except:  # pylint: disable=W0702
         return None  
Ejemplo 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)