def createVTodoFromTask(task): """Create a VTodo object from a yokadi task @param task: yokadi task (db.Task object) @return: ical VTODO (icalendar.Calendar.Todo object)""" vTodo = icalendar.Todo() vTodo["uid"] = TASK_UID % task.id vTodo["related-to"] = PROJECT_UID % task.project.id # Add standard attribute for yokadiAttribute, icalAttribute in YOKADI_ICAL_ATT_MAPPING.items(): attr = getattr(task, yokadiAttribute) if attr: if yokadiAttribute == "urgency": attr = icalutils.yokadiUrgencyToIcalPriority(attr) if yokadiAttribute == "title": attr += " (%s)" % task.id vTodo.add(icalAttribute, attr) # Add categories from keywords categories = [] if task.keywords: for name, value in task.getKeywordDict().items(): if value: categories.append("%s=%s" % (name, value)) else: categories.append(name) vTodo.add("categories", categories) return vTodo
def __init__(self, todo=None, filename=None, mtime=None, new=False): """ Creates a new todo using `todo` as a source. :param icalendar.Todo todo: The icalendar component object on which this todo is based, if applicable. :param str filename: The name of the file for this todo. Defaults to the <uid>.ics :param mtime int: The last modified time for the file backing this Todo. :param bool new: Indicate that a new Todo is being created and should be populated with default values. """ if todo: self.todo = todo else: self.todo = icalendar.Todo() if new: now = datetime.now(self._localtimezone) uid = uuid4().hex + socket.gethostname() self.todo.add('uid', uid) self.todo.add('percent-complete', 0) self.todo.add('priority', 0) self.todo.add('created', now) if self.todo.get('dtstamp', None) is None: self.todo.add('dtstamp', datetime.utcnow()) self.filename = filename or "{}.ics".format(self.todo.get('uid')) if os.path.basename(self.filename) != self.filename: raise ValueError('Must not be an absolute path: {}' .format(self.filename)) self.mtime = mtime or datetime.now()
def __init__(self, **kwargs): self.vtodo = kwargs.pop('vtodo', None) self.callback_mapping = defaultdict(list) self.fields = DEFAULT_DATA.copy() self.fields['uid'] = uuid.uuid4().hex self.fields['created_date'] = self.fields['dtstamp'] = self.fields['last_modified_date'] = self.now(aware=True) self.fields.update(**kwargs) if self.vtodo is None: self.vtodo = icalendar.Todo() self.update_vtodo() def on_complete(): if self.completed_date is not None and not self.completed: self.completed_date = None elif self.completed_date is None and self.completed: self.completed_date = self.now(aware=True) self.connect('progress', on_complete) self.connect('status', on_complete) def update(): _now = self.now(aware=True) if ( self.last_modified_date is not None and abs(self.last_modified_date - _now).total_seconds() > 60 ): self.sequence += 1 self.last_modified_date = _now self.connect_to_all(update)
def dummy_vcal(): cal = icalendar.Calendar() cal.add('prodid', '-//watdo//mimedir.icalendar//EN') cal.add('version', '2.0') todo = icalendar.Todo() todo['uid'] = icalendar.tools.UIDGenerator().uid(host_name='watdo') cal.add_component(todo) return cal
def get(environ, service): headers = [] if environ['PATH_INFO'] != '/' and environ['PATH_INFO'] != '': headers.append(('Content-Type', 'text/calendar')) task_id = environ['PATH_INFO'].split('/')[1] task = service.tasks().get(tasklist=tasklist_id, task=task_id).execute() event = icalendar.Todo() event.add('summary', task['title']) event.add('status', statvalues[task['status']]) return event.as_string() + '\n', httplib.OK, headers else: return 'NOT SUPPORTED\n', httplib.INTERNAL_SERVER_ERROR, headers
def populate(instance, created, **kwargs): if created and not instance.raw: calendar = icalendar.Calendar() calendar["version"] = "2.0" calendar["PRODID"] = "todo-server" event = icalendar.Todo() event.add("uid", instance.pk) event.add("summary", instance.summary) event.add("created", instance.created) calendar.add_component(event) instance.raw = calendar.to_ical().decode("utf-8") instance.save()
def _convert_todo(self, p_todo): """ Converts a Todo instance (Topydo) to an icalendar Todo instance. """ def _get_uid(p_todo): """ Gets a unique ID from a todo item, stored by the ical tag. If the tag is not present, a random value is assigned to it and returned. """ def generate_uid(p_length=4): """ Generates a random string of the given length, used as identifier. """ return ''.join( random.choice(string.ascii_letters + string.digits) for i in xrange(p_length)) uid = p_todo.tag_value('ical') if not uid: uid = generate_uid() p_todo.set_tag('ical', uid) self.todolist.set_dirty() return uid result = ical.Todo() # this should be called first, it may set the ical: tag and therefore # change the source() output. result['uid'] = _get_uid(p_todo) result['summary'] = ical.vText(p_todo.text()) result['description'] = ical.vText(p_todo.source()) result.add('priority', _convert_priority(p_todo.priority())) start = p_todo.start_date() if start: result.add('dtstart', start) due = p_todo.due_date() if due: result.add('due', due) created = p_todo.creation_date() if created: result.add('created', created) completed = p_todo.completion_date() if completed: completed = datetime.combine(completed, time(0, 0)) result.add('completed', completed) return result
def as_string_itip(self, method="REQUEST"): cal = icalendar.Calendar() cal.add( 'prodid', '-//pykolab-%s-%s//kolab.org//' % (constants.__version__, constants.__release__)) cal.add('version', '2.0') cal.add('calscale', 'GREGORIAN') cal.add('method', method) ical_todo = icalendar.Todo() singletons = list(set(ical_todo.singletons)) singletons.extend(['PERCENT-COMPLETE']) for attr in singletons: ical_getter = 'get_ical_%s' % (attr.lower()) default_getter = 'get_%s' % (attr.lower()) retval = None if hasattr(self, ical_getter): retval = getattr(self, ical_getter)() if not retval == None and not retval == "": ical_todo.add(attr.lower(), retval) elif hasattr(self, default_getter): retval = getattr(self, default_getter)() if not retval == None and not retval == "": ical_todo.add(attr.lower(), retval, encode=0) for attr in list(set(ical_todo.multiple)): ical_getter = 'get_ical_%s' % (attr.lower()) default_getter = 'get_%s' % (attr.lower()) retval = None if hasattr(self, ical_getter): retval = getattr(self, ical_getter)() elif hasattr(self, default_getter): retval = getattr(self, default_getter)() if isinstance(retval, list) and not len(retval) == 0: for _retval in retval: ical_todo.add(attr.lower(), _retval, encode=0) # copy custom properties to iCal for cs in self.event.customProperties(): ical_todo.add(cs.identifier, cs.value) cal.add_component(ical_todo) if hasattr(cal, 'to_ical'): return cal.to_ical() elif hasattr(cal, 'as_string'): return cal.as_string()
def serialize(self, original=None): """Serialize a Todo into a VTODO.""" if not original: original = icalendar.Todo() self.vtodo = original for source, target in self.FIELD_MAP.items(): if getattr(self.todo, source): self.set_field( target, self.serialize_field(source, getattr(self.todo, source)), ) return self.vtodo
def make_todo(issue, repo_title=None): if repo_title is None: repo_title = issue.repository.name try: todo = icalendar.Todo() todo['uid'] = make_uid(issue) todo['summary'] = make_title(repo_title, issue) todo['description'] = issue.body todo['url'] = issue.html_url todo['created'] = issue.created_at todo['last-modified'] = issue.updated_at todo['status'] = 'NEEDS-ACTION' todo['organizer'] = make_reporter(issue) return todo except Exception: log.error("Failed to parse %r", t, exc_info=True) return None
def generateCal(): """Generate an ical calendar from yokadi database @return: icalendar.Calendar object""" cal = icalendar.Calendar() cal.add("prodid", '-//Yokadi calendar //yokadi.github.com//') cal.add("version", "2.0") # Add projects for project in Project.select(Project.q.active == True): vTodo = icalendar.Todo() vTodo.add("summary", project.name) vTodo["uid"] = PROJECT_UID % project.id cal.add_component(vTodo) # Add tasks for task in Task.select(Task.q.status != "done"): vTodo = createVTodoFromTask(task) cal.add_component(vTodo) return cal
def generateCal(): """Generate an ical calendar from yokadi database @return: icalendar.Calendar object""" session = db.getSession() cal = icalendar.Calendar() cal.add("prodid", '-//Yokadi calendar //yokadi.github.io//') cal.add("version", "2.0") # Add projects for project in session.query(Project).filter( Project.active == True): # noqa vTodo = icalendar.Todo() vTodo.add("summary", project.name) vTodo["uid"] = PROJECT_UID % project.id cal.add_component(vTodo) # Add tasks for task in session.query(Task).filter(Task.status != "done"): vTodo = createVTodoFromTask(task) cal.add_component(vTodo) return cal
def __init__(self, todo=None, filename=None): """ :param icalendar.Todo todo: The icalendar component object on which this todo is based. If None is passed, a new one is created. :param str filename: The name of the file for this todo. Defaults to the <uid>.ics """ if todo: self.todo = todo else: now = datetime.now(self._localtimezone) self.todo = icalendar.Todo() self.todo.add('uid', uuid4()) self.todo.add('due', now + timedelta(days=1)) self.todo.add('percent-complete', 0) self.todo.add('priority', 0) self.todo.add('created', now) self.filename = filename or "{}.ics".format(self.todo.get('uid'))
def ics_feed(): log.debug('handling a query') if conf is None: log.error("No configuration available") return flask.Response(status_code=500, status='Missing configuration') q_contact = flask.request.args.get('contact') cal = icalendar.Calendar() cal.add('prodid', '-//danielpocock.com//NagiosIssueFeed//') cal.add('version', '1.0') s = mk_livestatus.Socket(conf['livestatus_sock']) q = s.services.columns('state', 'host_alias', 'description', 'plugin_output', 'last_state_change', 'last_check', 'action_url_expanded', 'acknowledged').filter('state > 0') q_contact = flask.request.args.get('contact') if q_contact is not None: log.debug("Contact: %s" % q_contact) q = q.filter('contacts >= %s' % q_contact) result = q.call() log.debug("services query got %d row(s)" % (len(result))) for row in result: try: todo = icalendar.Todo() todo['uid'] = make_uid(row) todo['summary'] = make_title(row) todo['description'] = row['plugin_output'] if row['action_url_expanded']: todo['url'] = row['action_url_expanded'] todo.add('created', parse_nagios_ts(row['last_state_change'])) todo['last-modified'] = parse_nagios_ts(row['last_check']) todo['status'] = get_todo_status(row) todo['organizer'] = make_contact(row) todo['priority'] = make_priority(row) cal.add_component(todo) except Exception: log.error("Failed to parse %r", row, exc_info=True) return flask.Response(status_code=500, status='Error parsing Nagios data') q = s.hosts.columns('state', 'alias', 'plugin_output', 'last_state_change', 'last_check', 'action_url_expanded', 'acknowledged').filter('state > 0') if q_contact is not None: log.debug("Contact: %s" % q_contact) q = q.filter('contacts >= %s' % q_contact) result = q.call() log.debug("hosts query got %d row(s)" % (len(result))) for row in result: try: todo = icalendar.Todo() todo['uid'] = make_uid(row) todo['summary'] = make_title(row) if row['action_url_expanded']: todo['url'] = row['action_url_expanded'] todo.add('created', parse_nagios_ts(row['last_state_change'])) todo['last-modified'] = parse_nagios_ts(row['last_check']) todo['status'] = get_todo_status(row) todo['organizer'] = make_contact(row) todo['priority'] = make_priority(row) cal.add_component(todo) except Exception: log.error("Failed to parse %r", row, exc_info=True) return flask.Response(status_code=500, status='Error parsing Nagios data') log.debug("done, writing response to stream") return flask.Response("%s" % display(cal), mimetype='text/calendar')