Beispiel #1
0
def todo_add(caldav_conn, args):
    ## TODO: copied from calendar_add, should probably be consolidated
    if args.icalendar or args.nocaldav:
        niy(feature="add todo item by icalendar raw stdin data or create raw icalendar data to stdout")
    if args.todo_uid:
        uid = args.todo_uid
    else:
        uid = uuid.uuid1()
    cal = Calendar()
    cal.add('prodid', '-//{author_short}//{product}//{language}'.format(author_short=__author_short__, product=__product__, language=args.language))
    cal.add('version', '2.0')
    todo = Todo()
    todo.add('dtstamp', _now())

    for setarg in ('due', 'dtstart'):
        if getattr(args, 'set_'+setarg):
            if type(getattr(args, 'set_'+setarg)) == str:
                val = dateutil.parser.parse(getattr(args, 'set_'+setarg))
            else:
                val = getattr(args, 'set_'+setarg)
            todo.add(setarg, val)
    todo.add('uid', str(uid))
    todo.add('summary', ' '.join(args.summaryline))
    todo.add('status', 'NEEDS-ACTION')

    if args.is_child:
        for t in todo_select(caldav_conn, args):
            todo.add('related-to', t.instance.vtodo.uid.value)
            rt = t.instance.vtodo.add('related-to')
            rt.params['RELTYPE']=['CHILD']
            rt.value = str(uid)
            t.save()

    for attr in vtodo_txt_one:
        if attr == 'summary':
            continue
        val = getattr(args, 'set_'+attr)
        if val:
            todo.add(attr, val)
    ## TODO: this doesn't currently work quite the way we'd like it to
    ## work (it adds to lines to the ical, and vobject cares only
    ## about one of them), and if we do get it to work, we'd like to
    ## refactor and get the same logic in the edit-function
    for attr in vtodo_txt_many:
        val = getattr(args, 'set_'+attr)
        if val:
            vals = val.split(',')
            todo.add(attr, vals)

    if args.alarm is not None:
        alarm = create_alarm(' '.join(args.summaryline), parse_time_delta(args.alarm))
        todo.add_component(alarm)

    cal.add_component(todo)
    _calendar_addics(caldav_conn, cal.to_ical(), uid, args)
    print("Added todo item with uid=%s" % uid)
def todo_add(caldav_conn, args):
    ## TODO: copied from calendar_add, should probably be consolidated
    if args.icalendar or args.nocaldav:
        niy(feature=
            "add todo item by icalendar raw stdin data or create raw icalendar data to stdout"
            )
    if args.todo_uid:
        uid = args.todo_uid
    else:
        uid = uuid.uuid1()
    cal = Calendar()
    cal.add(
        'prodid', '-//{author_short}//{product}//{language}'.format(
            author_short=__author_short__,
            product=__product__,
            language=args.language))
    cal.add('version', '2.0')
    todo = Todo()
    ## TODO: what does the cryptic comment here really mean, and why was the dtstamp commented out?  dtstamp is required according to the RFC.
    ## TODO: (cryptic old comment:) not really correct, and it breaks i.e. with google calendar
    todo.add('dtstamp', datetime.now())

    for arg in ('set_due', 'set_dtstart'):
        if getattr(args, arg):
            if type(getattr(args, arg)) == str:
                val = dateutil.parser.parse(getattr(args, arg))
            else:
                val = getattr(args, arg)
        todo.add(arg, val)
    todo.add('uid', str(uid))
    todo.add('summary', ' '.join(args.summaryline))
    todo.add('status', 'NEEDS-ACTION')

    if args.is_child:
        for t in todo_select(caldav_conn, args):
            todo.add('related-to', t.instance.vtodo.uid.value)
            rt = t.instance.vtodo.add('related-to')
            rt.params['RELTYPE'] = ['CHILD']
            rt.value = str(uid)
            t.save()

    for attr in vtodo_txt_one + vtodo_txt_many:
        if attr == 'summary':
            continue
        val = getattr(args, 'set_' + attr)
        if val:
            todo.add(attr, val)
    cal.add_component(todo)
    _calendar_addics(caldav_conn, cal.to_ical(), uid, args)
    print("Added todo item with uid=%s" % uid)
Beispiel #3
0
 def write_items(self, calendar):
     """
     Write all events to the calendar
     """
     for item in self.items:
         event = Event() if vText(
             'MEETING') in item['categories'] else Todo()
         for ifield, efield in ITEM_EVENT_FIELD_MAP:
             val = item.get(ifield)
             if isinstance(val, list):
                 for list_item in val:
                     event.add(efield, list_item)
             elif val is not None:
                 event.add(efield, val)
         calendar.add_component(event)
Beispiel #4
0
def createVTODOs(task, parent=None):
    todos = []
    todo = Todo()
    try:
        todo.add('UID', str(task['id']))
    except KeyError:
        todo.add('UID', str(uuid.uuid1()))
    try:
        todo.add('dtstamp', datetime.strptime(task['createdAt'], "%Y-%m-%dT%H:%M:%S.%f%z"))
    except ValueError: #Thank you for using different formats within the same field!
        try:
            todo.add('dtstamp', datetime.strptime(task['createdAt'], "%Y-%m-%dT%H:%M:%S%z"))
        except:
            logger.error('Could not parse creation date for Task {}'.format(task['id']))
            quit()
    todo.add('summary', task.get('title', ''))
    if task.get('dueDate', None) is not None:
        todo.add('DUE', datetime.strptime(task['dueDate'], "%Y-%m-%dT%H:%M:%S"))
    if task['completed']:
        todo.add('status', 'COMPLETED')
        todo.add('PERCENT-COMPLETE', '100')
        todo.add('COMPLETED', datetime.strptime(task['completedAt'], "%Y-%m-%dT%H:%M:%S.%f%z"))
        todo.add('LAST-MODIFIED', datetime.strptime(task['completedAt'], "%Y-%m-%dT%H:%M:%S.%f%z"))
    todo.add('COMMENT', task.get('notes', ''))
    if task.get('reminders', False):
        reminders = []
        for reminder in task['reminders']:
            try:
                reminders += [datetime.strptime(reminder['remindAt'], "%Y-%m-%dT%H:%M:%S.%f%z")]
            except ValueError: #Thank you for using different formats within the same file!
                try:
                    reminders += [datetime.strptime(reminder['remindAt'], "%Y-%m-%dT%H:%M:%S%z")]
                except:
                    logger.error('Could not parse reminder date for Task {}'.format(task['id']))
        logger.debug('Task {} has {} reminders. Not supported'.format(task['id'], len(reminders)))
    if task.get('comment', False):
        todo.add('description', task['comment'])
    if task.get('files', False):
        logger.error('There are files linked!')
    if parent is not None:
        todo.add('RELATED-TO', parent)
    todos.extend([todo])
    if task.get('subtasks', False):
        logger.debug('Task {} has {} subtasks'.format(task['id'], len(task['subtasks'])))
        for subtask in task['subtasks']:
            todos.extend(createVTODOs(subtask, parent=task['id']))
    return todos
Beispiel #5
0
    'E': 'EASTERLY',
}

ical_freq_hsh = {
    'YEARLY': 'y',
    'MONTHLY': 'm',
    'WEEKLY': 'w',
    'DAILY': 'd',
    'HOURLY': 'h',
    'MINUTELY': 'n',
    # 'EASTERLY': 'e'
}

item_types = {
        '*': Event(),
        '-': Todo(),
        '%': Journal()
        }


# BEGIN:VCALENDAR
# VERSION:2.0
# PRODID:-//etm_tk 3.2.38//dgraham.us//
# BEGIN:VEVENT
# SUMMARY:Charleston Volvo Open
# DTSTART;VALUE=DATE:20190402
# UID:f42d3035fd634835a01f6193a925f32eetm
# RRULE:FREQ=DAILY;COUNT=4
# END:VEVENT
# END:VCALENDAR
 
Beispiel #6
0
def create_calendar_feed(user, secret):
    if True:  #try:
        # check access
        enabled = frappe.db.get_value("Calendar Feed Settings",
                                      "Calendar Feed Settings", "enabled")
        if float(enabled) == 0:
            return
        erp_secret = frappe.db.get_value("Calendar Feed Settings",
                                         "Calendar Feed Settings", "secret")
        if not secret == erp_secret:
            return

        # initialise calendar
        cal = Calendar()

        # set properties
        cal.add('prodid', '-//finkzeit//libracore//')
        cal.add('version', '2.0')

        # get data for public events
        show_public_events = frappe.db.get_value("Calendar Feed Settings",
                                                 "Calendar Feed Settings",
                                                 "show_public_events")
        if float(show_public_events) == 1:
            sql_query = """SELECT `subject`, `starts_on`, `ends_on`, `modified`, `description`
                 FROM `tabEvent` 
                 WHERE `event_type` = 'Public'"""
            events = frappe.db.sql(sql_query, as_dict=True)
            # add events
            for erp_event in events:
                event = Event()
                event.add('summary', erp_event['subject'])
                event.add('dtstart', erp_event['starts_on'])
                if erp_event['ends_on']:
                    event.add('dtend', erp_event['ends_on'])
                event.add('dtstamp', erp_event['modified'])
                event.add('description', erp_event['description'])
                # add to calendar
                cal.add_component(event)

        # get data for personal events
        sql_query = """SELECT `subject`, `starts_on`, `ends_on`, `modified`, `description` 
             FROM `tabEvent` 
             WHERE `event_type` = 'Private'
               AND (`owner` = '{user}' OR `modified_by` = '{user}')""".format(
            user=user)
        events = frappe.db.sql(sql_query, as_dict=True)
        # add events
        for erp_event in events:
            event = Event()
            event.add('summary', erp_event['subject'])
            event.add('dtstart', erp_event['starts_on'])
            if erp_event['ends_on']:
                event.add('dtend', erp_event['ends_on'])
            event.add('dtstamp', erp_event['modified'])
            event.add('description', erp_event['description'])
            # add to calendar
            cal.add_component(event)

        # get data for personal todo's
        sql_query = """SELECT 
               IFNULL(`reference_type`, '-') AS `reference_type`, 
               IFNULL(`reference_name`, '-') AS `reference_name`,
               `description`, 
               `modified`, 
               `date` 
             FROM `tabToDo` 
             WHERE `status` = 'Open'
               AND (`owner` = '{user}' OR `modified_by` = '{user}')""".format(
            user=user)
        todos = frappe.db.sql(sql_query, as_dict=True)
        # add events
        for erp_todo in todos:
            todo = Todo()
            todo.add(
                'summary', "{0} {1}".format(erp_todo['reference_type'],
                                            erp_todo['reference_name']))
            todo.add('dtstamp', erp_todo['modified'])
            todo.add('description', erp_todo['description'])
            if erp_todo['date']:
                todo.add('due', erp_todo['date'])
            todo.add('status', 'Open')
            # add to calendar
            cal.add_component(todo)

        # return calendar object
        return cal
Beispiel #7
0
def make_todo(item: ToDoItem) -> Todo:
    todo = Todo()
    todo['uid'] = item.id
    todo['summary'] = item.title
    todo['status'] = "Completed" if item.completed else "In Progress"
    return todo
Beispiel #8
0
def TodoFromJSON(cal, data):
    tz = pytz.timezone("Europe/Budapest")
    if 'dynalist_info' in data:
        if data['note'] == '':
            description = data['dynalist_info']
        else:
            description = data['note'] + '\n' + data['dynalist_info']
    else:
        description = data['note']
    duedate = data['date'].replace('-', '')
    time = data['time'].replace(':', '')
    if not duedate == '':
        Y = int(duedate[:4])
        m = int(duedate[4:6])
        D = int(duedate[6:8])
        if not time == '':
            H = int(time[:2])
            M = int(time[2:4])

    if cal is None:
        cal = Calendar()
        cal.add('prodid', '-//Dynatask//')
        cal.add('version', '2.0')
        todo = Todo()
        if 'dynalist_id' in data:
            todo.add('uid', data['caldav_uid'])
            todo.add('X-DYNATASK-DYNALISTID', data['dynalist_id'])
        elif 'caldav_uid' in data:
            todo.add('uid', data['caldav_uid'])
        todo.add('summary', data['name'])
        now = datetime.now(pytz.utc)
        todo.add('dtstamp', now)
        todo.add('created', now)
        todo.add('last-modified', now)
        if not duedate == '':
            if not time == '':
                todo.add('due', datetime(Y, m, D, H, M, tzinfo=tz))
            else:
                todo.add('due', datetime(Y, m, D).date())
        todo.add('description', description)

        if 'checked' in data:
            if data['checked']:
                todo.add('status', 'COMPLETED')
                todo.add('completed', datetime.now(pytz.utc))
                todo.add('percent-complete', '100')
            else:
                todo.add('status', 'NEEDS-ACTION')
                todo.add('percent-complete', '0')

        if 'caldav_parent' in data:
            todo.add('related-to', data['caldav_parent'])

        if 'alarm' in data and not data['alarm'] == '':
            alarm = Alarm()
            alarm.add('action', 'DISPLAY')
            alarm.add('trigger', timedelta(minutes=-int(data['alarm'])))
            todo.add_component(alarm)

        cal.add_component(todo)
        return (cal)