repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
jspricke/python-remind
remind.py
Remind._gen_vevent
python
def _gen_vevent(self, event, vevent): vevent.add('dtstart').value = event['dtstart'][0] vevent.add('dtstamp').value = datetime.fromtimestamp(self._mtime) vevent.add('summary').value = event['msg'] vevent.add('uid').value = event['uid'] if 'class' in event: vevent.add('class').value = event['class'] if 'categories' in event and len(event['categories']) > 0: vevent.add('categories').value = event['categories'] if 'location' in event: vevent.add('location').value = event['location'] if 'description' in event: vevent.add('description').value = event['description'] if isinstance(event['dtstart'][0], datetime): if self._alarm != timedelta(): valarm = vevent.add('valarm') valarm.add('trigger').value = self._alarm valarm.add('action').value = 'DISPLAY' valarm.add('description').value = event['msg'] if 'duration' in event: vevent.add('duration').value = event['duration'] else: vevent.add('dtend').value = event['dtstart'][0] elif len(event['dtstart']) == 1: vevent.add('dtend').value = event['dtstart'][0] + timedelta(days=1) if len(event['dtstart']) > 1: Remind._gen_dtend_rrule(event['dtstart'], vevent)
Generate vevent from given event
train
https://github.com/jspricke/python-remind/blob/dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1/remind.py#L208-L243
[ "def _gen_dtend_rrule(dtstarts, vevent):\n \"\"\"Generate an rdate or rrule from a list of dates and add it to the vevent\"\"\"\n interval = Remind._interval(dtstarts)\n if interval > 0 and interval % 7 == 0:\n rset = rrule.rruleset()\n rset.rrule(rrule.rrule(freq=rrule.WEEKLY, interval=inter...
class Remind(object): """Represents a collection of Remind files""" def __init__(self, filename=expanduser('~/.reminders'), localtz=None, startdate=date.today() - timedelta(weeks=12), month=15, alarm=timedelta(minutes=-10)): """Constructor filename -- the remind file (included files will be used as well) localtz -- the timezone of the remind file startdate -- the date to start parsing, will be passed to remind month -- how many month to parse, will be passed to remind -s """ self._localtz = localtz if localtz else get_localzone() self._filename = filename self._startdate = startdate self._month = month self._lock = Lock() self._reminders = {} self._mtime = 0 self._alarm = alarm self._update() def _parse_remind(self, filename, lines=''): """Calls remind and parses the output into a dict filename -- the remind file (included files will be used as well) lines -- used as stdin to remind (filename will be set to -) """ files = {} reminders = {} if lines: filename = '-' files[filename] = lines reminders[filename] = {} cmd = ['remind', '-l', '-s%d' % self._month, '-b1', '-y', '-r', filename, str(self._startdate)] try: rem = Popen(cmd, stdin=PIPE, stdout=PIPE).communicate(input=lines.encode('utf-8'))[0].decode('utf-8') except OSError: raise OSError('Error running: %s' % ' '.join(cmd)) rem = rem.splitlines() for (fileinfo, line) in zip(rem[::2], rem[1::2]): fileinfo = fileinfo.split() src_filename = fileinfo[3] if src_filename not in files: # There is a race condition with the remind call above here. # This could be solved by parsing the remind -de output, # but I don't see an easy way to do that. files[src_filename] = open(src_filename).readlines() reminders[src_filename] = {} mtime = getmtime(src_filename) if mtime > self._mtime: self._mtime = mtime text = files[src_filename][int(fileinfo[2]) - 1] event = self._parse_remind_line(line, text) if event['uid'] in reminders[src_filename]: reminders[src_filename][event['uid']]['dtstart'] += event['dtstart'] reminders[src_filename][event['uid']]['line'] += line else: reminders[src_filename][event['uid']] = event reminders[src_filename][event['uid']]['line'] = line # Find included files without reminders and add them to the file list for source in files.values(): for line in source: if line.startswith('include'): new_file = line.split(' ')[1].strip() if new_file not in reminders: reminders[new_file] = {} mtime = getmtime(new_file) if mtime > self._mtime: self._mtime = mtime return reminders @staticmethod def _gen_description(text): """Convert from Remind MSG to iCal description Opposite of _gen_msg() """ return text[text.rfind('%"') + 3:].replace('%_', '\n').replace('["["]', '[').strip() def _parse_remind_line(self, line, text): """Parse a line of remind output into a dict line -- the remind output text -- the original remind input """ event = {} line = line.split(None, 6) dat = [int(f) for f in line[0].split('/')] if line[4] != '*': start = divmod(int(line[4]), 60) event['dtstart'] = [datetime(dat[0], dat[1], dat[2], start[0], start[1], tzinfo=self._localtz)] if line[3] != '*': event['duration'] = timedelta(minutes=int(line[3])) else: event['dtstart'] = [date(dat[0], dat[1], dat[2])] msg = ' '.join(line[5:]) if line[4] == '*' else line[6] msg = msg.strip().replace('%_', '\n').replace('["["]', '[') if ' at ' in msg: (event['msg'], event['location']) = msg.rsplit(' at ', 1) else: event['msg'] = msg if '%"' in text: event['description'] = Remind._gen_description(text) tags = line[2].split(',') classes = ['PUBLIC', 'PRIVATE', 'CONFIDENTIAL'] for tag in tags[:-1]: if tag in classes: event['class'] = tag event['categories'] = [tag for tag in tags[:-1] if tag not in classes] event['uid'] = '%s@%s' % (tags[-1][7:], getfqdn()) return event @staticmethod def _interval(dates): """Return the distance between all dates and 0 if they are different""" interval = (dates[1] - dates[0]).days last = dates[0] for dat in dates[1:]: if (dat - last).days != interval: return 0 last = dat return interval @staticmethod def _gen_dtend_rrule(dtstarts, vevent): """Generate an rdate or rrule from a list of dates and add it to the vevent""" interval = Remind._interval(dtstarts) if interval > 0 and interval % 7 == 0: rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.WEEKLY, interval=interval // 7, count=len(dtstarts))) vevent.rruleset = rset elif interval > 1: rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.DAILY, interval=interval, count=len(dtstarts))) vevent.rruleset = rset elif interval > 0: if isinstance(dtstarts[0], datetime): rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.DAILY, count=len(dtstarts))) vevent.rruleset = rset else: vevent.add('dtend').value = dtstarts[-1] + timedelta(days=1) else: rset = rrule.rruleset() if isinstance(dtstarts[0], datetime): for dat in dtstarts: rset.rdate(dat) else: for dat in dtstarts: rset.rdate(datetime(dat.year, dat.month, dat.day)) # temporary set dtstart to a different date, so it's not # removed from rset by python-vobject works around bug in # Android: # https://github.com/rfc2822/davdroid/issues/340 vevent.dtstart.value = dtstarts[0] - timedelta(days=1) vevent.rruleset = rset vevent.dtstart.value = dtstarts[0] if not isinstance(dtstarts[0], datetime): vevent.add('dtend').value = dtstarts[0] + timedelta(days=1) def _update(self): """Reload Remind files if the mtime is newer""" update = not self._reminders with self._lock: for fname in self._reminders: if getmtime(fname) > self._mtime: update = True break if update: self._reminders = self._parse_remind(self._filename) def get_filesnames(self): """All filenames parsed by remind (including included files)""" self._update() return list(self._reminders.keys()) @staticmethod def _get_uid(line): """UID of a remind line""" return '%s@%s' % (md5(line[:-1].encode('utf-8')).hexdigest(), getfqdn()) def get_uids(self, filename=None): """UIDs of all reminders in the file excluding included files If a filename is specified, only it's UIDs are return, otherwise all. filename -- the remind file """ self._update() if filename: if filename not in self._reminders: return [] return self._reminders[filename].keys() return [uid for uids in self._reminders.values() for uid in uids] def to_vobject_etag(self, filename, uid): """Return iCal object and etag of one Remind entry filename -- the remind file uid -- the UID of the Remind line """ return self.to_vobjects(filename, [uid])[0][1:3] def to_vobjects(self, filename, uids=None): """Return iCal objects and etags of all Remind entries in uids filename -- the remind file uids -- the UIDs of the Remind lines (all if None) """ self._update() if not uids: uids = self._reminders[filename] items = [] for uid in uids: cal = iCalendar() self._gen_vevent(self._reminders[filename][uid], cal.add('vevent')) etag = md5() etag.update(self._reminders[filename][uid]['line'].encode("utf-8")) items.append((uid, cal, '"%s"' % etag.hexdigest())) return items def to_vobject(self, filename=None, uid=None): """Return iCal object of Remind lines If filename and UID are specified, the vObject only contains that event. If only a filename is specified, the vObject contains all events in the file. Otherwise the vObject contains all all objects of all files associated with the Remind object. filename -- the remind file uid -- the UID of the Remind line """ self._update() cal = iCalendar() if uid: self._gen_vevent(self._reminders[filename][uid], cal.add('vevent')) elif filename: for event in self._reminders[filename].values(): self._gen_vevent(event, cal.add('vevent')) else: for filename in self._reminders: for event in self._reminders[filename].values(): self._gen_vevent(event, cal.add('vevent')) return cal def stdin_to_vobject(self, lines): """Return iCal object of the Remind commands in lines""" cal = iCalendar() for event in self._parse_remind('-', lines)['-'].values(): self._gen_vevent(event, cal.add('vevent')) return cal @staticmethod def _parse_rdate(rdates): """Convert from iCal rdate to Remind trigdate syntax""" trigdates = [rdate.strftime("trigdate()=='%Y-%m-%d'") for rdate in rdates] return 'SATISFY [%s]' % '||'.join(trigdates) @staticmethod def _parse_rruleset(rruleset): """Convert from iCal rrule to Remind recurrence syntax""" # pylint: disable=protected-access if rruleset._rrule[0]._freq == 0: return [] rep = [] if rruleset._rrule[0]._byweekday and len(rruleset._rrule[0]._byweekday) > 1: rep.append('*1') elif rruleset._rrule[0]._freq == rrule.DAILY: rep.append('*%d' % rruleset._rrule[0]._interval) elif rruleset._rrule[0]._freq == rrule.WEEKLY: rep.append('*%d' % (7 * rruleset._rrule[0]._interval)) else: return Remind._parse_rdate(rruleset._rrule[0]) if rruleset._rrule[0]._byweekday and len(rruleset._rrule[0]._byweekday) > 1: daynums = set(range(7)) - set(rruleset._rrule[0]._byweekday) weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] days = [weekdays[day] for day in daynums] rep.append('SKIP OMIT %s' % ' '.join(days)) if rruleset._rrule[0]._until: rep.append(rruleset._rrule[0]._until.strftime('UNTIL %b %d %Y').replace(' 0', ' ')) elif rruleset._rrule[0]._count: rep.append(rruleset[-1].strftime('UNTIL %b %d %Y').replace(' 0', ' ')) return rep @staticmethod def _event_duration(vevent): """unify dtend and duration to the duration of the given vevent""" if hasattr(vevent, 'dtend'): return vevent.dtend.value - vevent.dtstart.value elif hasattr(vevent, 'duration') and vevent.duration.value: return vevent.duration.value return timedelta(0) @staticmethod def _gen_msg(vevent, label, tail, sep): """Generate a Remind MSG from the given vevent. Opposite of _gen_description() """ rem = ['MSG'] msg = [] if label: msg.append(label) if hasattr(vevent, 'summary') and vevent.summary.value: msg.append(Remind._rem_clean(vevent.summary.value)) else: msg.append('empty reminder') if hasattr(vevent, 'location') and vevent.location.value: msg.append('at %s' % Remind._rem_clean(vevent.location.value)) has_desc = hasattr(vevent, 'description') and vevent.description.value if tail or has_desc: rem.append('%%"%s%%"' % ' '.join(msg)) else: rem.append(' '.join(msg)) if tail: rem.append(tail) if has_desc: rem[-1] += sep + Remind._rem_clean(vevent.description.value) return ' '.join(rem) @staticmethod def _rem_clean(rem): """Strip, transform newlines, and escape '[' in string so it's acceptable as a remind entry.""" return rem.strip().replace('\n', '%_').replace('[', '["["]') @staticmethod def _abbr_tag(tag): """Transform a string so it's acceptable as a remind tag. """ return tag.replace(" ", "")[:48] def to_remind(self, vevent, label=None, priority=None, tags=None, tail=None, sep=" ", postdate=None, posttime=None): """Generate a Remind command from the given vevent""" remind = ['REM'] trigdates = None if hasattr(vevent, 'rrule'): trigdates = Remind._parse_rruleset(vevent.rruleset) dtstart = vevent.dtstart.value # If we don't get timezone information, handle it as a naive datetime. # See https://github.com/jspricke/python-remind/issues/2 for reference. if isinstance(dtstart, datetime) and dtstart.tzinfo: dtstart = dtstart.astimezone(self._localtz) dtend = None if hasattr(vevent, 'dtend'): dtend = vevent.dtend.value if isinstance(dtend, datetime) and dtend.tzinfo: dtend = dtend.astimezone(self._localtz) if not hasattr(vevent, 'rdate') and not isinstance(trigdates, str): remind.append(dtstart.strftime('%b %d %Y').replace(' 0', ' ')) if postdate: remind.append(postdate) if priority: remind.append('PRIORITY %s' % priority) if isinstance(trigdates, list): remind.extend(trigdates) duration = Remind._event_duration(vevent) if type(dtstart) is date and duration.days > 1: remind.append('*1') if dtend is not None: dtend -= timedelta(days=1) remind.append(dtend.strftime('UNTIL %b %d %Y').replace(' 0', ' ')) if isinstance(dtstart, datetime): remind.append(dtstart.strftime('AT %H:%M').replace(' 0', ' ')) if posttime: remind.append(posttime) if duration.total_seconds() > 0: remind.append('DURATION %d:%02d' % divmod(duration.total_seconds() / 60, 60)) if hasattr(vevent, 'rdate'): remind.append(Remind._parse_rdate(vevent.rdate.value)) elif isinstance(trigdates, str): remind.append(trigdates) if hasattr(vevent, 'class'): remind.append('TAG %s' % Remind._abbr_tag(vevent.getChildValue('class'))) if tags: remind.extend(['TAG %s' % Remind._abbr_tag(tag) for tag in tags]) if hasattr(vevent, 'categories_list'): for categories in vevent.categories_list: for category in categories.value: remind.append('TAG %s' % Remind._abbr_tag(category)) remind.append(Remind._gen_msg(vevent, label, tail, sep)) return ' '.join(remind) + '\n' def to_reminders(self, ical, label=None, priority=None, tags=None, tail=None, sep=" ", postdate=None, posttime=None): """Return Remind commands for all events of a iCalendar""" if not hasattr(ical, 'vevent_list'): return '' reminders = [self.to_remind(vevent, label, priority, tags, tail, sep, postdate, posttime) for vevent in ical.vevent_list] return ''.join(reminders) def append(self, ical, filename=None): """Append a Remind command generated from the iCalendar to the file""" return self.append_vobject(readOne(ical), filename) def append_vobject(self, ical, filename=None): """Append a Remind command generated from the iCalendar to the file""" if not filename: filename = self._filename elif filename not in self._reminders: return with self._lock: outdat = self.to_reminders(ical) open(filename, 'a').write(outdat) return Remind._get_uid(outdat) def remove(self, uid, filename=None): """Remove the Remind command with the uid from the file""" if not filename: filename = self._filename elif filename not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(filename).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): del rem[index] open(filename, 'w').writelines(rem) break def replace(self, uid, ical, filename=None): """Update the Remind command with the uid in the file with the new iCalendar""" return self.replace_vobject(uid, readOne(ical), filename) def replace_vobject(self, uid, ical, filename=None): """Update the Remind command with the uid in the file with the new iCalendar""" if not filename: filename = self._filename elif filename not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(filename).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): rem[index] = self.to_reminders(ical) new_uid = self._get_uid(rem[index]) open(filename, 'w').writelines(rem) return new_uid def move_vobject(self, uid, from_file, to_file): """Move the Remind command with the uid from from_file to to_file""" if from_file not in self._reminders or to_file not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(from_file).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): del rem[index] open(from_file, 'w').writelines(rem) open(to_file, 'a').write(line) break def get_meta(self): """Meta tags of the vObject collection""" return {'tag': 'VCALENDAR', 'C:supported-calendar-component-set': 'VEVENT'} def last_modified(self): """Last time the Remind files where parsed""" self._update() return self._mtime
jspricke/python-remind
remind.py
Remind._update
python
def _update(self): update = not self._reminders with self._lock: for fname in self._reminders: if getmtime(fname) > self._mtime: update = True break if update: self._reminders = self._parse_remind(self._filename)
Reload Remind files if the mtime is newer
train
https://github.com/jspricke/python-remind/blob/dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1/remind.py#L245-L256
[ "def _parse_remind(self, filename, lines=''):\n \"\"\"Calls remind and parses the output into a dict\n\n filename -- the remind file (included files will be used as well)\n lines -- used as stdin to remind (filename will be set to -)\n \"\"\"\n files = {}\n reminders = {}\n if lines:\n f...
class Remind(object): """Represents a collection of Remind files""" def __init__(self, filename=expanduser('~/.reminders'), localtz=None, startdate=date.today() - timedelta(weeks=12), month=15, alarm=timedelta(minutes=-10)): """Constructor filename -- the remind file (included files will be used as well) localtz -- the timezone of the remind file startdate -- the date to start parsing, will be passed to remind month -- how many month to parse, will be passed to remind -s """ self._localtz = localtz if localtz else get_localzone() self._filename = filename self._startdate = startdate self._month = month self._lock = Lock() self._reminders = {} self._mtime = 0 self._alarm = alarm self._update() def _parse_remind(self, filename, lines=''): """Calls remind and parses the output into a dict filename -- the remind file (included files will be used as well) lines -- used as stdin to remind (filename will be set to -) """ files = {} reminders = {} if lines: filename = '-' files[filename] = lines reminders[filename] = {} cmd = ['remind', '-l', '-s%d' % self._month, '-b1', '-y', '-r', filename, str(self._startdate)] try: rem = Popen(cmd, stdin=PIPE, stdout=PIPE).communicate(input=lines.encode('utf-8'))[0].decode('utf-8') except OSError: raise OSError('Error running: %s' % ' '.join(cmd)) rem = rem.splitlines() for (fileinfo, line) in zip(rem[::2], rem[1::2]): fileinfo = fileinfo.split() src_filename = fileinfo[3] if src_filename not in files: # There is a race condition with the remind call above here. # This could be solved by parsing the remind -de output, # but I don't see an easy way to do that. files[src_filename] = open(src_filename).readlines() reminders[src_filename] = {} mtime = getmtime(src_filename) if mtime > self._mtime: self._mtime = mtime text = files[src_filename][int(fileinfo[2]) - 1] event = self._parse_remind_line(line, text) if event['uid'] in reminders[src_filename]: reminders[src_filename][event['uid']]['dtstart'] += event['dtstart'] reminders[src_filename][event['uid']]['line'] += line else: reminders[src_filename][event['uid']] = event reminders[src_filename][event['uid']]['line'] = line # Find included files without reminders and add them to the file list for source in files.values(): for line in source: if line.startswith('include'): new_file = line.split(' ')[1].strip() if new_file not in reminders: reminders[new_file] = {} mtime = getmtime(new_file) if mtime > self._mtime: self._mtime = mtime return reminders @staticmethod def _gen_description(text): """Convert from Remind MSG to iCal description Opposite of _gen_msg() """ return text[text.rfind('%"') + 3:].replace('%_', '\n').replace('["["]', '[').strip() def _parse_remind_line(self, line, text): """Parse a line of remind output into a dict line -- the remind output text -- the original remind input """ event = {} line = line.split(None, 6) dat = [int(f) for f in line[0].split('/')] if line[4] != '*': start = divmod(int(line[4]), 60) event['dtstart'] = [datetime(dat[0], dat[1], dat[2], start[0], start[1], tzinfo=self._localtz)] if line[3] != '*': event['duration'] = timedelta(minutes=int(line[3])) else: event['dtstart'] = [date(dat[0], dat[1], dat[2])] msg = ' '.join(line[5:]) if line[4] == '*' else line[6] msg = msg.strip().replace('%_', '\n').replace('["["]', '[') if ' at ' in msg: (event['msg'], event['location']) = msg.rsplit(' at ', 1) else: event['msg'] = msg if '%"' in text: event['description'] = Remind._gen_description(text) tags = line[2].split(',') classes = ['PUBLIC', 'PRIVATE', 'CONFIDENTIAL'] for tag in tags[:-1]: if tag in classes: event['class'] = tag event['categories'] = [tag for tag in tags[:-1] if tag not in classes] event['uid'] = '%s@%s' % (tags[-1][7:], getfqdn()) return event @staticmethod def _interval(dates): """Return the distance between all dates and 0 if they are different""" interval = (dates[1] - dates[0]).days last = dates[0] for dat in dates[1:]: if (dat - last).days != interval: return 0 last = dat return interval @staticmethod def _gen_dtend_rrule(dtstarts, vevent): """Generate an rdate or rrule from a list of dates and add it to the vevent""" interval = Remind._interval(dtstarts) if interval > 0 and interval % 7 == 0: rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.WEEKLY, interval=interval // 7, count=len(dtstarts))) vevent.rruleset = rset elif interval > 1: rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.DAILY, interval=interval, count=len(dtstarts))) vevent.rruleset = rset elif interval > 0: if isinstance(dtstarts[0], datetime): rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.DAILY, count=len(dtstarts))) vevent.rruleset = rset else: vevent.add('dtend').value = dtstarts[-1] + timedelta(days=1) else: rset = rrule.rruleset() if isinstance(dtstarts[0], datetime): for dat in dtstarts: rset.rdate(dat) else: for dat in dtstarts: rset.rdate(datetime(dat.year, dat.month, dat.day)) # temporary set dtstart to a different date, so it's not # removed from rset by python-vobject works around bug in # Android: # https://github.com/rfc2822/davdroid/issues/340 vevent.dtstart.value = dtstarts[0] - timedelta(days=1) vevent.rruleset = rset vevent.dtstart.value = dtstarts[0] if not isinstance(dtstarts[0], datetime): vevent.add('dtend').value = dtstarts[0] + timedelta(days=1) def _gen_vevent(self, event, vevent): """Generate vevent from given event""" vevent.add('dtstart').value = event['dtstart'][0] vevent.add('dtstamp').value = datetime.fromtimestamp(self._mtime) vevent.add('summary').value = event['msg'] vevent.add('uid').value = event['uid'] if 'class' in event: vevent.add('class').value = event['class'] if 'categories' in event and len(event['categories']) > 0: vevent.add('categories').value = event['categories'] if 'location' in event: vevent.add('location').value = event['location'] if 'description' in event: vevent.add('description').value = event['description'] if isinstance(event['dtstart'][0], datetime): if self._alarm != timedelta(): valarm = vevent.add('valarm') valarm.add('trigger').value = self._alarm valarm.add('action').value = 'DISPLAY' valarm.add('description').value = event['msg'] if 'duration' in event: vevent.add('duration').value = event['duration'] else: vevent.add('dtend').value = event['dtstart'][0] elif len(event['dtstart']) == 1: vevent.add('dtend').value = event['dtstart'][0] + timedelta(days=1) if len(event['dtstart']) > 1: Remind._gen_dtend_rrule(event['dtstart'], vevent) def get_filesnames(self): """All filenames parsed by remind (including included files)""" self._update() return list(self._reminders.keys()) @staticmethod def _get_uid(line): """UID of a remind line""" return '%s@%s' % (md5(line[:-1].encode('utf-8')).hexdigest(), getfqdn()) def get_uids(self, filename=None): """UIDs of all reminders in the file excluding included files If a filename is specified, only it's UIDs are return, otherwise all. filename -- the remind file """ self._update() if filename: if filename not in self._reminders: return [] return self._reminders[filename].keys() return [uid for uids in self._reminders.values() for uid in uids] def to_vobject_etag(self, filename, uid): """Return iCal object and etag of one Remind entry filename -- the remind file uid -- the UID of the Remind line """ return self.to_vobjects(filename, [uid])[0][1:3] def to_vobjects(self, filename, uids=None): """Return iCal objects and etags of all Remind entries in uids filename -- the remind file uids -- the UIDs of the Remind lines (all if None) """ self._update() if not uids: uids = self._reminders[filename] items = [] for uid in uids: cal = iCalendar() self._gen_vevent(self._reminders[filename][uid], cal.add('vevent')) etag = md5() etag.update(self._reminders[filename][uid]['line'].encode("utf-8")) items.append((uid, cal, '"%s"' % etag.hexdigest())) return items def to_vobject(self, filename=None, uid=None): """Return iCal object of Remind lines If filename and UID are specified, the vObject only contains that event. If only a filename is specified, the vObject contains all events in the file. Otherwise the vObject contains all all objects of all files associated with the Remind object. filename -- the remind file uid -- the UID of the Remind line """ self._update() cal = iCalendar() if uid: self._gen_vevent(self._reminders[filename][uid], cal.add('vevent')) elif filename: for event in self._reminders[filename].values(): self._gen_vevent(event, cal.add('vevent')) else: for filename in self._reminders: for event in self._reminders[filename].values(): self._gen_vevent(event, cal.add('vevent')) return cal def stdin_to_vobject(self, lines): """Return iCal object of the Remind commands in lines""" cal = iCalendar() for event in self._parse_remind('-', lines)['-'].values(): self._gen_vevent(event, cal.add('vevent')) return cal @staticmethod def _parse_rdate(rdates): """Convert from iCal rdate to Remind trigdate syntax""" trigdates = [rdate.strftime("trigdate()=='%Y-%m-%d'") for rdate in rdates] return 'SATISFY [%s]' % '||'.join(trigdates) @staticmethod def _parse_rruleset(rruleset): """Convert from iCal rrule to Remind recurrence syntax""" # pylint: disable=protected-access if rruleset._rrule[0]._freq == 0: return [] rep = [] if rruleset._rrule[0]._byweekday and len(rruleset._rrule[0]._byweekday) > 1: rep.append('*1') elif rruleset._rrule[0]._freq == rrule.DAILY: rep.append('*%d' % rruleset._rrule[0]._interval) elif rruleset._rrule[0]._freq == rrule.WEEKLY: rep.append('*%d' % (7 * rruleset._rrule[0]._interval)) else: return Remind._parse_rdate(rruleset._rrule[0]) if rruleset._rrule[0]._byweekday and len(rruleset._rrule[0]._byweekday) > 1: daynums = set(range(7)) - set(rruleset._rrule[0]._byweekday) weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] days = [weekdays[day] for day in daynums] rep.append('SKIP OMIT %s' % ' '.join(days)) if rruleset._rrule[0]._until: rep.append(rruleset._rrule[0]._until.strftime('UNTIL %b %d %Y').replace(' 0', ' ')) elif rruleset._rrule[0]._count: rep.append(rruleset[-1].strftime('UNTIL %b %d %Y').replace(' 0', ' ')) return rep @staticmethod def _event_duration(vevent): """unify dtend and duration to the duration of the given vevent""" if hasattr(vevent, 'dtend'): return vevent.dtend.value - vevent.dtstart.value elif hasattr(vevent, 'duration') and vevent.duration.value: return vevent.duration.value return timedelta(0) @staticmethod def _gen_msg(vevent, label, tail, sep): """Generate a Remind MSG from the given vevent. Opposite of _gen_description() """ rem = ['MSG'] msg = [] if label: msg.append(label) if hasattr(vevent, 'summary') and vevent.summary.value: msg.append(Remind._rem_clean(vevent.summary.value)) else: msg.append('empty reminder') if hasattr(vevent, 'location') and vevent.location.value: msg.append('at %s' % Remind._rem_clean(vevent.location.value)) has_desc = hasattr(vevent, 'description') and vevent.description.value if tail or has_desc: rem.append('%%"%s%%"' % ' '.join(msg)) else: rem.append(' '.join(msg)) if tail: rem.append(tail) if has_desc: rem[-1] += sep + Remind._rem_clean(vevent.description.value) return ' '.join(rem) @staticmethod def _rem_clean(rem): """Strip, transform newlines, and escape '[' in string so it's acceptable as a remind entry.""" return rem.strip().replace('\n', '%_').replace('[', '["["]') @staticmethod def _abbr_tag(tag): """Transform a string so it's acceptable as a remind tag. """ return tag.replace(" ", "")[:48] def to_remind(self, vevent, label=None, priority=None, tags=None, tail=None, sep=" ", postdate=None, posttime=None): """Generate a Remind command from the given vevent""" remind = ['REM'] trigdates = None if hasattr(vevent, 'rrule'): trigdates = Remind._parse_rruleset(vevent.rruleset) dtstart = vevent.dtstart.value # If we don't get timezone information, handle it as a naive datetime. # See https://github.com/jspricke/python-remind/issues/2 for reference. if isinstance(dtstart, datetime) and dtstart.tzinfo: dtstart = dtstart.astimezone(self._localtz) dtend = None if hasattr(vevent, 'dtend'): dtend = vevent.dtend.value if isinstance(dtend, datetime) and dtend.tzinfo: dtend = dtend.astimezone(self._localtz) if not hasattr(vevent, 'rdate') and not isinstance(trigdates, str): remind.append(dtstart.strftime('%b %d %Y').replace(' 0', ' ')) if postdate: remind.append(postdate) if priority: remind.append('PRIORITY %s' % priority) if isinstance(trigdates, list): remind.extend(trigdates) duration = Remind._event_duration(vevent) if type(dtstart) is date and duration.days > 1: remind.append('*1') if dtend is not None: dtend -= timedelta(days=1) remind.append(dtend.strftime('UNTIL %b %d %Y').replace(' 0', ' ')) if isinstance(dtstart, datetime): remind.append(dtstart.strftime('AT %H:%M').replace(' 0', ' ')) if posttime: remind.append(posttime) if duration.total_seconds() > 0: remind.append('DURATION %d:%02d' % divmod(duration.total_seconds() / 60, 60)) if hasattr(vevent, 'rdate'): remind.append(Remind._parse_rdate(vevent.rdate.value)) elif isinstance(trigdates, str): remind.append(trigdates) if hasattr(vevent, 'class'): remind.append('TAG %s' % Remind._abbr_tag(vevent.getChildValue('class'))) if tags: remind.extend(['TAG %s' % Remind._abbr_tag(tag) for tag in tags]) if hasattr(vevent, 'categories_list'): for categories in vevent.categories_list: for category in categories.value: remind.append('TAG %s' % Remind._abbr_tag(category)) remind.append(Remind._gen_msg(vevent, label, tail, sep)) return ' '.join(remind) + '\n' def to_reminders(self, ical, label=None, priority=None, tags=None, tail=None, sep=" ", postdate=None, posttime=None): """Return Remind commands for all events of a iCalendar""" if not hasattr(ical, 'vevent_list'): return '' reminders = [self.to_remind(vevent, label, priority, tags, tail, sep, postdate, posttime) for vevent in ical.vevent_list] return ''.join(reminders) def append(self, ical, filename=None): """Append a Remind command generated from the iCalendar to the file""" return self.append_vobject(readOne(ical), filename) def append_vobject(self, ical, filename=None): """Append a Remind command generated from the iCalendar to the file""" if not filename: filename = self._filename elif filename not in self._reminders: return with self._lock: outdat = self.to_reminders(ical) open(filename, 'a').write(outdat) return Remind._get_uid(outdat) def remove(self, uid, filename=None): """Remove the Remind command with the uid from the file""" if not filename: filename = self._filename elif filename not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(filename).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): del rem[index] open(filename, 'w').writelines(rem) break def replace(self, uid, ical, filename=None): """Update the Remind command with the uid in the file with the new iCalendar""" return self.replace_vobject(uid, readOne(ical), filename) def replace_vobject(self, uid, ical, filename=None): """Update the Remind command with the uid in the file with the new iCalendar""" if not filename: filename = self._filename elif filename not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(filename).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): rem[index] = self.to_reminders(ical) new_uid = self._get_uid(rem[index]) open(filename, 'w').writelines(rem) return new_uid def move_vobject(self, uid, from_file, to_file): """Move the Remind command with the uid from from_file to to_file""" if from_file not in self._reminders or to_file not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(from_file).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): del rem[index] open(from_file, 'w').writelines(rem) open(to_file, 'a').write(line) break def get_meta(self): """Meta tags of the vObject collection""" return {'tag': 'VCALENDAR', 'C:supported-calendar-component-set': 'VEVENT'} def last_modified(self): """Last time the Remind files where parsed""" self._update() return self._mtime
jspricke/python-remind
remind.py
Remind.get_uids
python
def get_uids(self, filename=None): self._update() if filename: if filename not in self._reminders: return [] return self._reminders[filename].keys() return [uid for uids in self._reminders.values() for uid in uids]
UIDs of all reminders in the file excluding included files If a filename is specified, only it's UIDs are return, otherwise all. filename -- the remind file
train
https://github.com/jspricke/python-remind/blob/dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1/remind.py#L268-L280
[ "def _update(self):\n \"\"\"Reload Remind files if the mtime is newer\"\"\"\n update = not self._reminders\n\n with self._lock:\n for fname in self._reminders:\n if getmtime(fname) > self._mtime:\n update = True\n break\n\n if update:\n self...
class Remind(object): """Represents a collection of Remind files""" def __init__(self, filename=expanduser('~/.reminders'), localtz=None, startdate=date.today() - timedelta(weeks=12), month=15, alarm=timedelta(minutes=-10)): """Constructor filename -- the remind file (included files will be used as well) localtz -- the timezone of the remind file startdate -- the date to start parsing, will be passed to remind month -- how many month to parse, will be passed to remind -s """ self._localtz = localtz if localtz else get_localzone() self._filename = filename self._startdate = startdate self._month = month self._lock = Lock() self._reminders = {} self._mtime = 0 self._alarm = alarm self._update() def _parse_remind(self, filename, lines=''): """Calls remind and parses the output into a dict filename -- the remind file (included files will be used as well) lines -- used as stdin to remind (filename will be set to -) """ files = {} reminders = {} if lines: filename = '-' files[filename] = lines reminders[filename] = {} cmd = ['remind', '-l', '-s%d' % self._month, '-b1', '-y', '-r', filename, str(self._startdate)] try: rem = Popen(cmd, stdin=PIPE, stdout=PIPE).communicate(input=lines.encode('utf-8'))[0].decode('utf-8') except OSError: raise OSError('Error running: %s' % ' '.join(cmd)) rem = rem.splitlines() for (fileinfo, line) in zip(rem[::2], rem[1::2]): fileinfo = fileinfo.split() src_filename = fileinfo[3] if src_filename not in files: # There is a race condition with the remind call above here. # This could be solved by parsing the remind -de output, # but I don't see an easy way to do that. files[src_filename] = open(src_filename).readlines() reminders[src_filename] = {} mtime = getmtime(src_filename) if mtime > self._mtime: self._mtime = mtime text = files[src_filename][int(fileinfo[2]) - 1] event = self._parse_remind_line(line, text) if event['uid'] in reminders[src_filename]: reminders[src_filename][event['uid']]['dtstart'] += event['dtstart'] reminders[src_filename][event['uid']]['line'] += line else: reminders[src_filename][event['uid']] = event reminders[src_filename][event['uid']]['line'] = line # Find included files without reminders and add them to the file list for source in files.values(): for line in source: if line.startswith('include'): new_file = line.split(' ')[1].strip() if new_file not in reminders: reminders[new_file] = {} mtime = getmtime(new_file) if mtime > self._mtime: self._mtime = mtime return reminders @staticmethod def _gen_description(text): """Convert from Remind MSG to iCal description Opposite of _gen_msg() """ return text[text.rfind('%"') + 3:].replace('%_', '\n').replace('["["]', '[').strip() def _parse_remind_line(self, line, text): """Parse a line of remind output into a dict line -- the remind output text -- the original remind input """ event = {} line = line.split(None, 6) dat = [int(f) for f in line[0].split('/')] if line[4] != '*': start = divmod(int(line[4]), 60) event['dtstart'] = [datetime(dat[0], dat[1], dat[2], start[0], start[1], tzinfo=self._localtz)] if line[3] != '*': event['duration'] = timedelta(minutes=int(line[3])) else: event['dtstart'] = [date(dat[0], dat[1], dat[2])] msg = ' '.join(line[5:]) if line[4] == '*' else line[6] msg = msg.strip().replace('%_', '\n').replace('["["]', '[') if ' at ' in msg: (event['msg'], event['location']) = msg.rsplit(' at ', 1) else: event['msg'] = msg if '%"' in text: event['description'] = Remind._gen_description(text) tags = line[2].split(',') classes = ['PUBLIC', 'PRIVATE', 'CONFIDENTIAL'] for tag in tags[:-1]: if tag in classes: event['class'] = tag event['categories'] = [tag for tag in tags[:-1] if tag not in classes] event['uid'] = '%s@%s' % (tags[-1][7:], getfqdn()) return event @staticmethod def _interval(dates): """Return the distance between all dates and 0 if they are different""" interval = (dates[1] - dates[0]).days last = dates[0] for dat in dates[1:]: if (dat - last).days != interval: return 0 last = dat return interval @staticmethod def _gen_dtend_rrule(dtstarts, vevent): """Generate an rdate or rrule from a list of dates and add it to the vevent""" interval = Remind._interval(dtstarts) if interval > 0 and interval % 7 == 0: rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.WEEKLY, interval=interval // 7, count=len(dtstarts))) vevent.rruleset = rset elif interval > 1: rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.DAILY, interval=interval, count=len(dtstarts))) vevent.rruleset = rset elif interval > 0: if isinstance(dtstarts[0], datetime): rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.DAILY, count=len(dtstarts))) vevent.rruleset = rset else: vevent.add('dtend').value = dtstarts[-1] + timedelta(days=1) else: rset = rrule.rruleset() if isinstance(dtstarts[0], datetime): for dat in dtstarts: rset.rdate(dat) else: for dat in dtstarts: rset.rdate(datetime(dat.year, dat.month, dat.day)) # temporary set dtstart to a different date, so it's not # removed from rset by python-vobject works around bug in # Android: # https://github.com/rfc2822/davdroid/issues/340 vevent.dtstart.value = dtstarts[0] - timedelta(days=1) vevent.rruleset = rset vevent.dtstart.value = dtstarts[0] if not isinstance(dtstarts[0], datetime): vevent.add('dtend').value = dtstarts[0] + timedelta(days=1) def _gen_vevent(self, event, vevent): """Generate vevent from given event""" vevent.add('dtstart').value = event['dtstart'][0] vevent.add('dtstamp').value = datetime.fromtimestamp(self._mtime) vevent.add('summary').value = event['msg'] vevent.add('uid').value = event['uid'] if 'class' in event: vevent.add('class').value = event['class'] if 'categories' in event and len(event['categories']) > 0: vevent.add('categories').value = event['categories'] if 'location' in event: vevent.add('location').value = event['location'] if 'description' in event: vevent.add('description').value = event['description'] if isinstance(event['dtstart'][0], datetime): if self._alarm != timedelta(): valarm = vevent.add('valarm') valarm.add('trigger').value = self._alarm valarm.add('action').value = 'DISPLAY' valarm.add('description').value = event['msg'] if 'duration' in event: vevent.add('duration').value = event['duration'] else: vevent.add('dtend').value = event['dtstart'][0] elif len(event['dtstart']) == 1: vevent.add('dtend').value = event['dtstart'][0] + timedelta(days=1) if len(event['dtstart']) > 1: Remind._gen_dtend_rrule(event['dtstart'], vevent) def _update(self): """Reload Remind files if the mtime is newer""" update = not self._reminders with self._lock: for fname in self._reminders: if getmtime(fname) > self._mtime: update = True break if update: self._reminders = self._parse_remind(self._filename) def get_filesnames(self): """All filenames parsed by remind (including included files)""" self._update() return list(self._reminders.keys()) @staticmethod def _get_uid(line): """UID of a remind line""" return '%s@%s' % (md5(line[:-1].encode('utf-8')).hexdigest(), getfqdn()) def to_vobject_etag(self, filename, uid): """Return iCal object and etag of one Remind entry filename -- the remind file uid -- the UID of the Remind line """ return self.to_vobjects(filename, [uid])[0][1:3] def to_vobjects(self, filename, uids=None): """Return iCal objects and etags of all Remind entries in uids filename -- the remind file uids -- the UIDs of the Remind lines (all if None) """ self._update() if not uids: uids = self._reminders[filename] items = [] for uid in uids: cal = iCalendar() self._gen_vevent(self._reminders[filename][uid], cal.add('vevent')) etag = md5() etag.update(self._reminders[filename][uid]['line'].encode("utf-8")) items.append((uid, cal, '"%s"' % etag.hexdigest())) return items def to_vobject(self, filename=None, uid=None): """Return iCal object of Remind lines If filename and UID are specified, the vObject only contains that event. If only a filename is specified, the vObject contains all events in the file. Otherwise the vObject contains all all objects of all files associated with the Remind object. filename -- the remind file uid -- the UID of the Remind line """ self._update() cal = iCalendar() if uid: self._gen_vevent(self._reminders[filename][uid], cal.add('vevent')) elif filename: for event in self._reminders[filename].values(): self._gen_vevent(event, cal.add('vevent')) else: for filename in self._reminders: for event in self._reminders[filename].values(): self._gen_vevent(event, cal.add('vevent')) return cal def stdin_to_vobject(self, lines): """Return iCal object of the Remind commands in lines""" cal = iCalendar() for event in self._parse_remind('-', lines)['-'].values(): self._gen_vevent(event, cal.add('vevent')) return cal @staticmethod def _parse_rdate(rdates): """Convert from iCal rdate to Remind trigdate syntax""" trigdates = [rdate.strftime("trigdate()=='%Y-%m-%d'") for rdate in rdates] return 'SATISFY [%s]' % '||'.join(trigdates) @staticmethod def _parse_rruleset(rruleset): """Convert from iCal rrule to Remind recurrence syntax""" # pylint: disable=protected-access if rruleset._rrule[0]._freq == 0: return [] rep = [] if rruleset._rrule[0]._byweekday and len(rruleset._rrule[0]._byweekday) > 1: rep.append('*1') elif rruleset._rrule[0]._freq == rrule.DAILY: rep.append('*%d' % rruleset._rrule[0]._interval) elif rruleset._rrule[0]._freq == rrule.WEEKLY: rep.append('*%d' % (7 * rruleset._rrule[0]._interval)) else: return Remind._parse_rdate(rruleset._rrule[0]) if rruleset._rrule[0]._byweekday and len(rruleset._rrule[0]._byweekday) > 1: daynums = set(range(7)) - set(rruleset._rrule[0]._byweekday) weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] days = [weekdays[day] for day in daynums] rep.append('SKIP OMIT %s' % ' '.join(days)) if rruleset._rrule[0]._until: rep.append(rruleset._rrule[0]._until.strftime('UNTIL %b %d %Y').replace(' 0', ' ')) elif rruleset._rrule[0]._count: rep.append(rruleset[-1].strftime('UNTIL %b %d %Y').replace(' 0', ' ')) return rep @staticmethod def _event_duration(vevent): """unify dtend and duration to the duration of the given vevent""" if hasattr(vevent, 'dtend'): return vevent.dtend.value - vevent.dtstart.value elif hasattr(vevent, 'duration') and vevent.duration.value: return vevent.duration.value return timedelta(0) @staticmethod def _gen_msg(vevent, label, tail, sep): """Generate a Remind MSG from the given vevent. Opposite of _gen_description() """ rem = ['MSG'] msg = [] if label: msg.append(label) if hasattr(vevent, 'summary') and vevent.summary.value: msg.append(Remind._rem_clean(vevent.summary.value)) else: msg.append('empty reminder') if hasattr(vevent, 'location') and vevent.location.value: msg.append('at %s' % Remind._rem_clean(vevent.location.value)) has_desc = hasattr(vevent, 'description') and vevent.description.value if tail or has_desc: rem.append('%%"%s%%"' % ' '.join(msg)) else: rem.append(' '.join(msg)) if tail: rem.append(tail) if has_desc: rem[-1] += sep + Remind._rem_clean(vevent.description.value) return ' '.join(rem) @staticmethod def _rem_clean(rem): """Strip, transform newlines, and escape '[' in string so it's acceptable as a remind entry.""" return rem.strip().replace('\n', '%_').replace('[', '["["]') @staticmethod def _abbr_tag(tag): """Transform a string so it's acceptable as a remind tag. """ return tag.replace(" ", "")[:48] def to_remind(self, vevent, label=None, priority=None, tags=None, tail=None, sep=" ", postdate=None, posttime=None): """Generate a Remind command from the given vevent""" remind = ['REM'] trigdates = None if hasattr(vevent, 'rrule'): trigdates = Remind._parse_rruleset(vevent.rruleset) dtstart = vevent.dtstart.value # If we don't get timezone information, handle it as a naive datetime. # See https://github.com/jspricke/python-remind/issues/2 for reference. if isinstance(dtstart, datetime) and dtstart.tzinfo: dtstart = dtstart.astimezone(self._localtz) dtend = None if hasattr(vevent, 'dtend'): dtend = vevent.dtend.value if isinstance(dtend, datetime) and dtend.tzinfo: dtend = dtend.astimezone(self._localtz) if not hasattr(vevent, 'rdate') and not isinstance(trigdates, str): remind.append(dtstart.strftime('%b %d %Y').replace(' 0', ' ')) if postdate: remind.append(postdate) if priority: remind.append('PRIORITY %s' % priority) if isinstance(trigdates, list): remind.extend(trigdates) duration = Remind._event_duration(vevent) if type(dtstart) is date and duration.days > 1: remind.append('*1') if dtend is not None: dtend -= timedelta(days=1) remind.append(dtend.strftime('UNTIL %b %d %Y').replace(' 0', ' ')) if isinstance(dtstart, datetime): remind.append(dtstart.strftime('AT %H:%M').replace(' 0', ' ')) if posttime: remind.append(posttime) if duration.total_seconds() > 0: remind.append('DURATION %d:%02d' % divmod(duration.total_seconds() / 60, 60)) if hasattr(vevent, 'rdate'): remind.append(Remind._parse_rdate(vevent.rdate.value)) elif isinstance(trigdates, str): remind.append(trigdates) if hasattr(vevent, 'class'): remind.append('TAG %s' % Remind._abbr_tag(vevent.getChildValue('class'))) if tags: remind.extend(['TAG %s' % Remind._abbr_tag(tag) for tag in tags]) if hasattr(vevent, 'categories_list'): for categories in vevent.categories_list: for category in categories.value: remind.append('TAG %s' % Remind._abbr_tag(category)) remind.append(Remind._gen_msg(vevent, label, tail, sep)) return ' '.join(remind) + '\n' def to_reminders(self, ical, label=None, priority=None, tags=None, tail=None, sep=" ", postdate=None, posttime=None): """Return Remind commands for all events of a iCalendar""" if not hasattr(ical, 'vevent_list'): return '' reminders = [self.to_remind(vevent, label, priority, tags, tail, sep, postdate, posttime) for vevent in ical.vevent_list] return ''.join(reminders) def append(self, ical, filename=None): """Append a Remind command generated from the iCalendar to the file""" return self.append_vobject(readOne(ical), filename) def append_vobject(self, ical, filename=None): """Append a Remind command generated from the iCalendar to the file""" if not filename: filename = self._filename elif filename not in self._reminders: return with self._lock: outdat = self.to_reminders(ical) open(filename, 'a').write(outdat) return Remind._get_uid(outdat) def remove(self, uid, filename=None): """Remove the Remind command with the uid from the file""" if not filename: filename = self._filename elif filename not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(filename).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): del rem[index] open(filename, 'w').writelines(rem) break def replace(self, uid, ical, filename=None): """Update the Remind command with the uid in the file with the new iCalendar""" return self.replace_vobject(uid, readOne(ical), filename) def replace_vobject(self, uid, ical, filename=None): """Update the Remind command with the uid in the file with the new iCalendar""" if not filename: filename = self._filename elif filename not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(filename).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): rem[index] = self.to_reminders(ical) new_uid = self._get_uid(rem[index]) open(filename, 'w').writelines(rem) return new_uid def move_vobject(self, uid, from_file, to_file): """Move the Remind command with the uid from from_file to to_file""" if from_file not in self._reminders or to_file not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(from_file).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): del rem[index] open(from_file, 'w').writelines(rem) open(to_file, 'a').write(line) break def get_meta(self): """Meta tags of the vObject collection""" return {'tag': 'VCALENDAR', 'C:supported-calendar-component-set': 'VEVENT'} def last_modified(self): """Last time the Remind files where parsed""" self._update() return self._mtime
jspricke/python-remind
remind.py
Remind.to_vobjects
python
def to_vobjects(self, filename, uids=None): self._update() if not uids: uids = self._reminders[filename] items = [] for uid in uids: cal = iCalendar() self._gen_vevent(self._reminders[filename][uid], cal.add('vevent')) etag = md5() etag.update(self._reminders[filename][uid]['line'].encode("utf-8")) items.append((uid, cal, '"%s"' % etag.hexdigest())) return items
Return iCal objects and etags of all Remind entries in uids filename -- the remind file uids -- the UIDs of the Remind lines (all if None)
train
https://github.com/jspricke/python-remind/blob/dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1/remind.py#L290-L309
[ "def _gen_vevent(self, event, vevent):\n \"\"\"Generate vevent from given event\"\"\"\n vevent.add('dtstart').value = event['dtstart'][0]\n vevent.add('dtstamp').value = datetime.fromtimestamp(self._mtime)\n vevent.add('summary').value = event['msg']\n vevent.add('uid').value = event['uid']\n\n if...
class Remind(object): """Represents a collection of Remind files""" def __init__(self, filename=expanduser('~/.reminders'), localtz=None, startdate=date.today() - timedelta(weeks=12), month=15, alarm=timedelta(minutes=-10)): """Constructor filename -- the remind file (included files will be used as well) localtz -- the timezone of the remind file startdate -- the date to start parsing, will be passed to remind month -- how many month to parse, will be passed to remind -s """ self._localtz = localtz if localtz else get_localzone() self._filename = filename self._startdate = startdate self._month = month self._lock = Lock() self._reminders = {} self._mtime = 0 self._alarm = alarm self._update() def _parse_remind(self, filename, lines=''): """Calls remind and parses the output into a dict filename -- the remind file (included files will be used as well) lines -- used as stdin to remind (filename will be set to -) """ files = {} reminders = {} if lines: filename = '-' files[filename] = lines reminders[filename] = {} cmd = ['remind', '-l', '-s%d' % self._month, '-b1', '-y', '-r', filename, str(self._startdate)] try: rem = Popen(cmd, stdin=PIPE, stdout=PIPE).communicate(input=lines.encode('utf-8'))[0].decode('utf-8') except OSError: raise OSError('Error running: %s' % ' '.join(cmd)) rem = rem.splitlines() for (fileinfo, line) in zip(rem[::2], rem[1::2]): fileinfo = fileinfo.split() src_filename = fileinfo[3] if src_filename not in files: # There is a race condition with the remind call above here. # This could be solved by parsing the remind -de output, # but I don't see an easy way to do that. files[src_filename] = open(src_filename).readlines() reminders[src_filename] = {} mtime = getmtime(src_filename) if mtime > self._mtime: self._mtime = mtime text = files[src_filename][int(fileinfo[2]) - 1] event = self._parse_remind_line(line, text) if event['uid'] in reminders[src_filename]: reminders[src_filename][event['uid']]['dtstart'] += event['dtstart'] reminders[src_filename][event['uid']]['line'] += line else: reminders[src_filename][event['uid']] = event reminders[src_filename][event['uid']]['line'] = line # Find included files without reminders and add them to the file list for source in files.values(): for line in source: if line.startswith('include'): new_file = line.split(' ')[1].strip() if new_file not in reminders: reminders[new_file] = {} mtime = getmtime(new_file) if mtime > self._mtime: self._mtime = mtime return reminders @staticmethod def _gen_description(text): """Convert from Remind MSG to iCal description Opposite of _gen_msg() """ return text[text.rfind('%"') + 3:].replace('%_', '\n').replace('["["]', '[').strip() def _parse_remind_line(self, line, text): """Parse a line of remind output into a dict line -- the remind output text -- the original remind input """ event = {} line = line.split(None, 6) dat = [int(f) for f in line[0].split('/')] if line[4] != '*': start = divmod(int(line[4]), 60) event['dtstart'] = [datetime(dat[0], dat[1], dat[2], start[0], start[1], tzinfo=self._localtz)] if line[3] != '*': event['duration'] = timedelta(minutes=int(line[3])) else: event['dtstart'] = [date(dat[0], dat[1], dat[2])] msg = ' '.join(line[5:]) if line[4] == '*' else line[6] msg = msg.strip().replace('%_', '\n').replace('["["]', '[') if ' at ' in msg: (event['msg'], event['location']) = msg.rsplit(' at ', 1) else: event['msg'] = msg if '%"' in text: event['description'] = Remind._gen_description(text) tags = line[2].split(',') classes = ['PUBLIC', 'PRIVATE', 'CONFIDENTIAL'] for tag in tags[:-1]: if tag in classes: event['class'] = tag event['categories'] = [tag for tag in tags[:-1] if tag not in classes] event['uid'] = '%s@%s' % (tags[-1][7:], getfqdn()) return event @staticmethod def _interval(dates): """Return the distance between all dates and 0 if they are different""" interval = (dates[1] - dates[0]).days last = dates[0] for dat in dates[1:]: if (dat - last).days != interval: return 0 last = dat return interval @staticmethod def _gen_dtend_rrule(dtstarts, vevent): """Generate an rdate or rrule from a list of dates and add it to the vevent""" interval = Remind._interval(dtstarts) if interval > 0 and interval % 7 == 0: rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.WEEKLY, interval=interval // 7, count=len(dtstarts))) vevent.rruleset = rset elif interval > 1: rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.DAILY, interval=interval, count=len(dtstarts))) vevent.rruleset = rset elif interval > 0: if isinstance(dtstarts[0], datetime): rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.DAILY, count=len(dtstarts))) vevent.rruleset = rset else: vevent.add('dtend').value = dtstarts[-1] + timedelta(days=1) else: rset = rrule.rruleset() if isinstance(dtstarts[0], datetime): for dat in dtstarts: rset.rdate(dat) else: for dat in dtstarts: rset.rdate(datetime(dat.year, dat.month, dat.day)) # temporary set dtstart to a different date, so it's not # removed from rset by python-vobject works around bug in # Android: # https://github.com/rfc2822/davdroid/issues/340 vevent.dtstart.value = dtstarts[0] - timedelta(days=1) vevent.rruleset = rset vevent.dtstart.value = dtstarts[0] if not isinstance(dtstarts[0], datetime): vevent.add('dtend').value = dtstarts[0] + timedelta(days=1) def _gen_vevent(self, event, vevent): """Generate vevent from given event""" vevent.add('dtstart').value = event['dtstart'][0] vevent.add('dtstamp').value = datetime.fromtimestamp(self._mtime) vevent.add('summary').value = event['msg'] vevent.add('uid').value = event['uid'] if 'class' in event: vevent.add('class').value = event['class'] if 'categories' in event and len(event['categories']) > 0: vevent.add('categories').value = event['categories'] if 'location' in event: vevent.add('location').value = event['location'] if 'description' in event: vevent.add('description').value = event['description'] if isinstance(event['dtstart'][0], datetime): if self._alarm != timedelta(): valarm = vevent.add('valarm') valarm.add('trigger').value = self._alarm valarm.add('action').value = 'DISPLAY' valarm.add('description').value = event['msg'] if 'duration' in event: vevent.add('duration').value = event['duration'] else: vevent.add('dtend').value = event['dtstart'][0] elif len(event['dtstart']) == 1: vevent.add('dtend').value = event['dtstart'][0] + timedelta(days=1) if len(event['dtstart']) > 1: Remind._gen_dtend_rrule(event['dtstart'], vevent) def _update(self): """Reload Remind files if the mtime is newer""" update = not self._reminders with self._lock: for fname in self._reminders: if getmtime(fname) > self._mtime: update = True break if update: self._reminders = self._parse_remind(self._filename) def get_filesnames(self): """All filenames parsed by remind (including included files)""" self._update() return list(self._reminders.keys()) @staticmethod def _get_uid(line): """UID of a remind line""" return '%s@%s' % (md5(line[:-1].encode('utf-8')).hexdigest(), getfqdn()) def get_uids(self, filename=None): """UIDs of all reminders in the file excluding included files If a filename is specified, only it's UIDs are return, otherwise all. filename -- the remind file """ self._update() if filename: if filename not in self._reminders: return [] return self._reminders[filename].keys() return [uid for uids in self._reminders.values() for uid in uids] def to_vobject_etag(self, filename, uid): """Return iCal object and etag of one Remind entry filename -- the remind file uid -- the UID of the Remind line """ return self.to_vobjects(filename, [uid])[0][1:3] def to_vobject(self, filename=None, uid=None): """Return iCal object of Remind lines If filename and UID are specified, the vObject only contains that event. If only a filename is specified, the vObject contains all events in the file. Otherwise the vObject contains all all objects of all files associated with the Remind object. filename -- the remind file uid -- the UID of the Remind line """ self._update() cal = iCalendar() if uid: self._gen_vevent(self._reminders[filename][uid], cal.add('vevent')) elif filename: for event in self._reminders[filename].values(): self._gen_vevent(event, cal.add('vevent')) else: for filename in self._reminders: for event in self._reminders[filename].values(): self._gen_vevent(event, cal.add('vevent')) return cal def stdin_to_vobject(self, lines): """Return iCal object of the Remind commands in lines""" cal = iCalendar() for event in self._parse_remind('-', lines)['-'].values(): self._gen_vevent(event, cal.add('vevent')) return cal @staticmethod def _parse_rdate(rdates): """Convert from iCal rdate to Remind trigdate syntax""" trigdates = [rdate.strftime("trigdate()=='%Y-%m-%d'") for rdate in rdates] return 'SATISFY [%s]' % '||'.join(trigdates) @staticmethod def _parse_rruleset(rruleset): """Convert from iCal rrule to Remind recurrence syntax""" # pylint: disable=protected-access if rruleset._rrule[0]._freq == 0: return [] rep = [] if rruleset._rrule[0]._byweekday and len(rruleset._rrule[0]._byweekday) > 1: rep.append('*1') elif rruleset._rrule[0]._freq == rrule.DAILY: rep.append('*%d' % rruleset._rrule[0]._interval) elif rruleset._rrule[0]._freq == rrule.WEEKLY: rep.append('*%d' % (7 * rruleset._rrule[0]._interval)) else: return Remind._parse_rdate(rruleset._rrule[0]) if rruleset._rrule[0]._byweekday and len(rruleset._rrule[0]._byweekday) > 1: daynums = set(range(7)) - set(rruleset._rrule[0]._byweekday) weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] days = [weekdays[day] for day in daynums] rep.append('SKIP OMIT %s' % ' '.join(days)) if rruleset._rrule[0]._until: rep.append(rruleset._rrule[0]._until.strftime('UNTIL %b %d %Y').replace(' 0', ' ')) elif rruleset._rrule[0]._count: rep.append(rruleset[-1].strftime('UNTIL %b %d %Y').replace(' 0', ' ')) return rep @staticmethod def _event_duration(vevent): """unify dtend and duration to the duration of the given vevent""" if hasattr(vevent, 'dtend'): return vevent.dtend.value - vevent.dtstart.value elif hasattr(vevent, 'duration') and vevent.duration.value: return vevent.duration.value return timedelta(0) @staticmethod def _gen_msg(vevent, label, tail, sep): """Generate a Remind MSG from the given vevent. Opposite of _gen_description() """ rem = ['MSG'] msg = [] if label: msg.append(label) if hasattr(vevent, 'summary') and vevent.summary.value: msg.append(Remind._rem_clean(vevent.summary.value)) else: msg.append('empty reminder') if hasattr(vevent, 'location') and vevent.location.value: msg.append('at %s' % Remind._rem_clean(vevent.location.value)) has_desc = hasattr(vevent, 'description') and vevent.description.value if tail or has_desc: rem.append('%%"%s%%"' % ' '.join(msg)) else: rem.append(' '.join(msg)) if tail: rem.append(tail) if has_desc: rem[-1] += sep + Remind._rem_clean(vevent.description.value) return ' '.join(rem) @staticmethod def _rem_clean(rem): """Strip, transform newlines, and escape '[' in string so it's acceptable as a remind entry.""" return rem.strip().replace('\n', '%_').replace('[', '["["]') @staticmethod def _abbr_tag(tag): """Transform a string so it's acceptable as a remind tag. """ return tag.replace(" ", "")[:48] def to_remind(self, vevent, label=None, priority=None, tags=None, tail=None, sep=" ", postdate=None, posttime=None): """Generate a Remind command from the given vevent""" remind = ['REM'] trigdates = None if hasattr(vevent, 'rrule'): trigdates = Remind._parse_rruleset(vevent.rruleset) dtstart = vevent.dtstart.value # If we don't get timezone information, handle it as a naive datetime. # See https://github.com/jspricke/python-remind/issues/2 for reference. if isinstance(dtstart, datetime) and dtstart.tzinfo: dtstart = dtstart.astimezone(self._localtz) dtend = None if hasattr(vevent, 'dtend'): dtend = vevent.dtend.value if isinstance(dtend, datetime) and dtend.tzinfo: dtend = dtend.astimezone(self._localtz) if not hasattr(vevent, 'rdate') and not isinstance(trigdates, str): remind.append(dtstart.strftime('%b %d %Y').replace(' 0', ' ')) if postdate: remind.append(postdate) if priority: remind.append('PRIORITY %s' % priority) if isinstance(trigdates, list): remind.extend(trigdates) duration = Remind._event_duration(vevent) if type(dtstart) is date and duration.days > 1: remind.append('*1') if dtend is not None: dtend -= timedelta(days=1) remind.append(dtend.strftime('UNTIL %b %d %Y').replace(' 0', ' ')) if isinstance(dtstart, datetime): remind.append(dtstart.strftime('AT %H:%M').replace(' 0', ' ')) if posttime: remind.append(posttime) if duration.total_seconds() > 0: remind.append('DURATION %d:%02d' % divmod(duration.total_seconds() / 60, 60)) if hasattr(vevent, 'rdate'): remind.append(Remind._parse_rdate(vevent.rdate.value)) elif isinstance(trigdates, str): remind.append(trigdates) if hasattr(vevent, 'class'): remind.append('TAG %s' % Remind._abbr_tag(vevent.getChildValue('class'))) if tags: remind.extend(['TAG %s' % Remind._abbr_tag(tag) for tag in tags]) if hasattr(vevent, 'categories_list'): for categories in vevent.categories_list: for category in categories.value: remind.append('TAG %s' % Remind._abbr_tag(category)) remind.append(Remind._gen_msg(vevent, label, tail, sep)) return ' '.join(remind) + '\n' def to_reminders(self, ical, label=None, priority=None, tags=None, tail=None, sep=" ", postdate=None, posttime=None): """Return Remind commands for all events of a iCalendar""" if not hasattr(ical, 'vevent_list'): return '' reminders = [self.to_remind(vevent, label, priority, tags, tail, sep, postdate, posttime) for vevent in ical.vevent_list] return ''.join(reminders) def append(self, ical, filename=None): """Append a Remind command generated from the iCalendar to the file""" return self.append_vobject(readOne(ical), filename) def append_vobject(self, ical, filename=None): """Append a Remind command generated from the iCalendar to the file""" if not filename: filename = self._filename elif filename not in self._reminders: return with self._lock: outdat = self.to_reminders(ical) open(filename, 'a').write(outdat) return Remind._get_uid(outdat) def remove(self, uid, filename=None): """Remove the Remind command with the uid from the file""" if not filename: filename = self._filename elif filename not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(filename).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): del rem[index] open(filename, 'w').writelines(rem) break def replace(self, uid, ical, filename=None): """Update the Remind command with the uid in the file with the new iCalendar""" return self.replace_vobject(uid, readOne(ical), filename) def replace_vobject(self, uid, ical, filename=None): """Update the Remind command with the uid in the file with the new iCalendar""" if not filename: filename = self._filename elif filename not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(filename).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): rem[index] = self.to_reminders(ical) new_uid = self._get_uid(rem[index]) open(filename, 'w').writelines(rem) return new_uid def move_vobject(self, uid, from_file, to_file): """Move the Remind command with the uid from from_file to to_file""" if from_file not in self._reminders or to_file not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(from_file).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): del rem[index] open(from_file, 'w').writelines(rem) open(to_file, 'a').write(line) break def get_meta(self): """Meta tags of the vObject collection""" return {'tag': 'VCALENDAR', 'C:supported-calendar-component-set': 'VEVENT'} def last_modified(self): """Last time the Remind files where parsed""" self._update() return self._mtime
jspricke/python-remind
remind.py
Remind.to_vobject
python
def to_vobject(self, filename=None, uid=None): self._update() cal = iCalendar() if uid: self._gen_vevent(self._reminders[filename][uid], cal.add('vevent')) elif filename: for event in self._reminders[filename].values(): self._gen_vevent(event, cal.add('vevent')) else: for filename in self._reminders: for event in self._reminders[filename].values(): self._gen_vevent(event, cal.add('vevent')) return cal
Return iCal object of Remind lines If filename and UID are specified, the vObject only contains that event. If only a filename is specified, the vObject contains all events in the file. Otherwise the vObject contains all all objects of all files associated with the Remind object. filename -- the remind file uid -- the UID of the Remind line
train
https://github.com/jspricke/python-remind/blob/dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1/remind.py#L311-L332
[ "def _gen_vevent(self, event, vevent):\n \"\"\"Generate vevent from given event\"\"\"\n vevent.add('dtstart').value = event['dtstart'][0]\n vevent.add('dtstamp').value = datetime.fromtimestamp(self._mtime)\n vevent.add('summary').value = event['msg']\n vevent.add('uid').value = event['uid']\n\n if...
class Remind(object): """Represents a collection of Remind files""" def __init__(self, filename=expanduser('~/.reminders'), localtz=None, startdate=date.today() - timedelta(weeks=12), month=15, alarm=timedelta(minutes=-10)): """Constructor filename -- the remind file (included files will be used as well) localtz -- the timezone of the remind file startdate -- the date to start parsing, will be passed to remind month -- how many month to parse, will be passed to remind -s """ self._localtz = localtz if localtz else get_localzone() self._filename = filename self._startdate = startdate self._month = month self._lock = Lock() self._reminders = {} self._mtime = 0 self._alarm = alarm self._update() def _parse_remind(self, filename, lines=''): """Calls remind and parses the output into a dict filename -- the remind file (included files will be used as well) lines -- used as stdin to remind (filename will be set to -) """ files = {} reminders = {} if lines: filename = '-' files[filename] = lines reminders[filename] = {} cmd = ['remind', '-l', '-s%d' % self._month, '-b1', '-y', '-r', filename, str(self._startdate)] try: rem = Popen(cmd, stdin=PIPE, stdout=PIPE).communicate(input=lines.encode('utf-8'))[0].decode('utf-8') except OSError: raise OSError('Error running: %s' % ' '.join(cmd)) rem = rem.splitlines() for (fileinfo, line) in zip(rem[::2], rem[1::2]): fileinfo = fileinfo.split() src_filename = fileinfo[3] if src_filename not in files: # There is a race condition with the remind call above here. # This could be solved by parsing the remind -de output, # but I don't see an easy way to do that. files[src_filename] = open(src_filename).readlines() reminders[src_filename] = {} mtime = getmtime(src_filename) if mtime > self._mtime: self._mtime = mtime text = files[src_filename][int(fileinfo[2]) - 1] event = self._parse_remind_line(line, text) if event['uid'] in reminders[src_filename]: reminders[src_filename][event['uid']]['dtstart'] += event['dtstart'] reminders[src_filename][event['uid']]['line'] += line else: reminders[src_filename][event['uid']] = event reminders[src_filename][event['uid']]['line'] = line # Find included files without reminders and add them to the file list for source in files.values(): for line in source: if line.startswith('include'): new_file = line.split(' ')[1].strip() if new_file not in reminders: reminders[new_file] = {} mtime = getmtime(new_file) if mtime > self._mtime: self._mtime = mtime return reminders @staticmethod def _gen_description(text): """Convert from Remind MSG to iCal description Opposite of _gen_msg() """ return text[text.rfind('%"') + 3:].replace('%_', '\n').replace('["["]', '[').strip() def _parse_remind_line(self, line, text): """Parse a line of remind output into a dict line -- the remind output text -- the original remind input """ event = {} line = line.split(None, 6) dat = [int(f) for f in line[0].split('/')] if line[4] != '*': start = divmod(int(line[4]), 60) event['dtstart'] = [datetime(dat[0], dat[1], dat[2], start[0], start[1], tzinfo=self._localtz)] if line[3] != '*': event['duration'] = timedelta(minutes=int(line[3])) else: event['dtstart'] = [date(dat[0], dat[1], dat[2])] msg = ' '.join(line[5:]) if line[4] == '*' else line[6] msg = msg.strip().replace('%_', '\n').replace('["["]', '[') if ' at ' in msg: (event['msg'], event['location']) = msg.rsplit(' at ', 1) else: event['msg'] = msg if '%"' in text: event['description'] = Remind._gen_description(text) tags = line[2].split(',') classes = ['PUBLIC', 'PRIVATE', 'CONFIDENTIAL'] for tag in tags[:-1]: if tag in classes: event['class'] = tag event['categories'] = [tag for tag in tags[:-1] if tag not in classes] event['uid'] = '%s@%s' % (tags[-1][7:], getfqdn()) return event @staticmethod def _interval(dates): """Return the distance between all dates and 0 if they are different""" interval = (dates[1] - dates[0]).days last = dates[0] for dat in dates[1:]: if (dat - last).days != interval: return 0 last = dat return interval @staticmethod def _gen_dtend_rrule(dtstarts, vevent): """Generate an rdate or rrule from a list of dates and add it to the vevent""" interval = Remind._interval(dtstarts) if interval > 0 and interval % 7 == 0: rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.WEEKLY, interval=interval // 7, count=len(dtstarts))) vevent.rruleset = rset elif interval > 1: rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.DAILY, interval=interval, count=len(dtstarts))) vevent.rruleset = rset elif interval > 0: if isinstance(dtstarts[0], datetime): rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.DAILY, count=len(dtstarts))) vevent.rruleset = rset else: vevent.add('dtend').value = dtstarts[-1] + timedelta(days=1) else: rset = rrule.rruleset() if isinstance(dtstarts[0], datetime): for dat in dtstarts: rset.rdate(dat) else: for dat in dtstarts: rset.rdate(datetime(dat.year, dat.month, dat.day)) # temporary set dtstart to a different date, so it's not # removed from rset by python-vobject works around bug in # Android: # https://github.com/rfc2822/davdroid/issues/340 vevent.dtstart.value = dtstarts[0] - timedelta(days=1) vevent.rruleset = rset vevent.dtstart.value = dtstarts[0] if not isinstance(dtstarts[0], datetime): vevent.add('dtend').value = dtstarts[0] + timedelta(days=1) def _gen_vevent(self, event, vevent): """Generate vevent from given event""" vevent.add('dtstart').value = event['dtstart'][0] vevent.add('dtstamp').value = datetime.fromtimestamp(self._mtime) vevent.add('summary').value = event['msg'] vevent.add('uid').value = event['uid'] if 'class' in event: vevent.add('class').value = event['class'] if 'categories' in event and len(event['categories']) > 0: vevent.add('categories').value = event['categories'] if 'location' in event: vevent.add('location').value = event['location'] if 'description' in event: vevent.add('description').value = event['description'] if isinstance(event['dtstart'][0], datetime): if self._alarm != timedelta(): valarm = vevent.add('valarm') valarm.add('trigger').value = self._alarm valarm.add('action').value = 'DISPLAY' valarm.add('description').value = event['msg'] if 'duration' in event: vevent.add('duration').value = event['duration'] else: vevent.add('dtend').value = event['dtstart'][0] elif len(event['dtstart']) == 1: vevent.add('dtend').value = event['dtstart'][0] + timedelta(days=1) if len(event['dtstart']) > 1: Remind._gen_dtend_rrule(event['dtstart'], vevent) def _update(self): """Reload Remind files if the mtime is newer""" update = not self._reminders with self._lock: for fname in self._reminders: if getmtime(fname) > self._mtime: update = True break if update: self._reminders = self._parse_remind(self._filename) def get_filesnames(self): """All filenames parsed by remind (including included files)""" self._update() return list(self._reminders.keys()) @staticmethod def _get_uid(line): """UID of a remind line""" return '%s@%s' % (md5(line[:-1].encode('utf-8')).hexdigest(), getfqdn()) def get_uids(self, filename=None): """UIDs of all reminders in the file excluding included files If a filename is specified, only it's UIDs are return, otherwise all. filename -- the remind file """ self._update() if filename: if filename not in self._reminders: return [] return self._reminders[filename].keys() return [uid for uids in self._reminders.values() for uid in uids] def to_vobject_etag(self, filename, uid): """Return iCal object and etag of one Remind entry filename -- the remind file uid -- the UID of the Remind line """ return self.to_vobjects(filename, [uid])[0][1:3] def to_vobjects(self, filename, uids=None): """Return iCal objects and etags of all Remind entries in uids filename -- the remind file uids -- the UIDs of the Remind lines (all if None) """ self._update() if not uids: uids = self._reminders[filename] items = [] for uid in uids: cal = iCalendar() self._gen_vevent(self._reminders[filename][uid], cal.add('vevent')) etag = md5() etag.update(self._reminders[filename][uid]['line'].encode("utf-8")) items.append((uid, cal, '"%s"' % etag.hexdigest())) return items def stdin_to_vobject(self, lines): """Return iCal object of the Remind commands in lines""" cal = iCalendar() for event in self._parse_remind('-', lines)['-'].values(): self._gen_vevent(event, cal.add('vevent')) return cal @staticmethod def _parse_rdate(rdates): """Convert from iCal rdate to Remind trigdate syntax""" trigdates = [rdate.strftime("trigdate()=='%Y-%m-%d'") for rdate in rdates] return 'SATISFY [%s]' % '||'.join(trigdates) @staticmethod def _parse_rruleset(rruleset): """Convert from iCal rrule to Remind recurrence syntax""" # pylint: disable=protected-access if rruleset._rrule[0]._freq == 0: return [] rep = [] if rruleset._rrule[0]._byweekday and len(rruleset._rrule[0]._byweekday) > 1: rep.append('*1') elif rruleset._rrule[0]._freq == rrule.DAILY: rep.append('*%d' % rruleset._rrule[0]._interval) elif rruleset._rrule[0]._freq == rrule.WEEKLY: rep.append('*%d' % (7 * rruleset._rrule[0]._interval)) else: return Remind._parse_rdate(rruleset._rrule[0]) if rruleset._rrule[0]._byweekday and len(rruleset._rrule[0]._byweekday) > 1: daynums = set(range(7)) - set(rruleset._rrule[0]._byweekday) weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] days = [weekdays[day] for day in daynums] rep.append('SKIP OMIT %s' % ' '.join(days)) if rruleset._rrule[0]._until: rep.append(rruleset._rrule[0]._until.strftime('UNTIL %b %d %Y').replace(' 0', ' ')) elif rruleset._rrule[0]._count: rep.append(rruleset[-1].strftime('UNTIL %b %d %Y').replace(' 0', ' ')) return rep @staticmethod def _event_duration(vevent): """unify dtend and duration to the duration of the given vevent""" if hasattr(vevent, 'dtend'): return vevent.dtend.value - vevent.dtstart.value elif hasattr(vevent, 'duration') and vevent.duration.value: return vevent.duration.value return timedelta(0) @staticmethod def _gen_msg(vevent, label, tail, sep): """Generate a Remind MSG from the given vevent. Opposite of _gen_description() """ rem = ['MSG'] msg = [] if label: msg.append(label) if hasattr(vevent, 'summary') and vevent.summary.value: msg.append(Remind._rem_clean(vevent.summary.value)) else: msg.append('empty reminder') if hasattr(vevent, 'location') and vevent.location.value: msg.append('at %s' % Remind._rem_clean(vevent.location.value)) has_desc = hasattr(vevent, 'description') and vevent.description.value if tail or has_desc: rem.append('%%"%s%%"' % ' '.join(msg)) else: rem.append(' '.join(msg)) if tail: rem.append(tail) if has_desc: rem[-1] += sep + Remind._rem_clean(vevent.description.value) return ' '.join(rem) @staticmethod def _rem_clean(rem): """Strip, transform newlines, and escape '[' in string so it's acceptable as a remind entry.""" return rem.strip().replace('\n', '%_').replace('[', '["["]') @staticmethod def _abbr_tag(tag): """Transform a string so it's acceptable as a remind tag. """ return tag.replace(" ", "")[:48] def to_remind(self, vevent, label=None, priority=None, tags=None, tail=None, sep=" ", postdate=None, posttime=None): """Generate a Remind command from the given vevent""" remind = ['REM'] trigdates = None if hasattr(vevent, 'rrule'): trigdates = Remind._parse_rruleset(vevent.rruleset) dtstart = vevent.dtstart.value # If we don't get timezone information, handle it as a naive datetime. # See https://github.com/jspricke/python-remind/issues/2 for reference. if isinstance(dtstart, datetime) and dtstart.tzinfo: dtstart = dtstart.astimezone(self._localtz) dtend = None if hasattr(vevent, 'dtend'): dtend = vevent.dtend.value if isinstance(dtend, datetime) and dtend.tzinfo: dtend = dtend.astimezone(self._localtz) if not hasattr(vevent, 'rdate') and not isinstance(trigdates, str): remind.append(dtstart.strftime('%b %d %Y').replace(' 0', ' ')) if postdate: remind.append(postdate) if priority: remind.append('PRIORITY %s' % priority) if isinstance(trigdates, list): remind.extend(trigdates) duration = Remind._event_duration(vevent) if type(dtstart) is date and duration.days > 1: remind.append('*1') if dtend is not None: dtend -= timedelta(days=1) remind.append(dtend.strftime('UNTIL %b %d %Y').replace(' 0', ' ')) if isinstance(dtstart, datetime): remind.append(dtstart.strftime('AT %H:%M').replace(' 0', ' ')) if posttime: remind.append(posttime) if duration.total_seconds() > 0: remind.append('DURATION %d:%02d' % divmod(duration.total_seconds() / 60, 60)) if hasattr(vevent, 'rdate'): remind.append(Remind._parse_rdate(vevent.rdate.value)) elif isinstance(trigdates, str): remind.append(trigdates) if hasattr(vevent, 'class'): remind.append('TAG %s' % Remind._abbr_tag(vevent.getChildValue('class'))) if tags: remind.extend(['TAG %s' % Remind._abbr_tag(tag) for tag in tags]) if hasattr(vevent, 'categories_list'): for categories in vevent.categories_list: for category in categories.value: remind.append('TAG %s' % Remind._abbr_tag(category)) remind.append(Remind._gen_msg(vevent, label, tail, sep)) return ' '.join(remind) + '\n' def to_reminders(self, ical, label=None, priority=None, tags=None, tail=None, sep=" ", postdate=None, posttime=None): """Return Remind commands for all events of a iCalendar""" if not hasattr(ical, 'vevent_list'): return '' reminders = [self.to_remind(vevent, label, priority, tags, tail, sep, postdate, posttime) for vevent in ical.vevent_list] return ''.join(reminders) def append(self, ical, filename=None): """Append a Remind command generated from the iCalendar to the file""" return self.append_vobject(readOne(ical), filename) def append_vobject(self, ical, filename=None): """Append a Remind command generated from the iCalendar to the file""" if not filename: filename = self._filename elif filename not in self._reminders: return with self._lock: outdat = self.to_reminders(ical) open(filename, 'a').write(outdat) return Remind._get_uid(outdat) def remove(self, uid, filename=None): """Remove the Remind command with the uid from the file""" if not filename: filename = self._filename elif filename not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(filename).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): del rem[index] open(filename, 'w').writelines(rem) break def replace(self, uid, ical, filename=None): """Update the Remind command with the uid in the file with the new iCalendar""" return self.replace_vobject(uid, readOne(ical), filename) def replace_vobject(self, uid, ical, filename=None): """Update the Remind command with the uid in the file with the new iCalendar""" if not filename: filename = self._filename elif filename not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(filename).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): rem[index] = self.to_reminders(ical) new_uid = self._get_uid(rem[index]) open(filename, 'w').writelines(rem) return new_uid def move_vobject(self, uid, from_file, to_file): """Move the Remind command with the uid from from_file to to_file""" if from_file not in self._reminders or to_file not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(from_file).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): del rem[index] open(from_file, 'w').writelines(rem) open(to_file, 'a').write(line) break def get_meta(self): """Meta tags of the vObject collection""" return {'tag': 'VCALENDAR', 'C:supported-calendar-component-set': 'VEVENT'} def last_modified(self): """Last time the Remind files where parsed""" self._update() return self._mtime
jspricke/python-remind
remind.py
Remind.stdin_to_vobject
python
def stdin_to_vobject(self, lines): cal = iCalendar() for event in self._parse_remind('-', lines)['-'].values(): self._gen_vevent(event, cal.add('vevent')) return cal
Return iCal object of the Remind commands in lines
train
https://github.com/jspricke/python-remind/blob/dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1/remind.py#L334-L339
[ "def _parse_remind(self, filename, lines=''):\n \"\"\"Calls remind and parses the output into a dict\n\n filename -- the remind file (included files will be used as well)\n lines -- used as stdin to remind (filename will be set to -)\n \"\"\"\n files = {}\n reminders = {}\n if lines:\n f...
class Remind(object): """Represents a collection of Remind files""" def __init__(self, filename=expanduser('~/.reminders'), localtz=None, startdate=date.today() - timedelta(weeks=12), month=15, alarm=timedelta(minutes=-10)): """Constructor filename -- the remind file (included files will be used as well) localtz -- the timezone of the remind file startdate -- the date to start parsing, will be passed to remind month -- how many month to parse, will be passed to remind -s """ self._localtz = localtz if localtz else get_localzone() self._filename = filename self._startdate = startdate self._month = month self._lock = Lock() self._reminders = {} self._mtime = 0 self._alarm = alarm self._update() def _parse_remind(self, filename, lines=''): """Calls remind and parses the output into a dict filename -- the remind file (included files will be used as well) lines -- used as stdin to remind (filename will be set to -) """ files = {} reminders = {} if lines: filename = '-' files[filename] = lines reminders[filename] = {} cmd = ['remind', '-l', '-s%d' % self._month, '-b1', '-y', '-r', filename, str(self._startdate)] try: rem = Popen(cmd, stdin=PIPE, stdout=PIPE).communicate(input=lines.encode('utf-8'))[0].decode('utf-8') except OSError: raise OSError('Error running: %s' % ' '.join(cmd)) rem = rem.splitlines() for (fileinfo, line) in zip(rem[::2], rem[1::2]): fileinfo = fileinfo.split() src_filename = fileinfo[3] if src_filename not in files: # There is a race condition with the remind call above here. # This could be solved by parsing the remind -de output, # but I don't see an easy way to do that. files[src_filename] = open(src_filename).readlines() reminders[src_filename] = {} mtime = getmtime(src_filename) if mtime > self._mtime: self._mtime = mtime text = files[src_filename][int(fileinfo[2]) - 1] event = self._parse_remind_line(line, text) if event['uid'] in reminders[src_filename]: reminders[src_filename][event['uid']]['dtstart'] += event['dtstart'] reminders[src_filename][event['uid']]['line'] += line else: reminders[src_filename][event['uid']] = event reminders[src_filename][event['uid']]['line'] = line # Find included files without reminders and add them to the file list for source in files.values(): for line in source: if line.startswith('include'): new_file = line.split(' ')[1].strip() if new_file not in reminders: reminders[new_file] = {} mtime = getmtime(new_file) if mtime > self._mtime: self._mtime = mtime return reminders @staticmethod def _gen_description(text): """Convert from Remind MSG to iCal description Opposite of _gen_msg() """ return text[text.rfind('%"') + 3:].replace('%_', '\n').replace('["["]', '[').strip() def _parse_remind_line(self, line, text): """Parse a line of remind output into a dict line -- the remind output text -- the original remind input """ event = {} line = line.split(None, 6) dat = [int(f) for f in line[0].split('/')] if line[4] != '*': start = divmod(int(line[4]), 60) event['dtstart'] = [datetime(dat[0], dat[1], dat[2], start[0], start[1], tzinfo=self._localtz)] if line[3] != '*': event['duration'] = timedelta(minutes=int(line[3])) else: event['dtstart'] = [date(dat[0], dat[1], dat[2])] msg = ' '.join(line[5:]) if line[4] == '*' else line[6] msg = msg.strip().replace('%_', '\n').replace('["["]', '[') if ' at ' in msg: (event['msg'], event['location']) = msg.rsplit(' at ', 1) else: event['msg'] = msg if '%"' in text: event['description'] = Remind._gen_description(text) tags = line[2].split(',') classes = ['PUBLIC', 'PRIVATE', 'CONFIDENTIAL'] for tag in tags[:-1]: if tag in classes: event['class'] = tag event['categories'] = [tag for tag in tags[:-1] if tag not in classes] event['uid'] = '%s@%s' % (tags[-1][7:], getfqdn()) return event @staticmethod def _interval(dates): """Return the distance between all dates and 0 if they are different""" interval = (dates[1] - dates[0]).days last = dates[0] for dat in dates[1:]: if (dat - last).days != interval: return 0 last = dat return interval @staticmethod def _gen_dtend_rrule(dtstarts, vevent): """Generate an rdate or rrule from a list of dates and add it to the vevent""" interval = Remind._interval(dtstarts) if interval > 0 and interval % 7 == 0: rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.WEEKLY, interval=interval // 7, count=len(dtstarts))) vevent.rruleset = rset elif interval > 1: rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.DAILY, interval=interval, count=len(dtstarts))) vevent.rruleset = rset elif interval > 0: if isinstance(dtstarts[0], datetime): rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.DAILY, count=len(dtstarts))) vevent.rruleset = rset else: vevent.add('dtend').value = dtstarts[-1] + timedelta(days=1) else: rset = rrule.rruleset() if isinstance(dtstarts[0], datetime): for dat in dtstarts: rset.rdate(dat) else: for dat in dtstarts: rset.rdate(datetime(dat.year, dat.month, dat.day)) # temporary set dtstart to a different date, so it's not # removed from rset by python-vobject works around bug in # Android: # https://github.com/rfc2822/davdroid/issues/340 vevent.dtstart.value = dtstarts[0] - timedelta(days=1) vevent.rruleset = rset vevent.dtstart.value = dtstarts[0] if not isinstance(dtstarts[0], datetime): vevent.add('dtend').value = dtstarts[0] + timedelta(days=1) def _gen_vevent(self, event, vevent): """Generate vevent from given event""" vevent.add('dtstart').value = event['dtstart'][0] vevent.add('dtstamp').value = datetime.fromtimestamp(self._mtime) vevent.add('summary').value = event['msg'] vevent.add('uid').value = event['uid'] if 'class' in event: vevent.add('class').value = event['class'] if 'categories' in event and len(event['categories']) > 0: vevent.add('categories').value = event['categories'] if 'location' in event: vevent.add('location').value = event['location'] if 'description' in event: vevent.add('description').value = event['description'] if isinstance(event['dtstart'][0], datetime): if self._alarm != timedelta(): valarm = vevent.add('valarm') valarm.add('trigger').value = self._alarm valarm.add('action').value = 'DISPLAY' valarm.add('description').value = event['msg'] if 'duration' in event: vevent.add('duration').value = event['duration'] else: vevent.add('dtend').value = event['dtstart'][0] elif len(event['dtstart']) == 1: vevent.add('dtend').value = event['dtstart'][0] + timedelta(days=1) if len(event['dtstart']) > 1: Remind._gen_dtend_rrule(event['dtstart'], vevent) def _update(self): """Reload Remind files if the mtime is newer""" update = not self._reminders with self._lock: for fname in self._reminders: if getmtime(fname) > self._mtime: update = True break if update: self._reminders = self._parse_remind(self._filename) def get_filesnames(self): """All filenames parsed by remind (including included files)""" self._update() return list(self._reminders.keys()) @staticmethod def _get_uid(line): """UID of a remind line""" return '%s@%s' % (md5(line[:-1].encode('utf-8')).hexdigest(), getfqdn()) def get_uids(self, filename=None): """UIDs of all reminders in the file excluding included files If a filename is specified, only it's UIDs are return, otherwise all. filename -- the remind file """ self._update() if filename: if filename not in self._reminders: return [] return self._reminders[filename].keys() return [uid for uids in self._reminders.values() for uid in uids] def to_vobject_etag(self, filename, uid): """Return iCal object and etag of one Remind entry filename -- the remind file uid -- the UID of the Remind line """ return self.to_vobjects(filename, [uid])[0][1:3] def to_vobjects(self, filename, uids=None): """Return iCal objects and etags of all Remind entries in uids filename -- the remind file uids -- the UIDs of the Remind lines (all if None) """ self._update() if not uids: uids = self._reminders[filename] items = [] for uid in uids: cal = iCalendar() self._gen_vevent(self._reminders[filename][uid], cal.add('vevent')) etag = md5() etag.update(self._reminders[filename][uid]['line'].encode("utf-8")) items.append((uid, cal, '"%s"' % etag.hexdigest())) return items def to_vobject(self, filename=None, uid=None): """Return iCal object of Remind lines If filename and UID are specified, the vObject only contains that event. If only a filename is specified, the vObject contains all events in the file. Otherwise the vObject contains all all objects of all files associated with the Remind object. filename -- the remind file uid -- the UID of the Remind line """ self._update() cal = iCalendar() if uid: self._gen_vevent(self._reminders[filename][uid], cal.add('vevent')) elif filename: for event in self._reminders[filename].values(): self._gen_vevent(event, cal.add('vevent')) else: for filename in self._reminders: for event in self._reminders[filename].values(): self._gen_vevent(event, cal.add('vevent')) return cal @staticmethod def _parse_rdate(rdates): """Convert from iCal rdate to Remind trigdate syntax""" trigdates = [rdate.strftime("trigdate()=='%Y-%m-%d'") for rdate in rdates] return 'SATISFY [%s]' % '||'.join(trigdates) @staticmethod def _parse_rruleset(rruleset): """Convert from iCal rrule to Remind recurrence syntax""" # pylint: disable=protected-access if rruleset._rrule[0]._freq == 0: return [] rep = [] if rruleset._rrule[0]._byweekday and len(rruleset._rrule[0]._byweekday) > 1: rep.append('*1') elif rruleset._rrule[0]._freq == rrule.DAILY: rep.append('*%d' % rruleset._rrule[0]._interval) elif rruleset._rrule[0]._freq == rrule.WEEKLY: rep.append('*%d' % (7 * rruleset._rrule[0]._interval)) else: return Remind._parse_rdate(rruleset._rrule[0]) if rruleset._rrule[0]._byweekday and len(rruleset._rrule[0]._byweekday) > 1: daynums = set(range(7)) - set(rruleset._rrule[0]._byweekday) weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] days = [weekdays[day] for day in daynums] rep.append('SKIP OMIT %s' % ' '.join(days)) if rruleset._rrule[0]._until: rep.append(rruleset._rrule[0]._until.strftime('UNTIL %b %d %Y').replace(' 0', ' ')) elif rruleset._rrule[0]._count: rep.append(rruleset[-1].strftime('UNTIL %b %d %Y').replace(' 0', ' ')) return rep @staticmethod def _event_duration(vevent): """unify dtend and duration to the duration of the given vevent""" if hasattr(vevent, 'dtend'): return vevent.dtend.value - vevent.dtstart.value elif hasattr(vevent, 'duration') and vevent.duration.value: return vevent.duration.value return timedelta(0) @staticmethod def _gen_msg(vevent, label, tail, sep): """Generate a Remind MSG from the given vevent. Opposite of _gen_description() """ rem = ['MSG'] msg = [] if label: msg.append(label) if hasattr(vevent, 'summary') and vevent.summary.value: msg.append(Remind._rem_clean(vevent.summary.value)) else: msg.append('empty reminder') if hasattr(vevent, 'location') and vevent.location.value: msg.append('at %s' % Remind._rem_clean(vevent.location.value)) has_desc = hasattr(vevent, 'description') and vevent.description.value if tail or has_desc: rem.append('%%"%s%%"' % ' '.join(msg)) else: rem.append(' '.join(msg)) if tail: rem.append(tail) if has_desc: rem[-1] += sep + Remind._rem_clean(vevent.description.value) return ' '.join(rem) @staticmethod def _rem_clean(rem): """Strip, transform newlines, and escape '[' in string so it's acceptable as a remind entry.""" return rem.strip().replace('\n', '%_').replace('[', '["["]') @staticmethod def _abbr_tag(tag): """Transform a string so it's acceptable as a remind tag. """ return tag.replace(" ", "")[:48] def to_remind(self, vevent, label=None, priority=None, tags=None, tail=None, sep=" ", postdate=None, posttime=None): """Generate a Remind command from the given vevent""" remind = ['REM'] trigdates = None if hasattr(vevent, 'rrule'): trigdates = Remind._parse_rruleset(vevent.rruleset) dtstart = vevent.dtstart.value # If we don't get timezone information, handle it as a naive datetime. # See https://github.com/jspricke/python-remind/issues/2 for reference. if isinstance(dtstart, datetime) and dtstart.tzinfo: dtstart = dtstart.astimezone(self._localtz) dtend = None if hasattr(vevent, 'dtend'): dtend = vevent.dtend.value if isinstance(dtend, datetime) and dtend.tzinfo: dtend = dtend.astimezone(self._localtz) if not hasattr(vevent, 'rdate') and not isinstance(trigdates, str): remind.append(dtstart.strftime('%b %d %Y').replace(' 0', ' ')) if postdate: remind.append(postdate) if priority: remind.append('PRIORITY %s' % priority) if isinstance(trigdates, list): remind.extend(trigdates) duration = Remind._event_duration(vevent) if type(dtstart) is date and duration.days > 1: remind.append('*1') if dtend is not None: dtend -= timedelta(days=1) remind.append(dtend.strftime('UNTIL %b %d %Y').replace(' 0', ' ')) if isinstance(dtstart, datetime): remind.append(dtstart.strftime('AT %H:%M').replace(' 0', ' ')) if posttime: remind.append(posttime) if duration.total_seconds() > 0: remind.append('DURATION %d:%02d' % divmod(duration.total_seconds() / 60, 60)) if hasattr(vevent, 'rdate'): remind.append(Remind._parse_rdate(vevent.rdate.value)) elif isinstance(trigdates, str): remind.append(trigdates) if hasattr(vevent, 'class'): remind.append('TAG %s' % Remind._abbr_tag(vevent.getChildValue('class'))) if tags: remind.extend(['TAG %s' % Remind._abbr_tag(tag) for tag in tags]) if hasattr(vevent, 'categories_list'): for categories in vevent.categories_list: for category in categories.value: remind.append('TAG %s' % Remind._abbr_tag(category)) remind.append(Remind._gen_msg(vevent, label, tail, sep)) return ' '.join(remind) + '\n' def to_reminders(self, ical, label=None, priority=None, tags=None, tail=None, sep=" ", postdate=None, posttime=None): """Return Remind commands for all events of a iCalendar""" if not hasattr(ical, 'vevent_list'): return '' reminders = [self.to_remind(vevent, label, priority, tags, tail, sep, postdate, posttime) for vevent in ical.vevent_list] return ''.join(reminders) def append(self, ical, filename=None): """Append a Remind command generated from the iCalendar to the file""" return self.append_vobject(readOne(ical), filename) def append_vobject(self, ical, filename=None): """Append a Remind command generated from the iCalendar to the file""" if not filename: filename = self._filename elif filename not in self._reminders: return with self._lock: outdat = self.to_reminders(ical) open(filename, 'a').write(outdat) return Remind._get_uid(outdat) def remove(self, uid, filename=None): """Remove the Remind command with the uid from the file""" if not filename: filename = self._filename elif filename not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(filename).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): del rem[index] open(filename, 'w').writelines(rem) break def replace(self, uid, ical, filename=None): """Update the Remind command with the uid in the file with the new iCalendar""" return self.replace_vobject(uid, readOne(ical), filename) def replace_vobject(self, uid, ical, filename=None): """Update the Remind command with the uid in the file with the new iCalendar""" if not filename: filename = self._filename elif filename not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(filename).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): rem[index] = self.to_reminders(ical) new_uid = self._get_uid(rem[index]) open(filename, 'w').writelines(rem) return new_uid def move_vobject(self, uid, from_file, to_file): """Move the Remind command with the uid from from_file to to_file""" if from_file not in self._reminders or to_file not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(from_file).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): del rem[index] open(from_file, 'w').writelines(rem) open(to_file, 'a').write(line) break def get_meta(self): """Meta tags of the vObject collection""" return {'tag': 'VCALENDAR', 'C:supported-calendar-component-set': 'VEVENT'} def last_modified(self): """Last time the Remind files where parsed""" self._update() return self._mtime
jspricke/python-remind
remind.py
Remind._parse_rruleset
python
def _parse_rruleset(rruleset): # pylint: disable=protected-access if rruleset._rrule[0]._freq == 0: return [] rep = [] if rruleset._rrule[0]._byweekday and len(rruleset._rrule[0]._byweekday) > 1: rep.append('*1') elif rruleset._rrule[0]._freq == rrule.DAILY: rep.append('*%d' % rruleset._rrule[0]._interval) elif rruleset._rrule[0]._freq == rrule.WEEKLY: rep.append('*%d' % (7 * rruleset._rrule[0]._interval)) else: return Remind._parse_rdate(rruleset._rrule[0]) if rruleset._rrule[0]._byweekday and len(rruleset._rrule[0]._byweekday) > 1: daynums = set(range(7)) - set(rruleset._rrule[0]._byweekday) weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] days = [weekdays[day] for day in daynums] rep.append('SKIP OMIT %s' % ' '.join(days)) if rruleset._rrule[0]._until: rep.append(rruleset._rrule[0]._until.strftime('UNTIL %b %d %Y').replace(' 0', ' ')) elif rruleset._rrule[0]._count: rep.append(rruleset[-1].strftime('UNTIL %b %d %Y').replace(' 0', ' ')) return rep
Convert from iCal rrule to Remind recurrence syntax
train
https://github.com/jspricke/python-remind/blob/dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1/remind.py#L348-L376
[ "def _parse_rdate(rdates):\n \"\"\"Convert from iCal rdate to Remind trigdate syntax\"\"\"\n trigdates = [rdate.strftime(\"trigdate()=='%Y-%m-%d'\") for rdate in rdates]\n return 'SATISFY [%s]' % '||'.join(trigdates)\n" ]
class Remind(object): """Represents a collection of Remind files""" def __init__(self, filename=expanduser('~/.reminders'), localtz=None, startdate=date.today() - timedelta(weeks=12), month=15, alarm=timedelta(minutes=-10)): """Constructor filename -- the remind file (included files will be used as well) localtz -- the timezone of the remind file startdate -- the date to start parsing, will be passed to remind month -- how many month to parse, will be passed to remind -s """ self._localtz = localtz if localtz else get_localzone() self._filename = filename self._startdate = startdate self._month = month self._lock = Lock() self._reminders = {} self._mtime = 0 self._alarm = alarm self._update() def _parse_remind(self, filename, lines=''): """Calls remind and parses the output into a dict filename -- the remind file (included files will be used as well) lines -- used as stdin to remind (filename will be set to -) """ files = {} reminders = {} if lines: filename = '-' files[filename] = lines reminders[filename] = {} cmd = ['remind', '-l', '-s%d' % self._month, '-b1', '-y', '-r', filename, str(self._startdate)] try: rem = Popen(cmd, stdin=PIPE, stdout=PIPE).communicate(input=lines.encode('utf-8'))[0].decode('utf-8') except OSError: raise OSError('Error running: %s' % ' '.join(cmd)) rem = rem.splitlines() for (fileinfo, line) in zip(rem[::2], rem[1::2]): fileinfo = fileinfo.split() src_filename = fileinfo[3] if src_filename not in files: # There is a race condition with the remind call above here. # This could be solved by parsing the remind -de output, # but I don't see an easy way to do that. files[src_filename] = open(src_filename).readlines() reminders[src_filename] = {} mtime = getmtime(src_filename) if mtime > self._mtime: self._mtime = mtime text = files[src_filename][int(fileinfo[2]) - 1] event = self._parse_remind_line(line, text) if event['uid'] in reminders[src_filename]: reminders[src_filename][event['uid']]['dtstart'] += event['dtstart'] reminders[src_filename][event['uid']]['line'] += line else: reminders[src_filename][event['uid']] = event reminders[src_filename][event['uid']]['line'] = line # Find included files without reminders and add them to the file list for source in files.values(): for line in source: if line.startswith('include'): new_file = line.split(' ')[1].strip() if new_file not in reminders: reminders[new_file] = {} mtime = getmtime(new_file) if mtime > self._mtime: self._mtime = mtime return reminders @staticmethod def _gen_description(text): """Convert from Remind MSG to iCal description Opposite of _gen_msg() """ return text[text.rfind('%"') + 3:].replace('%_', '\n').replace('["["]', '[').strip() def _parse_remind_line(self, line, text): """Parse a line of remind output into a dict line -- the remind output text -- the original remind input """ event = {} line = line.split(None, 6) dat = [int(f) for f in line[0].split('/')] if line[4] != '*': start = divmod(int(line[4]), 60) event['dtstart'] = [datetime(dat[0], dat[1], dat[2], start[0], start[1], tzinfo=self._localtz)] if line[3] != '*': event['duration'] = timedelta(minutes=int(line[3])) else: event['dtstart'] = [date(dat[0], dat[1], dat[2])] msg = ' '.join(line[5:]) if line[4] == '*' else line[6] msg = msg.strip().replace('%_', '\n').replace('["["]', '[') if ' at ' in msg: (event['msg'], event['location']) = msg.rsplit(' at ', 1) else: event['msg'] = msg if '%"' in text: event['description'] = Remind._gen_description(text) tags = line[2].split(',') classes = ['PUBLIC', 'PRIVATE', 'CONFIDENTIAL'] for tag in tags[:-1]: if tag in classes: event['class'] = tag event['categories'] = [tag for tag in tags[:-1] if tag not in classes] event['uid'] = '%s@%s' % (tags[-1][7:], getfqdn()) return event @staticmethod def _interval(dates): """Return the distance between all dates and 0 if they are different""" interval = (dates[1] - dates[0]).days last = dates[0] for dat in dates[1:]: if (dat - last).days != interval: return 0 last = dat return interval @staticmethod def _gen_dtend_rrule(dtstarts, vevent): """Generate an rdate or rrule from a list of dates and add it to the vevent""" interval = Remind._interval(dtstarts) if interval > 0 and interval % 7 == 0: rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.WEEKLY, interval=interval // 7, count=len(dtstarts))) vevent.rruleset = rset elif interval > 1: rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.DAILY, interval=interval, count=len(dtstarts))) vevent.rruleset = rset elif interval > 0: if isinstance(dtstarts[0], datetime): rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.DAILY, count=len(dtstarts))) vevent.rruleset = rset else: vevent.add('dtend').value = dtstarts[-1] + timedelta(days=1) else: rset = rrule.rruleset() if isinstance(dtstarts[0], datetime): for dat in dtstarts: rset.rdate(dat) else: for dat in dtstarts: rset.rdate(datetime(dat.year, dat.month, dat.day)) # temporary set dtstart to a different date, so it's not # removed from rset by python-vobject works around bug in # Android: # https://github.com/rfc2822/davdroid/issues/340 vevent.dtstart.value = dtstarts[0] - timedelta(days=1) vevent.rruleset = rset vevent.dtstart.value = dtstarts[0] if not isinstance(dtstarts[0], datetime): vevent.add('dtend').value = dtstarts[0] + timedelta(days=1) def _gen_vevent(self, event, vevent): """Generate vevent from given event""" vevent.add('dtstart').value = event['dtstart'][0] vevent.add('dtstamp').value = datetime.fromtimestamp(self._mtime) vevent.add('summary').value = event['msg'] vevent.add('uid').value = event['uid'] if 'class' in event: vevent.add('class').value = event['class'] if 'categories' in event and len(event['categories']) > 0: vevent.add('categories').value = event['categories'] if 'location' in event: vevent.add('location').value = event['location'] if 'description' in event: vevent.add('description').value = event['description'] if isinstance(event['dtstart'][0], datetime): if self._alarm != timedelta(): valarm = vevent.add('valarm') valarm.add('trigger').value = self._alarm valarm.add('action').value = 'DISPLAY' valarm.add('description').value = event['msg'] if 'duration' in event: vevent.add('duration').value = event['duration'] else: vevent.add('dtend').value = event['dtstart'][0] elif len(event['dtstart']) == 1: vevent.add('dtend').value = event['dtstart'][0] + timedelta(days=1) if len(event['dtstart']) > 1: Remind._gen_dtend_rrule(event['dtstart'], vevent) def _update(self): """Reload Remind files if the mtime is newer""" update = not self._reminders with self._lock: for fname in self._reminders: if getmtime(fname) > self._mtime: update = True break if update: self._reminders = self._parse_remind(self._filename) def get_filesnames(self): """All filenames parsed by remind (including included files)""" self._update() return list(self._reminders.keys()) @staticmethod def _get_uid(line): """UID of a remind line""" return '%s@%s' % (md5(line[:-1].encode('utf-8')).hexdigest(), getfqdn()) def get_uids(self, filename=None): """UIDs of all reminders in the file excluding included files If a filename is specified, only it's UIDs are return, otherwise all. filename -- the remind file """ self._update() if filename: if filename not in self._reminders: return [] return self._reminders[filename].keys() return [uid for uids in self._reminders.values() for uid in uids] def to_vobject_etag(self, filename, uid): """Return iCal object and etag of one Remind entry filename -- the remind file uid -- the UID of the Remind line """ return self.to_vobjects(filename, [uid])[0][1:3] def to_vobjects(self, filename, uids=None): """Return iCal objects and etags of all Remind entries in uids filename -- the remind file uids -- the UIDs of the Remind lines (all if None) """ self._update() if not uids: uids = self._reminders[filename] items = [] for uid in uids: cal = iCalendar() self._gen_vevent(self._reminders[filename][uid], cal.add('vevent')) etag = md5() etag.update(self._reminders[filename][uid]['line'].encode("utf-8")) items.append((uid, cal, '"%s"' % etag.hexdigest())) return items def to_vobject(self, filename=None, uid=None): """Return iCal object of Remind lines If filename and UID are specified, the vObject only contains that event. If only a filename is specified, the vObject contains all events in the file. Otherwise the vObject contains all all objects of all files associated with the Remind object. filename -- the remind file uid -- the UID of the Remind line """ self._update() cal = iCalendar() if uid: self._gen_vevent(self._reminders[filename][uid], cal.add('vevent')) elif filename: for event in self._reminders[filename].values(): self._gen_vevent(event, cal.add('vevent')) else: for filename in self._reminders: for event in self._reminders[filename].values(): self._gen_vevent(event, cal.add('vevent')) return cal def stdin_to_vobject(self, lines): """Return iCal object of the Remind commands in lines""" cal = iCalendar() for event in self._parse_remind('-', lines)['-'].values(): self._gen_vevent(event, cal.add('vevent')) return cal @staticmethod def _parse_rdate(rdates): """Convert from iCal rdate to Remind trigdate syntax""" trigdates = [rdate.strftime("trigdate()=='%Y-%m-%d'") for rdate in rdates] return 'SATISFY [%s]' % '||'.join(trigdates) @staticmethod @staticmethod def _event_duration(vevent): """unify dtend and duration to the duration of the given vevent""" if hasattr(vevent, 'dtend'): return vevent.dtend.value - vevent.dtstart.value elif hasattr(vevent, 'duration') and vevent.duration.value: return vevent.duration.value return timedelta(0) @staticmethod def _gen_msg(vevent, label, tail, sep): """Generate a Remind MSG from the given vevent. Opposite of _gen_description() """ rem = ['MSG'] msg = [] if label: msg.append(label) if hasattr(vevent, 'summary') and vevent.summary.value: msg.append(Remind._rem_clean(vevent.summary.value)) else: msg.append('empty reminder') if hasattr(vevent, 'location') and vevent.location.value: msg.append('at %s' % Remind._rem_clean(vevent.location.value)) has_desc = hasattr(vevent, 'description') and vevent.description.value if tail or has_desc: rem.append('%%"%s%%"' % ' '.join(msg)) else: rem.append(' '.join(msg)) if tail: rem.append(tail) if has_desc: rem[-1] += sep + Remind._rem_clean(vevent.description.value) return ' '.join(rem) @staticmethod def _rem_clean(rem): """Strip, transform newlines, and escape '[' in string so it's acceptable as a remind entry.""" return rem.strip().replace('\n', '%_').replace('[', '["["]') @staticmethod def _abbr_tag(tag): """Transform a string so it's acceptable as a remind tag. """ return tag.replace(" ", "")[:48] def to_remind(self, vevent, label=None, priority=None, tags=None, tail=None, sep=" ", postdate=None, posttime=None): """Generate a Remind command from the given vevent""" remind = ['REM'] trigdates = None if hasattr(vevent, 'rrule'): trigdates = Remind._parse_rruleset(vevent.rruleset) dtstart = vevent.dtstart.value # If we don't get timezone information, handle it as a naive datetime. # See https://github.com/jspricke/python-remind/issues/2 for reference. if isinstance(dtstart, datetime) and dtstart.tzinfo: dtstart = dtstart.astimezone(self._localtz) dtend = None if hasattr(vevent, 'dtend'): dtend = vevent.dtend.value if isinstance(dtend, datetime) and dtend.tzinfo: dtend = dtend.astimezone(self._localtz) if not hasattr(vevent, 'rdate') and not isinstance(trigdates, str): remind.append(dtstart.strftime('%b %d %Y').replace(' 0', ' ')) if postdate: remind.append(postdate) if priority: remind.append('PRIORITY %s' % priority) if isinstance(trigdates, list): remind.extend(trigdates) duration = Remind._event_duration(vevent) if type(dtstart) is date and duration.days > 1: remind.append('*1') if dtend is not None: dtend -= timedelta(days=1) remind.append(dtend.strftime('UNTIL %b %d %Y').replace(' 0', ' ')) if isinstance(dtstart, datetime): remind.append(dtstart.strftime('AT %H:%M').replace(' 0', ' ')) if posttime: remind.append(posttime) if duration.total_seconds() > 0: remind.append('DURATION %d:%02d' % divmod(duration.total_seconds() / 60, 60)) if hasattr(vevent, 'rdate'): remind.append(Remind._parse_rdate(vevent.rdate.value)) elif isinstance(trigdates, str): remind.append(trigdates) if hasattr(vevent, 'class'): remind.append('TAG %s' % Remind._abbr_tag(vevent.getChildValue('class'))) if tags: remind.extend(['TAG %s' % Remind._abbr_tag(tag) for tag in tags]) if hasattr(vevent, 'categories_list'): for categories in vevent.categories_list: for category in categories.value: remind.append('TAG %s' % Remind._abbr_tag(category)) remind.append(Remind._gen_msg(vevent, label, tail, sep)) return ' '.join(remind) + '\n' def to_reminders(self, ical, label=None, priority=None, tags=None, tail=None, sep=" ", postdate=None, posttime=None): """Return Remind commands for all events of a iCalendar""" if not hasattr(ical, 'vevent_list'): return '' reminders = [self.to_remind(vevent, label, priority, tags, tail, sep, postdate, posttime) for vevent in ical.vevent_list] return ''.join(reminders) def append(self, ical, filename=None): """Append a Remind command generated from the iCalendar to the file""" return self.append_vobject(readOne(ical), filename) def append_vobject(self, ical, filename=None): """Append a Remind command generated from the iCalendar to the file""" if not filename: filename = self._filename elif filename not in self._reminders: return with self._lock: outdat = self.to_reminders(ical) open(filename, 'a').write(outdat) return Remind._get_uid(outdat) def remove(self, uid, filename=None): """Remove the Remind command with the uid from the file""" if not filename: filename = self._filename elif filename not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(filename).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): del rem[index] open(filename, 'w').writelines(rem) break def replace(self, uid, ical, filename=None): """Update the Remind command with the uid in the file with the new iCalendar""" return self.replace_vobject(uid, readOne(ical), filename) def replace_vobject(self, uid, ical, filename=None): """Update the Remind command with the uid in the file with the new iCalendar""" if not filename: filename = self._filename elif filename not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(filename).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): rem[index] = self.to_reminders(ical) new_uid = self._get_uid(rem[index]) open(filename, 'w').writelines(rem) return new_uid def move_vobject(self, uid, from_file, to_file): """Move the Remind command with the uid from from_file to to_file""" if from_file not in self._reminders or to_file not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(from_file).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): del rem[index] open(from_file, 'w').writelines(rem) open(to_file, 'a').write(line) break def get_meta(self): """Meta tags of the vObject collection""" return {'tag': 'VCALENDAR', 'C:supported-calendar-component-set': 'VEVENT'} def last_modified(self): """Last time the Remind files where parsed""" self._update() return self._mtime
jspricke/python-remind
remind.py
Remind._event_duration
python
def _event_duration(vevent): if hasattr(vevent, 'dtend'): return vevent.dtend.value - vevent.dtstart.value elif hasattr(vevent, 'duration') and vevent.duration.value: return vevent.duration.value return timedelta(0)
unify dtend and duration to the duration of the given vevent
train
https://github.com/jspricke/python-remind/blob/dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1/remind.py#L379-L385
null
class Remind(object): """Represents a collection of Remind files""" def __init__(self, filename=expanduser('~/.reminders'), localtz=None, startdate=date.today() - timedelta(weeks=12), month=15, alarm=timedelta(minutes=-10)): """Constructor filename -- the remind file (included files will be used as well) localtz -- the timezone of the remind file startdate -- the date to start parsing, will be passed to remind month -- how many month to parse, will be passed to remind -s """ self._localtz = localtz if localtz else get_localzone() self._filename = filename self._startdate = startdate self._month = month self._lock = Lock() self._reminders = {} self._mtime = 0 self._alarm = alarm self._update() def _parse_remind(self, filename, lines=''): """Calls remind and parses the output into a dict filename -- the remind file (included files will be used as well) lines -- used as stdin to remind (filename will be set to -) """ files = {} reminders = {} if lines: filename = '-' files[filename] = lines reminders[filename] = {} cmd = ['remind', '-l', '-s%d' % self._month, '-b1', '-y', '-r', filename, str(self._startdate)] try: rem = Popen(cmd, stdin=PIPE, stdout=PIPE).communicate(input=lines.encode('utf-8'))[0].decode('utf-8') except OSError: raise OSError('Error running: %s' % ' '.join(cmd)) rem = rem.splitlines() for (fileinfo, line) in zip(rem[::2], rem[1::2]): fileinfo = fileinfo.split() src_filename = fileinfo[3] if src_filename not in files: # There is a race condition with the remind call above here. # This could be solved by parsing the remind -de output, # but I don't see an easy way to do that. files[src_filename] = open(src_filename).readlines() reminders[src_filename] = {} mtime = getmtime(src_filename) if mtime > self._mtime: self._mtime = mtime text = files[src_filename][int(fileinfo[2]) - 1] event = self._parse_remind_line(line, text) if event['uid'] in reminders[src_filename]: reminders[src_filename][event['uid']]['dtstart'] += event['dtstart'] reminders[src_filename][event['uid']]['line'] += line else: reminders[src_filename][event['uid']] = event reminders[src_filename][event['uid']]['line'] = line # Find included files without reminders and add them to the file list for source in files.values(): for line in source: if line.startswith('include'): new_file = line.split(' ')[1].strip() if new_file not in reminders: reminders[new_file] = {} mtime = getmtime(new_file) if mtime > self._mtime: self._mtime = mtime return reminders @staticmethod def _gen_description(text): """Convert from Remind MSG to iCal description Opposite of _gen_msg() """ return text[text.rfind('%"') + 3:].replace('%_', '\n').replace('["["]', '[').strip() def _parse_remind_line(self, line, text): """Parse a line of remind output into a dict line -- the remind output text -- the original remind input """ event = {} line = line.split(None, 6) dat = [int(f) for f in line[0].split('/')] if line[4] != '*': start = divmod(int(line[4]), 60) event['dtstart'] = [datetime(dat[0], dat[1], dat[2], start[0], start[1], tzinfo=self._localtz)] if line[3] != '*': event['duration'] = timedelta(minutes=int(line[3])) else: event['dtstart'] = [date(dat[0], dat[1], dat[2])] msg = ' '.join(line[5:]) if line[4] == '*' else line[6] msg = msg.strip().replace('%_', '\n').replace('["["]', '[') if ' at ' in msg: (event['msg'], event['location']) = msg.rsplit(' at ', 1) else: event['msg'] = msg if '%"' in text: event['description'] = Remind._gen_description(text) tags = line[2].split(',') classes = ['PUBLIC', 'PRIVATE', 'CONFIDENTIAL'] for tag in tags[:-1]: if tag in classes: event['class'] = tag event['categories'] = [tag for tag in tags[:-1] if tag not in classes] event['uid'] = '%s@%s' % (tags[-1][7:], getfqdn()) return event @staticmethod def _interval(dates): """Return the distance between all dates and 0 if they are different""" interval = (dates[1] - dates[0]).days last = dates[0] for dat in dates[1:]: if (dat - last).days != interval: return 0 last = dat return interval @staticmethod def _gen_dtend_rrule(dtstarts, vevent): """Generate an rdate or rrule from a list of dates and add it to the vevent""" interval = Remind._interval(dtstarts) if interval > 0 and interval % 7 == 0: rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.WEEKLY, interval=interval // 7, count=len(dtstarts))) vevent.rruleset = rset elif interval > 1: rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.DAILY, interval=interval, count=len(dtstarts))) vevent.rruleset = rset elif interval > 0: if isinstance(dtstarts[0], datetime): rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.DAILY, count=len(dtstarts))) vevent.rruleset = rset else: vevent.add('dtend').value = dtstarts[-1] + timedelta(days=1) else: rset = rrule.rruleset() if isinstance(dtstarts[0], datetime): for dat in dtstarts: rset.rdate(dat) else: for dat in dtstarts: rset.rdate(datetime(dat.year, dat.month, dat.day)) # temporary set dtstart to a different date, so it's not # removed from rset by python-vobject works around bug in # Android: # https://github.com/rfc2822/davdroid/issues/340 vevent.dtstart.value = dtstarts[0] - timedelta(days=1) vevent.rruleset = rset vevent.dtstart.value = dtstarts[0] if not isinstance(dtstarts[0], datetime): vevent.add('dtend').value = dtstarts[0] + timedelta(days=1) def _gen_vevent(self, event, vevent): """Generate vevent from given event""" vevent.add('dtstart').value = event['dtstart'][0] vevent.add('dtstamp').value = datetime.fromtimestamp(self._mtime) vevent.add('summary').value = event['msg'] vevent.add('uid').value = event['uid'] if 'class' in event: vevent.add('class').value = event['class'] if 'categories' in event and len(event['categories']) > 0: vevent.add('categories').value = event['categories'] if 'location' in event: vevent.add('location').value = event['location'] if 'description' in event: vevent.add('description').value = event['description'] if isinstance(event['dtstart'][0], datetime): if self._alarm != timedelta(): valarm = vevent.add('valarm') valarm.add('trigger').value = self._alarm valarm.add('action').value = 'DISPLAY' valarm.add('description').value = event['msg'] if 'duration' in event: vevent.add('duration').value = event['duration'] else: vevent.add('dtend').value = event['dtstart'][0] elif len(event['dtstart']) == 1: vevent.add('dtend').value = event['dtstart'][0] + timedelta(days=1) if len(event['dtstart']) > 1: Remind._gen_dtend_rrule(event['dtstart'], vevent) def _update(self): """Reload Remind files if the mtime is newer""" update = not self._reminders with self._lock: for fname in self._reminders: if getmtime(fname) > self._mtime: update = True break if update: self._reminders = self._parse_remind(self._filename) def get_filesnames(self): """All filenames parsed by remind (including included files)""" self._update() return list(self._reminders.keys()) @staticmethod def _get_uid(line): """UID of a remind line""" return '%s@%s' % (md5(line[:-1].encode('utf-8')).hexdigest(), getfqdn()) def get_uids(self, filename=None): """UIDs of all reminders in the file excluding included files If a filename is specified, only it's UIDs are return, otherwise all. filename -- the remind file """ self._update() if filename: if filename not in self._reminders: return [] return self._reminders[filename].keys() return [uid for uids in self._reminders.values() for uid in uids] def to_vobject_etag(self, filename, uid): """Return iCal object and etag of one Remind entry filename -- the remind file uid -- the UID of the Remind line """ return self.to_vobjects(filename, [uid])[0][1:3] def to_vobjects(self, filename, uids=None): """Return iCal objects and etags of all Remind entries in uids filename -- the remind file uids -- the UIDs of the Remind lines (all if None) """ self._update() if not uids: uids = self._reminders[filename] items = [] for uid in uids: cal = iCalendar() self._gen_vevent(self._reminders[filename][uid], cal.add('vevent')) etag = md5() etag.update(self._reminders[filename][uid]['line'].encode("utf-8")) items.append((uid, cal, '"%s"' % etag.hexdigest())) return items def to_vobject(self, filename=None, uid=None): """Return iCal object of Remind lines If filename and UID are specified, the vObject only contains that event. If only a filename is specified, the vObject contains all events in the file. Otherwise the vObject contains all all objects of all files associated with the Remind object. filename -- the remind file uid -- the UID of the Remind line """ self._update() cal = iCalendar() if uid: self._gen_vevent(self._reminders[filename][uid], cal.add('vevent')) elif filename: for event in self._reminders[filename].values(): self._gen_vevent(event, cal.add('vevent')) else: for filename in self._reminders: for event in self._reminders[filename].values(): self._gen_vevent(event, cal.add('vevent')) return cal def stdin_to_vobject(self, lines): """Return iCal object of the Remind commands in lines""" cal = iCalendar() for event in self._parse_remind('-', lines)['-'].values(): self._gen_vevent(event, cal.add('vevent')) return cal @staticmethod def _parse_rdate(rdates): """Convert from iCal rdate to Remind trigdate syntax""" trigdates = [rdate.strftime("trigdate()=='%Y-%m-%d'") for rdate in rdates] return 'SATISFY [%s]' % '||'.join(trigdates) @staticmethod def _parse_rruleset(rruleset): """Convert from iCal rrule to Remind recurrence syntax""" # pylint: disable=protected-access if rruleset._rrule[0]._freq == 0: return [] rep = [] if rruleset._rrule[0]._byweekday and len(rruleset._rrule[0]._byweekday) > 1: rep.append('*1') elif rruleset._rrule[0]._freq == rrule.DAILY: rep.append('*%d' % rruleset._rrule[0]._interval) elif rruleset._rrule[0]._freq == rrule.WEEKLY: rep.append('*%d' % (7 * rruleset._rrule[0]._interval)) else: return Remind._parse_rdate(rruleset._rrule[0]) if rruleset._rrule[0]._byweekday and len(rruleset._rrule[0]._byweekday) > 1: daynums = set(range(7)) - set(rruleset._rrule[0]._byweekday) weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] days = [weekdays[day] for day in daynums] rep.append('SKIP OMIT %s' % ' '.join(days)) if rruleset._rrule[0]._until: rep.append(rruleset._rrule[0]._until.strftime('UNTIL %b %d %Y').replace(' 0', ' ')) elif rruleset._rrule[0]._count: rep.append(rruleset[-1].strftime('UNTIL %b %d %Y').replace(' 0', ' ')) return rep @staticmethod @staticmethod def _gen_msg(vevent, label, tail, sep): """Generate a Remind MSG from the given vevent. Opposite of _gen_description() """ rem = ['MSG'] msg = [] if label: msg.append(label) if hasattr(vevent, 'summary') and vevent.summary.value: msg.append(Remind._rem_clean(vevent.summary.value)) else: msg.append('empty reminder') if hasattr(vevent, 'location') and vevent.location.value: msg.append('at %s' % Remind._rem_clean(vevent.location.value)) has_desc = hasattr(vevent, 'description') and vevent.description.value if tail or has_desc: rem.append('%%"%s%%"' % ' '.join(msg)) else: rem.append(' '.join(msg)) if tail: rem.append(tail) if has_desc: rem[-1] += sep + Remind._rem_clean(vevent.description.value) return ' '.join(rem) @staticmethod def _rem_clean(rem): """Strip, transform newlines, and escape '[' in string so it's acceptable as a remind entry.""" return rem.strip().replace('\n', '%_').replace('[', '["["]') @staticmethod def _abbr_tag(tag): """Transform a string so it's acceptable as a remind tag. """ return tag.replace(" ", "")[:48] def to_remind(self, vevent, label=None, priority=None, tags=None, tail=None, sep=" ", postdate=None, posttime=None): """Generate a Remind command from the given vevent""" remind = ['REM'] trigdates = None if hasattr(vevent, 'rrule'): trigdates = Remind._parse_rruleset(vevent.rruleset) dtstart = vevent.dtstart.value # If we don't get timezone information, handle it as a naive datetime. # See https://github.com/jspricke/python-remind/issues/2 for reference. if isinstance(dtstart, datetime) and dtstart.tzinfo: dtstart = dtstart.astimezone(self._localtz) dtend = None if hasattr(vevent, 'dtend'): dtend = vevent.dtend.value if isinstance(dtend, datetime) and dtend.tzinfo: dtend = dtend.astimezone(self._localtz) if not hasattr(vevent, 'rdate') and not isinstance(trigdates, str): remind.append(dtstart.strftime('%b %d %Y').replace(' 0', ' ')) if postdate: remind.append(postdate) if priority: remind.append('PRIORITY %s' % priority) if isinstance(trigdates, list): remind.extend(trigdates) duration = Remind._event_duration(vevent) if type(dtstart) is date and duration.days > 1: remind.append('*1') if dtend is not None: dtend -= timedelta(days=1) remind.append(dtend.strftime('UNTIL %b %d %Y').replace(' 0', ' ')) if isinstance(dtstart, datetime): remind.append(dtstart.strftime('AT %H:%M').replace(' 0', ' ')) if posttime: remind.append(posttime) if duration.total_seconds() > 0: remind.append('DURATION %d:%02d' % divmod(duration.total_seconds() / 60, 60)) if hasattr(vevent, 'rdate'): remind.append(Remind._parse_rdate(vevent.rdate.value)) elif isinstance(trigdates, str): remind.append(trigdates) if hasattr(vevent, 'class'): remind.append('TAG %s' % Remind._abbr_tag(vevent.getChildValue('class'))) if tags: remind.extend(['TAG %s' % Remind._abbr_tag(tag) for tag in tags]) if hasattr(vevent, 'categories_list'): for categories in vevent.categories_list: for category in categories.value: remind.append('TAG %s' % Remind._abbr_tag(category)) remind.append(Remind._gen_msg(vevent, label, tail, sep)) return ' '.join(remind) + '\n' def to_reminders(self, ical, label=None, priority=None, tags=None, tail=None, sep=" ", postdate=None, posttime=None): """Return Remind commands for all events of a iCalendar""" if not hasattr(ical, 'vevent_list'): return '' reminders = [self.to_remind(vevent, label, priority, tags, tail, sep, postdate, posttime) for vevent in ical.vevent_list] return ''.join(reminders) def append(self, ical, filename=None): """Append a Remind command generated from the iCalendar to the file""" return self.append_vobject(readOne(ical), filename) def append_vobject(self, ical, filename=None): """Append a Remind command generated from the iCalendar to the file""" if not filename: filename = self._filename elif filename not in self._reminders: return with self._lock: outdat = self.to_reminders(ical) open(filename, 'a').write(outdat) return Remind._get_uid(outdat) def remove(self, uid, filename=None): """Remove the Remind command with the uid from the file""" if not filename: filename = self._filename elif filename not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(filename).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): del rem[index] open(filename, 'w').writelines(rem) break def replace(self, uid, ical, filename=None): """Update the Remind command with the uid in the file with the new iCalendar""" return self.replace_vobject(uid, readOne(ical), filename) def replace_vobject(self, uid, ical, filename=None): """Update the Remind command with the uid in the file with the new iCalendar""" if not filename: filename = self._filename elif filename not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(filename).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): rem[index] = self.to_reminders(ical) new_uid = self._get_uid(rem[index]) open(filename, 'w').writelines(rem) return new_uid def move_vobject(self, uid, from_file, to_file): """Move the Remind command with the uid from from_file to to_file""" if from_file not in self._reminders or to_file not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(from_file).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): del rem[index] open(from_file, 'w').writelines(rem) open(to_file, 'a').write(line) break def get_meta(self): """Meta tags of the vObject collection""" return {'tag': 'VCALENDAR', 'C:supported-calendar-component-set': 'VEVENT'} def last_modified(self): """Last time the Remind files where parsed""" self._update() return self._mtime
jspricke/python-remind
remind.py
Remind._gen_msg
python
def _gen_msg(vevent, label, tail, sep): rem = ['MSG'] msg = [] if label: msg.append(label) if hasattr(vevent, 'summary') and vevent.summary.value: msg.append(Remind._rem_clean(vevent.summary.value)) else: msg.append('empty reminder') if hasattr(vevent, 'location') and vevent.location.value: msg.append('at %s' % Remind._rem_clean(vevent.location.value)) has_desc = hasattr(vevent, 'description') and vevent.description.value if tail or has_desc: rem.append('%%"%s%%"' % ' '.join(msg)) else: rem.append(' '.join(msg)) if tail: rem.append(tail) if has_desc: rem[-1] += sep + Remind._rem_clean(vevent.description.value) return ' '.join(rem)
Generate a Remind MSG from the given vevent. Opposite of _gen_description()
train
https://github.com/jspricke/python-remind/blob/dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1/remind.py#L388-L418
[ "def _rem_clean(rem):\n \"\"\"Strip, transform newlines, and escape '[' in string so it's\n acceptable as a remind entry.\"\"\"\n return rem.strip().replace('\\n', '%_').replace('[', '[\"[\"]')\n" ]
class Remind(object): """Represents a collection of Remind files""" def __init__(self, filename=expanduser('~/.reminders'), localtz=None, startdate=date.today() - timedelta(weeks=12), month=15, alarm=timedelta(minutes=-10)): """Constructor filename -- the remind file (included files will be used as well) localtz -- the timezone of the remind file startdate -- the date to start parsing, will be passed to remind month -- how many month to parse, will be passed to remind -s """ self._localtz = localtz if localtz else get_localzone() self._filename = filename self._startdate = startdate self._month = month self._lock = Lock() self._reminders = {} self._mtime = 0 self._alarm = alarm self._update() def _parse_remind(self, filename, lines=''): """Calls remind and parses the output into a dict filename -- the remind file (included files will be used as well) lines -- used as stdin to remind (filename will be set to -) """ files = {} reminders = {} if lines: filename = '-' files[filename] = lines reminders[filename] = {} cmd = ['remind', '-l', '-s%d' % self._month, '-b1', '-y', '-r', filename, str(self._startdate)] try: rem = Popen(cmd, stdin=PIPE, stdout=PIPE).communicate(input=lines.encode('utf-8'))[0].decode('utf-8') except OSError: raise OSError('Error running: %s' % ' '.join(cmd)) rem = rem.splitlines() for (fileinfo, line) in zip(rem[::2], rem[1::2]): fileinfo = fileinfo.split() src_filename = fileinfo[3] if src_filename not in files: # There is a race condition with the remind call above here. # This could be solved by parsing the remind -de output, # but I don't see an easy way to do that. files[src_filename] = open(src_filename).readlines() reminders[src_filename] = {} mtime = getmtime(src_filename) if mtime > self._mtime: self._mtime = mtime text = files[src_filename][int(fileinfo[2]) - 1] event = self._parse_remind_line(line, text) if event['uid'] in reminders[src_filename]: reminders[src_filename][event['uid']]['dtstart'] += event['dtstart'] reminders[src_filename][event['uid']]['line'] += line else: reminders[src_filename][event['uid']] = event reminders[src_filename][event['uid']]['line'] = line # Find included files without reminders and add them to the file list for source in files.values(): for line in source: if line.startswith('include'): new_file = line.split(' ')[1].strip() if new_file not in reminders: reminders[new_file] = {} mtime = getmtime(new_file) if mtime > self._mtime: self._mtime = mtime return reminders @staticmethod def _gen_description(text): """Convert from Remind MSG to iCal description Opposite of _gen_msg() """ return text[text.rfind('%"') + 3:].replace('%_', '\n').replace('["["]', '[').strip() def _parse_remind_line(self, line, text): """Parse a line of remind output into a dict line -- the remind output text -- the original remind input """ event = {} line = line.split(None, 6) dat = [int(f) for f in line[0].split('/')] if line[4] != '*': start = divmod(int(line[4]), 60) event['dtstart'] = [datetime(dat[0], dat[1], dat[2], start[0], start[1], tzinfo=self._localtz)] if line[3] != '*': event['duration'] = timedelta(minutes=int(line[3])) else: event['dtstart'] = [date(dat[0], dat[1], dat[2])] msg = ' '.join(line[5:]) if line[4] == '*' else line[6] msg = msg.strip().replace('%_', '\n').replace('["["]', '[') if ' at ' in msg: (event['msg'], event['location']) = msg.rsplit(' at ', 1) else: event['msg'] = msg if '%"' in text: event['description'] = Remind._gen_description(text) tags = line[2].split(',') classes = ['PUBLIC', 'PRIVATE', 'CONFIDENTIAL'] for tag in tags[:-1]: if tag in classes: event['class'] = tag event['categories'] = [tag for tag in tags[:-1] if tag not in classes] event['uid'] = '%s@%s' % (tags[-1][7:], getfqdn()) return event @staticmethod def _interval(dates): """Return the distance between all dates and 0 if they are different""" interval = (dates[1] - dates[0]).days last = dates[0] for dat in dates[1:]: if (dat - last).days != interval: return 0 last = dat return interval @staticmethod def _gen_dtend_rrule(dtstarts, vevent): """Generate an rdate or rrule from a list of dates and add it to the vevent""" interval = Remind._interval(dtstarts) if interval > 0 and interval % 7 == 0: rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.WEEKLY, interval=interval // 7, count=len(dtstarts))) vevent.rruleset = rset elif interval > 1: rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.DAILY, interval=interval, count=len(dtstarts))) vevent.rruleset = rset elif interval > 0: if isinstance(dtstarts[0], datetime): rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.DAILY, count=len(dtstarts))) vevent.rruleset = rset else: vevent.add('dtend').value = dtstarts[-1] + timedelta(days=1) else: rset = rrule.rruleset() if isinstance(dtstarts[0], datetime): for dat in dtstarts: rset.rdate(dat) else: for dat in dtstarts: rset.rdate(datetime(dat.year, dat.month, dat.day)) # temporary set dtstart to a different date, so it's not # removed from rset by python-vobject works around bug in # Android: # https://github.com/rfc2822/davdroid/issues/340 vevent.dtstart.value = dtstarts[0] - timedelta(days=1) vevent.rruleset = rset vevent.dtstart.value = dtstarts[0] if not isinstance(dtstarts[0], datetime): vevent.add('dtend').value = dtstarts[0] + timedelta(days=1) def _gen_vevent(self, event, vevent): """Generate vevent from given event""" vevent.add('dtstart').value = event['dtstart'][0] vevent.add('dtstamp').value = datetime.fromtimestamp(self._mtime) vevent.add('summary').value = event['msg'] vevent.add('uid').value = event['uid'] if 'class' in event: vevent.add('class').value = event['class'] if 'categories' in event and len(event['categories']) > 0: vevent.add('categories').value = event['categories'] if 'location' in event: vevent.add('location').value = event['location'] if 'description' in event: vevent.add('description').value = event['description'] if isinstance(event['dtstart'][0], datetime): if self._alarm != timedelta(): valarm = vevent.add('valarm') valarm.add('trigger').value = self._alarm valarm.add('action').value = 'DISPLAY' valarm.add('description').value = event['msg'] if 'duration' in event: vevent.add('duration').value = event['duration'] else: vevent.add('dtend').value = event['dtstart'][0] elif len(event['dtstart']) == 1: vevent.add('dtend').value = event['dtstart'][0] + timedelta(days=1) if len(event['dtstart']) > 1: Remind._gen_dtend_rrule(event['dtstart'], vevent) def _update(self): """Reload Remind files if the mtime is newer""" update = not self._reminders with self._lock: for fname in self._reminders: if getmtime(fname) > self._mtime: update = True break if update: self._reminders = self._parse_remind(self._filename) def get_filesnames(self): """All filenames parsed by remind (including included files)""" self._update() return list(self._reminders.keys()) @staticmethod def _get_uid(line): """UID of a remind line""" return '%s@%s' % (md5(line[:-1].encode('utf-8')).hexdigest(), getfqdn()) def get_uids(self, filename=None): """UIDs of all reminders in the file excluding included files If a filename is specified, only it's UIDs are return, otherwise all. filename -- the remind file """ self._update() if filename: if filename not in self._reminders: return [] return self._reminders[filename].keys() return [uid for uids in self._reminders.values() for uid in uids] def to_vobject_etag(self, filename, uid): """Return iCal object and etag of one Remind entry filename -- the remind file uid -- the UID of the Remind line """ return self.to_vobjects(filename, [uid])[0][1:3] def to_vobjects(self, filename, uids=None): """Return iCal objects and etags of all Remind entries in uids filename -- the remind file uids -- the UIDs of the Remind lines (all if None) """ self._update() if not uids: uids = self._reminders[filename] items = [] for uid in uids: cal = iCalendar() self._gen_vevent(self._reminders[filename][uid], cal.add('vevent')) etag = md5() etag.update(self._reminders[filename][uid]['line'].encode("utf-8")) items.append((uid, cal, '"%s"' % etag.hexdigest())) return items def to_vobject(self, filename=None, uid=None): """Return iCal object of Remind lines If filename and UID are specified, the vObject only contains that event. If only a filename is specified, the vObject contains all events in the file. Otherwise the vObject contains all all objects of all files associated with the Remind object. filename -- the remind file uid -- the UID of the Remind line """ self._update() cal = iCalendar() if uid: self._gen_vevent(self._reminders[filename][uid], cal.add('vevent')) elif filename: for event in self._reminders[filename].values(): self._gen_vevent(event, cal.add('vevent')) else: for filename in self._reminders: for event in self._reminders[filename].values(): self._gen_vevent(event, cal.add('vevent')) return cal def stdin_to_vobject(self, lines): """Return iCal object of the Remind commands in lines""" cal = iCalendar() for event in self._parse_remind('-', lines)['-'].values(): self._gen_vevent(event, cal.add('vevent')) return cal @staticmethod def _parse_rdate(rdates): """Convert from iCal rdate to Remind trigdate syntax""" trigdates = [rdate.strftime("trigdate()=='%Y-%m-%d'") for rdate in rdates] return 'SATISFY [%s]' % '||'.join(trigdates) @staticmethod def _parse_rruleset(rruleset): """Convert from iCal rrule to Remind recurrence syntax""" # pylint: disable=protected-access if rruleset._rrule[0]._freq == 0: return [] rep = [] if rruleset._rrule[0]._byweekday and len(rruleset._rrule[0]._byweekday) > 1: rep.append('*1') elif rruleset._rrule[0]._freq == rrule.DAILY: rep.append('*%d' % rruleset._rrule[0]._interval) elif rruleset._rrule[0]._freq == rrule.WEEKLY: rep.append('*%d' % (7 * rruleset._rrule[0]._interval)) else: return Remind._parse_rdate(rruleset._rrule[0]) if rruleset._rrule[0]._byweekday and len(rruleset._rrule[0]._byweekday) > 1: daynums = set(range(7)) - set(rruleset._rrule[0]._byweekday) weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] days = [weekdays[day] for day in daynums] rep.append('SKIP OMIT %s' % ' '.join(days)) if rruleset._rrule[0]._until: rep.append(rruleset._rrule[0]._until.strftime('UNTIL %b %d %Y').replace(' 0', ' ')) elif rruleset._rrule[0]._count: rep.append(rruleset[-1].strftime('UNTIL %b %d %Y').replace(' 0', ' ')) return rep @staticmethod def _event_duration(vevent): """unify dtend and duration to the duration of the given vevent""" if hasattr(vevent, 'dtend'): return vevent.dtend.value - vevent.dtstart.value elif hasattr(vevent, 'duration') and vevent.duration.value: return vevent.duration.value return timedelta(0) @staticmethod @staticmethod def _rem_clean(rem): """Strip, transform newlines, and escape '[' in string so it's acceptable as a remind entry.""" return rem.strip().replace('\n', '%_').replace('[', '["["]') @staticmethod def _abbr_tag(tag): """Transform a string so it's acceptable as a remind tag. """ return tag.replace(" ", "")[:48] def to_remind(self, vevent, label=None, priority=None, tags=None, tail=None, sep=" ", postdate=None, posttime=None): """Generate a Remind command from the given vevent""" remind = ['REM'] trigdates = None if hasattr(vevent, 'rrule'): trigdates = Remind._parse_rruleset(vevent.rruleset) dtstart = vevent.dtstart.value # If we don't get timezone information, handle it as a naive datetime. # See https://github.com/jspricke/python-remind/issues/2 for reference. if isinstance(dtstart, datetime) and dtstart.tzinfo: dtstart = dtstart.astimezone(self._localtz) dtend = None if hasattr(vevent, 'dtend'): dtend = vevent.dtend.value if isinstance(dtend, datetime) and dtend.tzinfo: dtend = dtend.astimezone(self._localtz) if not hasattr(vevent, 'rdate') and not isinstance(trigdates, str): remind.append(dtstart.strftime('%b %d %Y').replace(' 0', ' ')) if postdate: remind.append(postdate) if priority: remind.append('PRIORITY %s' % priority) if isinstance(trigdates, list): remind.extend(trigdates) duration = Remind._event_duration(vevent) if type(dtstart) is date and duration.days > 1: remind.append('*1') if dtend is not None: dtend -= timedelta(days=1) remind.append(dtend.strftime('UNTIL %b %d %Y').replace(' 0', ' ')) if isinstance(dtstart, datetime): remind.append(dtstart.strftime('AT %H:%M').replace(' 0', ' ')) if posttime: remind.append(posttime) if duration.total_seconds() > 0: remind.append('DURATION %d:%02d' % divmod(duration.total_seconds() / 60, 60)) if hasattr(vevent, 'rdate'): remind.append(Remind._parse_rdate(vevent.rdate.value)) elif isinstance(trigdates, str): remind.append(trigdates) if hasattr(vevent, 'class'): remind.append('TAG %s' % Remind._abbr_tag(vevent.getChildValue('class'))) if tags: remind.extend(['TAG %s' % Remind._abbr_tag(tag) for tag in tags]) if hasattr(vevent, 'categories_list'): for categories in vevent.categories_list: for category in categories.value: remind.append('TAG %s' % Remind._abbr_tag(category)) remind.append(Remind._gen_msg(vevent, label, tail, sep)) return ' '.join(remind) + '\n' def to_reminders(self, ical, label=None, priority=None, tags=None, tail=None, sep=" ", postdate=None, posttime=None): """Return Remind commands for all events of a iCalendar""" if not hasattr(ical, 'vevent_list'): return '' reminders = [self.to_remind(vevent, label, priority, tags, tail, sep, postdate, posttime) for vevent in ical.vevent_list] return ''.join(reminders) def append(self, ical, filename=None): """Append a Remind command generated from the iCalendar to the file""" return self.append_vobject(readOne(ical), filename) def append_vobject(self, ical, filename=None): """Append a Remind command generated from the iCalendar to the file""" if not filename: filename = self._filename elif filename not in self._reminders: return with self._lock: outdat = self.to_reminders(ical) open(filename, 'a').write(outdat) return Remind._get_uid(outdat) def remove(self, uid, filename=None): """Remove the Remind command with the uid from the file""" if not filename: filename = self._filename elif filename not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(filename).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): del rem[index] open(filename, 'w').writelines(rem) break def replace(self, uid, ical, filename=None): """Update the Remind command with the uid in the file with the new iCalendar""" return self.replace_vobject(uid, readOne(ical), filename) def replace_vobject(self, uid, ical, filename=None): """Update the Remind command with the uid in the file with the new iCalendar""" if not filename: filename = self._filename elif filename not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(filename).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): rem[index] = self.to_reminders(ical) new_uid = self._get_uid(rem[index]) open(filename, 'w').writelines(rem) return new_uid def move_vobject(self, uid, from_file, to_file): """Move the Remind command with the uid from from_file to to_file""" if from_file not in self._reminders or to_file not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(from_file).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): del rem[index] open(from_file, 'w').writelines(rem) open(to_file, 'a').write(line) break def get_meta(self): """Meta tags of the vObject collection""" return {'tag': 'VCALENDAR', 'C:supported-calendar-component-set': 'VEVENT'} def last_modified(self): """Last time the Remind files where parsed""" self._update() return self._mtime
jspricke/python-remind
remind.py
Remind.to_remind
python
def to_remind(self, vevent, label=None, priority=None, tags=None, tail=None, sep=" ", postdate=None, posttime=None): remind = ['REM'] trigdates = None if hasattr(vevent, 'rrule'): trigdates = Remind._parse_rruleset(vevent.rruleset) dtstart = vevent.dtstart.value # If we don't get timezone information, handle it as a naive datetime. # See https://github.com/jspricke/python-remind/issues/2 for reference. if isinstance(dtstart, datetime) and dtstart.tzinfo: dtstart = dtstart.astimezone(self._localtz) dtend = None if hasattr(vevent, 'dtend'): dtend = vevent.dtend.value if isinstance(dtend, datetime) and dtend.tzinfo: dtend = dtend.astimezone(self._localtz) if not hasattr(vevent, 'rdate') and not isinstance(trigdates, str): remind.append(dtstart.strftime('%b %d %Y').replace(' 0', ' ')) if postdate: remind.append(postdate) if priority: remind.append('PRIORITY %s' % priority) if isinstance(trigdates, list): remind.extend(trigdates) duration = Remind._event_duration(vevent) if type(dtstart) is date and duration.days > 1: remind.append('*1') if dtend is not None: dtend -= timedelta(days=1) remind.append(dtend.strftime('UNTIL %b %d %Y').replace(' 0', ' ')) if isinstance(dtstart, datetime): remind.append(dtstart.strftime('AT %H:%M').replace(' 0', ' ')) if posttime: remind.append(posttime) if duration.total_seconds() > 0: remind.append('DURATION %d:%02d' % divmod(duration.total_seconds() / 60, 60)) if hasattr(vevent, 'rdate'): remind.append(Remind._parse_rdate(vevent.rdate.value)) elif isinstance(trigdates, str): remind.append(trigdates) if hasattr(vevent, 'class'): remind.append('TAG %s' % Remind._abbr_tag(vevent.getChildValue('class'))) if tags: remind.extend(['TAG %s' % Remind._abbr_tag(tag) for tag in tags]) if hasattr(vevent, 'categories_list'): for categories in vevent.categories_list: for category in categories.value: remind.append('TAG %s' % Remind._abbr_tag(category)) remind.append(Remind._gen_msg(vevent, label, tail, sep)) return ' '.join(remind) + '\n'
Generate a Remind command from the given vevent
train
https://github.com/jspricke/python-remind/blob/dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1/remind.py#L431-L499
[ "def _parse_rdate(rdates):\n \"\"\"Convert from iCal rdate to Remind trigdate syntax\"\"\"\n trigdates = [rdate.strftime(\"trigdate()=='%Y-%m-%d'\") for rdate in rdates]\n return 'SATISFY [%s]' % '||'.join(trigdates)\n", "def _parse_rruleset(rruleset):\n \"\"\"Convert from iCal rrule to Remind recurre...
class Remind(object): """Represents a collection of Remind files""" def __init__(self, filename=expanduser('~/.reminders'), localtz=None, startdate=date.today() - timedelta(weeks=12), month=15, alarm=timedelta(minutes=-10)): """Constructor filename -- the remind file (included files will be used as well) localtz -- the timezone of the remind file startdate -- the date to start parsing, will be passed to remind month -- how many month to parse, will be passed to remind -s """ self._localtz = localtz if localtz else get_localzone() self._filename = filename self._startdate = startdate self._month = month self._lock = Lock() self._reminders = {} self._mtime = 0 self._alarm = alarm self._update() def _parse_remind(self, filename, lines=''): """Calls remind and parses the output into a dict filename -- the remind file (included files will be used as well) lines -- used as stdin to remind (filename will be set to -) """ files = {} reminders = {} if lines: filename = '-' files[filename] = lines reminders[filename] = {} cmd = ['remind', '-l', '-s%d' % self._month, '-b1', '-y', '-r', filename, str(self._startdate)] try: rem = Popen(cmd, stdin=PIPE, stdout=PIPE).communicate(input=lines.encode('utf-8'))[0].decode('utf-8') except OSError: raise OSError('Error running: %s' % ' '.join(cmd)) rem = rem.splitlines() for (fileinfo, line) in zip(rem[::2], rem[1::2]): fileinfo = fileinfo.split() src_filename = fileinfo[3] if src_filename not in files: # There is a race condition with the remind call above here. # This could be solved by parsing the remind -de output, # but I don't see an easy way to do that. files[src_filename] = open(src_filename).readlines() reminders[src_filename] = {} mtime = getmtime(src_filename) if mtime > self._mtime: self._mtime = mtime text = files[src_filename][int(fileinfo[2]) - 1] event = self._parse_remind_line(line, text) if event['uid'] in reminders[src_filename]: reminders[src_filename][event['uid']]['dtstart'] += event['dtstart'] reminders[src_filename][event['uid']]['line'] += line else: reminders[src_filename][event['uid']] = event reminders[src_filename][event['uid']]['line'] = line # Find included files without reminders and add them to the file list for source in files.values(): for line in source: if line.startswith('include'): new_file = line.split(' ')[1].strip() if new_file not in reminders: reminders[new_file] = {} mtime = getmtime(new_file) if mtime > self._mtime: self._mtime = mtime return reminders @staticmethod def _gen_description(text): """Convert from Remind MSG to iCal description Opposite of _gen_msg() """ return text[text.rfind('%"') + 3:].replace('%_', '\n').replace('["["]', '[').strip() def _parse_remind_line(self, line, text): """Parse a line of remind output into a dict line -- the remind output text -- the original remind input """ event = {} line = line.split(None, 6) dat = [int(f) for f in line[0].split('/')] if line[4] != '*': start = divmod(int(line[4]), 60) event['dtstart'] = [datetime(dat[0], dat[1], dat[2], start[0], start[1], tzinfo=self._localtz)] if line[3] != '*': event['duration'] = timedelta(minutes=int(line[3])) else: event['dtstart'] = [date(dat[0], dat[1], dat[2])] msg = ' '.join(line[5:]) if line[4] == '*' else line[6] msg = msg.strip().replace('%_', '\n').replace('["["]', '[') if ' at ' in msg: (event['msg'], event['location']) = msg.rsplit(' at ', 1) else: event['msg'] = msg if '%"' in text: event['description'] = Remind._gen_description(text) tags = line[2].split(',') classes = ['PUBLIC', 'PRIVATE', 'CONFIDENTIAL'] for tag in tags[:-1]: if tag in classes: event['class'] = tag event['categories'] = [tag for tag in tags[:-1] if tag not in classes] event['uid'] = '%s@%s' % (tags[-1][7:], getfqdn()) return event @staticmethod def _interval(dates): """Return the distance between all dates and 0 if they are different""" interval = (dates[1] - dates[0]).days last = dates[0] for dat in dates[1:]: if (dat - last).days != interval: return 0 last = dat return interval @staticmethod def _gen_dtend_rrule(dtstarts, vevent): """Generate an rdate or rrule from a list of dates and add it to the vevent""" interval = Remind._interval(dtstarts) if interval > 0 and interval % 7 == 0: rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.WEEKLY, interval=interval // 7, count=len(dtstarts))) vevent.rruleset = rset elif interval > 1: rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.DAILY, interval=interval, count=len(dtstarts))) vevent.rruleset = rset elif interval > 0: if isinstance(dtstarts[0], datetime): rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.DAILY, count=len(dtstarts))) vevent.rruleset = rset else: vevent.add('dtend').value = dtstarts[-1] + timedelta(days=1) else: rset = rrule.rruleset() if isinstance(dtstarts[0], datetime): for dat in dtstarts: rset.rdate(dat) else: for dat in dtstarts: rset.rdate(datetime(dat.year, dat.month, dat.day)) # temporary set dtstart to a different date, so it's not # removed from rset by python-vobject works around bug in # Android: # https://github.com/rfc2822/davdroid/issues/340 vevent.dtstart.value = dtstarts[0] - timedelta(days=1) vevent.rruleset = rset vevent.dtstart.value = dtstarts[0] if not isinstance(dtstarts[0], datetime): vevent.add('dtend').value = dtstarts[0] + timedelta(days=1) def _gen_vevent(self, event, vevent): """Generate vevent from given event""" vevent.add('dtstart').value = event['dtstart'][0] vevent.add('dtstamp').value = datetime.fromtimestamp(self._mtime) vevent.add('summary').value = event['msg'] vevent.add('uid').value = event['uid'] if 'class' in event: vevent.add('class').value = event['class'] if 'categories' in event and len(event['categories']) > 0: vevent.add('categories').value = event['categories'] if 'location' in event: vevent.add('location').value = event['location'] if 'description' in event: vevent.add('description').value = event['description'] if isinstance(event['dtstart'][0], datetime): if self._alarm != timedelta(): valarm = vevent.add('valarm') valarm.add('trigger').value = self._alarm valarm.add('action').value = 'DISPLAY' valarm.add('description').value = event['msg'] if 'duration' in event: vevent.add('duration').value = event['duration'] else: vevent.add('dtend').value = event['dtstart'][0] elif len(event['dtstart']) == 1: vevent.add('dtend').value = event['dtstart'][0] + timedelta(days=1) if len(event['dtstart']) > 1: Remind._gen_dtend_rrule(event['dtstart'], vevent) def _update(self): """Reload Remind files if the mtime is newer""" update = not self._reminders with self._lock: for fname in self._reminders: if getmtime(fname) > self._mtime: update = True break if update: self._reminders = self._parse_remind(self._filename) def get_filesnames(self): """All filenames parsed by remind (including included files)""" self._update() return list(self._reminders.keys()) @staticmethod def _get_uid(line): """UID of a remind line""" return '%s@%s' % (md5(line[:-1].encode('utf-8')).hexdigest(), getfqdn()) def get_uids(self, filename=None): """UIDs of all reminders in the file excluding included files If a filename is specified, only it's UIDs are return, otherwise all. filename -- the remind file """ self._update() if filename: if filename not in self._reminders: return [] return self._reminders[filename].keys() return [uid for uids in self._reminders.values() for uid in uids] def to_vobject_etag(self, filename, uid): """Return iCal object and etag of one Remind entry filename -- the remind file uid -- the UID of the Remind line """ return self.to_vobjects(filename, [uid])[0][1:3] def to_vobjects(self, filename, uids=None): """Return iCal objects and etags of all Remind entries in uids filename -- the remind file uids -- the UIDs of the Remind lines (all if None) """ self._update() if not uids: uids = self._reminders[filename] items = [] for uid in uids: cal = iCalendar() self._gen_vevent(self._reminders[filename][uid], cal.add('vevent')) etag = md5() etag.update(self._reminders[filename][uid]['line'].encode("utf-8")) items.append((uid, cal, '"%s"' % etag.hexdigest())) return items def to_vobject(self, filename=None, uid=None): """Return iCal object of Remind lines If filename and UID are specified, the vObject only contains that event. If only a filename is specified, the vObject contains all events in the file. Otherwise the vObject contains all all objects of all files associated with the Remind object. filename -- the remind file uid -- the UID of the Remind line """ self._update() cal = iCalendar() if uid: self._gen_vevent(self._reminders[filename][uid], cal.add('vevent')) elif filename: for event in self._reminders[filename].values(): self._gen_vevent(event, cal.add('vevent')) else: for filename in self._reminders: for event in self._reminders[filename].values(): self._gen_vevent(event, cal.add('vevent')) return cal def stdin_to_vobject(self, lines): """Return iCal object of the Remind commands in lines""" cal = iCalendar() for event in self._parse_remind('-', lines)['-'].values(): self._gen_vevent(event, cal.add('vevent')) return cal @staticmethod def _parse_rdate(rdates): """Convert from iCal rdate to Remind trigdate syntax""" trigdates = [rdate.strftime("trigdate()=='%Y-%m-%d'") for rdate in rdates] return 'SATISFY [%s]' % '||'.join(trigdates) @staticmethod def _parse_rruleset(rruleset): """Convert from iCal rrule to Remind recurrence syntax""" # pylint: disable=protected-access if rruleset._rrule[0]._freq == 0: return [] rep = [] if rruleset._rrule[0]._byweekday and len(rruleset._rrule[0]._byweekday) > 1: rep.append('*1') elif rruleset._rrule[0]._freq == rrule.DAILY: rep.append('*%d' % rruleset._rrule[0]._interval) elif rruleset._rrule[0]._freq == rrule.WEEKLY: rep.append('*%d' % (7 * rruleset._rrule[0]._interval)) else: return Remind._parse_rdate(rruleset._rrule[0]) if rruleset._rrule[0]._byweekday and len(rruleset._rrule[0]._byweekday) > 1: daynums = set(range(7)) - set(rruleset._rrule[0]._byweekday) weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] days = [weekdays[day] for day in daynums] rep.append('SKIP OMIT %s' % ' '.join(days)) if rruleset._rrule[0]._until: rep.append(rruleset._rrule[0]._until.strftime('UNTIL %b %d %Y').replace(' 0', ' ')) elif rruleset._rrule[0]._count: rep.append(rruleset[-1].strftime('UNTIL %b %d %Y').replace(' 0', ' ')) return rep @staticmethod def _event_duration(vevent): """unify dtend and duration to the duration of the given vevent""" if hasattr(vevent, 'dtend'): return vevent.dtend.value - vevent.dtstart.value elif hasattr(vevent, 'duration') and vevent.duration.value: return vevent.duration.value return timedelta(0) @staticmethod def _gen_msg(vevent, label, tail, sep): """Generate a Remind MSG from the given vevent. Opposite of _gen_description() """ rem = ['MSG'] msg = [] if label: msg.append(label) if hasattr(vevent, 'summary') and vevent.summary.value: msg.append(Remind._rem_clean(vevent.summary.value)) else: msg.append('empty reminder') if hasattr(vevent, 'location') and vevent.location.value: msg.append('at %s' % Remind._rem_clean(vevent.location.value)) has_desc = hasattr(vevent, 'description') and vevent.description.value if tail or has_desc: rem.append('%%"%s%%"' % ' '.join(msg)) else: rem.append(' '.join(msg)) if tail: rem.append(tail) if has_desc: rem[-1] += sep + Remind._rem_clean(vevent.description.value) return ' '.join(rem) @staticmethod def _rem_clean(rem): """Strip, transform newlines, and escape '[' in string so it's acceptable as a remind entry.""" return rem.strip().replace('\n', '%_').replace('[', '["["]') @staticmethod def _abbr_tag(tag): """Transform a string so it's acceptable as a remind tag. """ return tag.replace(" ", "")[:48] def to_reminders(self, ical, label=None, priority=None, tags=None, tail=None, sep=" ", postdate=None, posttime=None): """Return Remind commands for all events of a iCalendar""" if not hasattr(ical, 'vevent_list'): return '' reminders = [self.to_remind(vevent, label, priority, tags, tail, sep, postdate, posttime) for vevent in ical.vevent_list] return ''.join(reminders) def append(self, ical, filename=None): """Append a Remind command generated from the iCalendar to the file""" return self.append_vobject(readOne(ical), filename) def append_vobject(self, ical, filename=None): """Append a Remind command generated from the iCalendar to the file""" if not filename: filename = self._filename elif filename not in self._reminders: return with self._lock: outdat = self.to_reminders(ical) open(filename, 'a').write(outdat) return Remind._get_uid(outdat) def remove(self, uid, filename=None): """Remove the Remind command with the uid from the file""" if not filename: filename = self._filename elif filename not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(filename).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): del rem[index] open(filename, 'w').writelines(rem) break def replace(self, uid, ical, filename=None): """Update the Remind command with the uid in the file with the new iCalendar""" return self.replace_vobject(uid, readOne(ical), filename) def replace_vobject(self, uid, ical, filename=None): """Update the Remind command with the uid in the file with the new iCalendar""" if not filename: filename = self._filename elif filename not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(filename).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): rem[index] = self.to_reminders(ical) new_uid = self._get_uid(rem[index]) open(filename, 'w').writelines(rem) return new_uid def move_vobject(self, uid, from_file, to_file): """Move the Remind command with the uid from from_file to to_file""" if from_file not in self._reminders or to_file not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(from_file).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): del rem[index] open(from_file, 'w').writelines(rem) open(to_file, 'a').write(line) break def get_meta(self): """Meta tags of the vObject collection""" return {'tag': 'VCALENDAR', 'C:supported-calendar-component-set': 'VEVENT'} def last_modified(self): """Last time the Remind files where parsed""" self._update() return self._mtime
jspricke/python-remind
remind.py
Remind.to_reminders
python
def to_reminders(self, ical, label=None, priority=None, tags=None, tail=None, sep=" ", postdate=None, posttime=None): if not hasattr(ical, 'vevent_list'): return '' reminders = [self.to_remind(vevent, label, priority, tags, tail, sep, postdate, posttime) for vevent in ical.vevent_list] return ''.join(reminders)
Return Remind commands for all events of a iCalendar
train
https://github.com/jspricke/python-remind/blob/dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1/remind.py#L501-L510
null
class Remind(object): """Represents a collection of Remind files""" def __init__(self, filename=expanduser('~/.reminders'), localtz=None, startdate=date.today() - timedelta(weeks=12), month=15, alarm=timedelta(minutes=-10)): """Constructor filename -- the remind file (included files will be used as well) localtz -- the timezone of the remind file startdate -- the date to start parsing, will be passed to remind month -- how many month to parse, will be passed to remind -s """ self._localtz = localtz if localtz else get_localzone() self._filename = filename self._startdate = startdate self._month = month self._lock = Lock() self._reminders = {} self._mtime = 0 self._alarm = alarm self._update() def _parse_remind(self, filename, lines=''): """Calls remind and parses the output into a dict filename -- the remind file (included files will be used as well) lines -- used as stdin to remind (filename will be set to -) """ files = {} reminders = {} if lines: filename = '-' files[filename] = lines reminders[filename] = {} cmd = ['remind', '-l', '-s%d' % self._month, '-b1', '-y', '-r', filename, str(self._startdate)] try: rem = Popen(cmd, stdin=PIPE, stdout=PIPE).communicate(input=lines.encode('utf-8'))[0].decode('utf-8') except OSError: raise OSError('Error running: %s' % ' '.join(cmd)) rem = rem.splitlines() for (fileinfo, line) in zip(rem[::2], rem[1::2]): fileinfo = fileinfo.split() src_filename = fileinfo[3] if src_filename not in files: # There is a race condition with the remind call above here. # This could be solved by parsing the remind -de output, # but I don't see an easy way to do that. files[src_filename] = open(src_filename).readlines() reminders[src_filename] = {} mtime = getmtime(src_filename) if mtime > self._mtime: self._mtime = mtime text = files[src_filename][int(fileinfo[2]) - 1] event = self._parse_remind_line(line, text) if event['uid'] in reminders[src_filename]: reminders[src_filename][event['uid']]['dtstart'] += event['dtstart'] reminders[src_filename][event['uid']]['line'] += line else: reminders[src_filename][event['uid']] = event reminders[src_filename][event['uid']]['line'] = line # Find included files without reminders and add them to the file list for source in files.values(): for line in source: if line.startswith('include'): new_file = line.split(' ')[1].strip() if new_file not in reminders: reminders[new_file] = {} mtime = getmtime(new_file) if mtime > self._mtime: self._mtime = mtime return reminders @staticmethod def _gen_description(text): """Convert from Remind MSG to iCal description Opposite of _gen_msg() """ return text[text.rfind('%"') + 3:].replace('%_', '\n').replace('["["]', '[').strip() def _parse_remind_line(self, line, text): """Parse a line of remind output into a dict line -- the remind output text -- the original remind input """ event = {} line = line.split(None, 6) dat = [int(f) for f in line[0].split('/')] if line[4] != '*': start = divmod(int(line[4]), 60) event['dtstart'] = [datetime(dat[0], dat[1], dat[2], start[0], start[1], tzinfo=self._localtz)] if line[3] != '*': event['duration'] = timedelta(minutes=int(line[3])) else: event['dtstart'] = [date(dat[0], dat[1], dat[2])] msg = ' '.join(line[5:]) if line[4] == '*' else line[6] msg = msg.strip().replace('%_', '\n').replace('["["]', '[') if ' at ' in msg: (event['msg'], event['location']) = msg.rsplit(' at ', 1) else: event['msg'] = msg if '%"' in text: event['description'] = Remind._gen_description(text) tags = line[2].split(',') classes = ['PUBLIC', 'PRIVATE', 'CONFIDENTIAL'] for tag in tags[:-1]: if tag in classes: event['class'] = tag event['categories'] = [tag for tag in tags[:-1] if tag not in classes] event['uid'] = '%s@%s' % (tags[-1][7:], getfqdn()) return event @staticmethod def _interval(dates): """Return the distance between all dates and 0 if they are different""" interval = (dates[1] - dates[0]).days last = dates[0] for dat in dates[1:]: if (dat - last).days != interval: return 0 last = dat return interval @staticmethod def _gen_dtend_rrule(dtstarts, vevent): """Generate an rdate or rrule from a list of dates and add it to the vevent""" interval = Remind._interval(dtstarts) if interval > 0 and interval % 7 == 0: rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.WEEKLY, interval=interval // 7, count=len(dtstarts))) vevent.rruleset = rset elif interval > 1: rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.DAILY, interval=interval, count=len(dtstarts))) vevent.rruleset = rset elif interval > 0: if isinstance(dtstarts[0], datetime): rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.DAILY, count=len(dtstarts))) vevent.rruleset = rset else: vevent.add('dtend').value = dtstarts[-1] + timedelta(days=1) else: rset = rrule.rruleset() if isinstance(dtstarts[0], datetime): for dat in dtstarts: rset.rdate(dat) else: for dat in dtstarts: rset.rdate(datetime(dat.year, dat.month, dat.day)) # temporary set dtstart to a different date, so it's not # removed from rset by python-vobject works around bug in # Android: # https://github.com/rfc2822/davdroid/issues/340 vevent.dtstart.value = dtstarts[0] - timedelta(days=1) vevent.rruleset = rset vevent.dtstart.value = dtstarts[0] if not isinstance(dtstarts[0], datetime): vevent.add('dtend').value = dtstarts[0] + timedelta(days=1) def _gen_vevent(self, event, vevent): """Generate vevent from given event""" vevent.add('dtstart').value = event['dtstart'][0] vevent.add('dtstamp').value = datetime.fromtimestamp(self._mtime) vevent.add('summary').value = event['msg'] vevent.add('uid').value = event['uid'] if 'class' in event: vevent.add('class').value = event['class'] if 'categories' in event and len(event['categories']) > 0: vevent.add('categories').value = event['categories'] if 'location' in event: vevent.add('location').value = event['location'] if 'description' in event: vevent.add('description').value = event['description'] if isinstance(event['dtstart'][0], datetime): if self._alarm != timedelta(): valarm = vevent.add('valarm') valarm.add('trigger').value = self._alarm valarm.add('action').value = 'DISPLAY' valarm.add('description').value = event['msg'] if 'duration' in event: vevent.add('duration').value = event['duration'] else: vevent.add('dtend').value = event['dtstart'][0] elif len(event['dtstart']) == 1: vevent.add('dtend').value = event['dtstart'][0] + timedelta(days=1) if len(event['dtstart']) > 1: Remind._gen_dtend_rrule(event['dtstart'], vevent) def _update(self): """Reload Remind files if the mtime is newer""" update = not self._reminders with self._lock: for fname in self._reminders: if getmtime(fname) > self._mtime: update = True break if update: self._reminders = self._parse_remind(self._filename) def get_filesnames(self): """All filenames parsed by remind (including included files)""" self._update() return list(self._reminders.keys()) @staticmethod def _get_uid(line): """UID of a remind line""" return '%s@%s' % (md5(line[:-1].encode('utf-8')).hexdigest(), getfqdn()) def get_uids(self, filename=None): """UIDs of all reminders in the file excluding included files If a filename is specified, only it's UIDs are return, otherwise all. filename -- the remind file """ self._update() if filename: if filename not in self._reminders: return [] return self._reminders[filename].keys() return [uid for uids in self._reminders.values() for uid in uids] def to_vobject_etag(self, filename, uid): """Return iCal object and etag of one Remind entry filename -- the remind file uid -- the UID of the Remind line """ return self.to_vobjects(filename, [uid])[0][1:3] def to_vobjects(self, filename, uids=None): """Return iCal objects and etags of all Remind entries in uids filename -- the remind file uids -- the UIDs of the Remind lines (all if None) """ self._update() if not uids: uids = self._reminders[filename] items = [] for uid in uids: cal = iCalendar() self._gen_vevent(self._reminders[filename][uid], cal.add('vevent')) etag = md5() etag.update(self._reminders[filename][uid]['line'].encode("utf-8")) items.append((uid, cal, '"%s"' % etag.hexdigest())) return items def to_vobject(self, filename=None, uid=None): """Return iCal object of Remind lines If filename and UID are specified, the vObject only contains that event. If only a filename is specified, the vObject contains all events in the file. Otherwise the vObject contains all all objects of all files associated with the Remind object. filename -- the remind file uid -- the UID of the Remind line """ self._update() cal = iCalendar() if uid: self._gen_vevent(self._reminders[filename][uid], cal.add('vevent')) elif filename: for event in self._reminders[filename].values(): self._gen_vevent(event, cal.add('vevent')) else: for filename in self._reminders: for event in self._reminders[filename].values(): self._gen_vevent(event, cal.add('vevent')) return cal def stdin_to_vobject(self, lines): """Return iCal object of the Remind commands in lines""" cal = iCalendar() for event in self._parse_remind('-', lines)['-'].values(): self._gen_vevent(event, cal.add('vevent')) return cal @staticmethod def _parse_rdate(rdates): """Convert from iCal rdate to Remind trigdate syntax""" trigdates = [rdate.strftime("trigdate()=='%Y-%m-%d'") for rdate in rdates] return 'SATISFY [%s]' % '||'.join(trigdates) @staticmethod def _parse_rruleset(rruleset): """Convert from iCal rrule to Remind recurrence syntax""" # pylint: disable=protected-access if rruleset._rrule[0]._freq == 0: return [] rep = [] if rruleset._rrule[0]._byweekday and len(rruleset._rrule[0]._byweekday) > 1: rep.append('*1') elif rruleset._rrule[0]._freq == rrule.DAILY: rep.append('*%d' % rruleset._rrule[0]._interval) elif rruleset._rrule[0]._freq == rrule.WEEKLY: rep.append('*%d' % (7 * rruleset._rrule[0]._interval)) else: return Remind._parse_rdate(rruleset._rrule[0]) if rruleset._rrule[0]._byweekday and len(rruleset._rrule[0]._byweekday) > 1: daynums = set(range(7)) - set(rruleset._rrule[0]._byweekday) weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] days = [weekdays[day] for day in daynums] rep.append('SKIP OMIT %s' % ' '.join(days)) if rruleset._rrule[0]._until: rep.append(rruleset._rrule[0]._until.strftime('UNTIL %b %d %Y').replace(' 0', ' ')) elif rruleset._rrule[0]._count: rep.append(rruleset[-1].strftime('UNTIL %b %d %Y').replace(' 0', ' ')) return rep @staticmethod def _event_duration(vevent): """unify dtend and duration to the duration of the given vevent""" if hasattr(vevent, 'dtend'): return vevent.dtend.value - vevent.dtstart.value elif hasattr(vevent, 'duration') and vevent.duration.value: return vevent.duration.value return timedelta(0) @staticmethod def _gen_msg(vevent, label, tail, sep): """Generate a Remind MSG from the given vevent. Opposite of _gen_description() """ rem = ['MSG'] msg = [] if label: msg.append(label) if hasattr(vevent, 'summary') and vevent.summary.value: msg.append(Remind._rem_clean(vevent.summary.value)) else: msg.append('empty reminder') if hasattr(vevent, 'location') and vevent.location.value: msg.append('at %s' % Remind._rem_clean(vevent.location.value)) has_desc = hasattr(vevent, 'description') and vevent.description.value if tail or has_desc: rem.append('%%"%s%%"' % ' '.join(msg)) else: rem.append(' '.join(msg)) if tail: rem.append(tail) if has_desc: rem[-1] += sep + Remind._rem_clean(vevent.description.value) return ' '.join(rem) @staticmethod def _rem_clean(rem): """Strip, transform newlines, and escape '[' in string so it's acceptable as a remind entry.""" return rem.strip().replace('\n', '%_').replace('[', '["["]') @staticmethod def _abbr_tag(tag): """Transform a string so it's acceptable as a remind tag. """ return tag.replace(" ", "")[:48] def to_remind(self, vevent, label=None, priority=None, tags=None, tail=None, sep=" ", postdate=None, posttime=None): """Generate a Remind command from the given vevent""" remind = ['REM'] trigdates = None if hasattr(vevent, 'rrule'): trigdates = Remind._parse_rruleset(vevent.rruleset) dtstart = vevent.dtstart.value # If we don't get timezone information, handle it as a naive datetime. # See https://github.com/jspricke/python-remind/issues/2 for reference. if isinstance(dtstart, datetime) and dtstart.tzinfo: dtstart = dtstart.astimezone(self._localtz) dtend = None if hasattr(vevent, 'dtend'): dtend = vevent.dtend.value if isinstance(dtend, datetime) and dtend.tzinfo: dtend = dtend.astimezone(self._localtz) if not hasattr(vevent, 'rdate') and not isinstance(trigdates, str): remind.append(dtstart.strftime('%b %d %Y').replace(' 0', ' ')) if postdate: remind.append(postdate) if priority: remind.append('PRIORITY %s' % priority) if isinstance(trigdates, list): remind.extend(trigdates) duration = Remind._event_duration(vevent) if type(dtstart) is date and duration.days > 1: remind.append('*1') if dtend is not None: dtend -= timedelta(days=1) remind.append(dtend.strftime('UNTIL %b %d %Y').replace(' 0', ' ')) if isinstance(dtstart, datetime): remind.append(dtstart.strftime('AT %H:%M').replace(' 0', ' ')) if posttime: remind.append(posttime) if duration.total_seconds() > 0: remind.append('DURATION %d:%02d' % divmod(duration.total_seconds() / 60, 60)) if hasattr(vevent, 'rdate'): remind.append(Remind._parse_rdate(vevent.rdate.value)) elif isinstance(trigdates, str): remind.append(trigdates) if hasattr(vevent, 'class'): remind.append('TAG %s' % Remind._abbr_tag(vevent.getChildValue('class'))) if tags: remind.extend(['TAG %s' % Remind._abbr_tag(tag) for tag in tags]) if hasattr(vevent, 'categories_list'): for categories in vevent.categories_list: for category in categories.value: remind.append('TAG %s' % Remind._abbr_tag(category)) remind.append(Remind._gen_msg(vevent, label, tail, sep)) return ' '.join(remind) + '\n' def append(self, ical, filename=None): """Append a Remind command generated from the iCalendar to the file""" return self.append_vobject(readOne(ical), filename) def append_vobject(self, ical, filename=None): """Append a Remind command generated from the iCalendar to the file""" if not filename: filename = self._filename elif filename not in self._reminders: return with self._lock: outdat = self.to_reminders(ical) open(filename, 'a').write(outdat) return Remind._get_uid(outdat) def remove(self, uid, filename=None): """Remove the Remind command with the uid from the file""" if not filename: filename = self._filename elif filename not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(filename).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): del rem[index] open(filename, 'w').writelines(rem) break def replace(self, uid, ical, filename=None): """Update the Remind command with the uid in the file with the new iCalendar""" return self.replace_vobject(uid, readOne(ical), filename) def replace_vobject(self, uid, ical, filename=None): """Update the Remind command with the uid in the file with the new iCalendar""" if not filename: filename = self._filename elif filename not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(filename).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): rem[index] = self.to_reminders(ical) new_uid = self._get_uid(rem[index]) open(filename, 'w').writelines(rem) return new_uid def move_vobject(self, uid, from_file, to_file): """Move the Remind command with the uid from from_file to to_file""" if from_file not in self._reminders or to_file not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(from_file).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): del rem[index] open(from_file, 'w').writelines(rem) open(to_file, 'a').write(line) break def get_meta(self): """Meta tags of the vObject collection""" return {'tag': 'VCALENDAR', 'C:supported-calendar-component-set': 'VEVENT'} def last_modified(self): """Last time the Remind files where parsed""" self._update() return self._mtime
jspricke/python-remind
remind.py
Remind.append_vobject
python
def append_vobject(self, ical, filename=None): if not filename: filename = self._filename elif filename not in self._reminders: return with self._lock: outdat = self.to_reminders(ical) open(filename, 'a').write(outdat) return Remind._get_uid(outdat)
Append a Remind command generated from the iCalendar to the file
train
https://github.com/jspricke/python-remind/blob/dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1/remind.py#L516-L527
[ "def _get_uid(line):\n \"\"\"UID of a remind line\"\"\"\n return '%s@%s' % (md5(line[:-1].encode('utf-8')).hexdigest(), getfqdn())\n", "def to_reminders(self, ical, label=None, priority=None, tags=None,\n tail=None, sep=\" \", postdate=None, posttime=None):\n \"\"\"Return Remind commands ...
class Remind(object): """Represents a collection of Remind files""" def __init__(self, filename=expanduser('~/.reminders'), localtz=None, startdate=date.today() - timedelta(weeks=12), month=15, alarm=timedelta(minutes=-10)): """Constructor filename -- the remind file (included files will be used as well) localtz -- the timezone of the remind file startdate -- the date to start parsing, will be passed to remind month -- how many month to parse, will be passed to remind -s """ self._localtz = localtz if localtz else get_localzone() self._filename = filename self._startdate = startdate self._month = month self._lock = Lock() self._reminders = {} self._mtime = 0 self._alarm = alarm self._update() def _parse_remind(self, filename, lines=''): """Calls remind and parses the output into a dict filename -- the remind file (included files will be used as well) lines -- used as stdin to remind (filename will be set to -) """ files = {} reminders = {} if lines: filename = '-' files[filename] = lines reminders[filename] = {} cmd = ['remind', '-l', '-s%d' % self._month, '-b1', '-y', '-r', filename, str(self._startdate)] try: rem = Popen(cmd, stdin=PIPE, stdout=PIPE).communicate(input=lines.encode('utf-8'))[0].decode('utf-8') except OSError: raise OSError('Error running: %s' % ' '.join(cmd)) rem = rem.splitlines() for (fileinfo, line) in zip(rem[::2], rem[1::2]): fileinfo = fileinfo.split() src_filename = fileinfo[3] if src_filename not in files: # There is a race condition with the remind call above here. # This could be solved by parsing the remind -de output, # but I don't see an easy way to do that. files[src_filename] = open(src_filename).readlines() reminders[src_filename] = {} mtime = getmtime(src_filename) if mtime > self._mtime: self._mtime = mtime text = files[src_filename][int(fileinfo[2]) - 1] event = self._parse_remind_line(line, text) if event['uid'] in reminders[src_filename]: reminders[src_filename][event['uid']]['dtstart'] += event['dtstart'] reminders[src_filename][event['uid']]['line'] += line else: reminders[src_filename][event['uid']] = event reminders[src_filename][event['uid']]['line'] = line # Find included files without reminders and add them to the file list for source in files.values(): for line in source: if line.startswith('include'): new_file = line.split(' ')[1].strip() if new_file not in reminders: reminders[new_file] = {} mtime = getmtime(new_file) if mtime > self._mtime: self._mtime = mtime return reminders @staticmethod def _gen_description(text): """Convert from Remind MSG to iCal description Opposite of _gen_msg() """ return text[text.rfind('%"') + 3:].replace('%_', '\n').replace('["["]', '[').strip() def _parse_remind_line(self, line, text): """Parse a line of remind output into a dict line -- the remind output text -- the original remind input """ event = {} line = line.split(None, 6) dat = [int(f) for f in line[0].split('/')] if line[4] != '*': start = divmod(int(line[4]), 60) event['dtstart'] = [datetime(dat[0], dat[1], dat[2], start[0], start[1], tzinfo=self._localtz)] if line[3] != '*': event['duration'] = timedelta(minutes=int(line[3])) else: event['dtstart'] = [date(dat[0], dat[1], dat[2])] msg = ' '.join(line[5:]) if line[4] == '*' else line[6] msg = msg.strip().replace('%_', '\n').replace('["["]', '[') if ' at ' in msg: (event['msg'], event['location']) = msg.rsplit(' at ', 1) else: event['msg'] = msg if '%"' in text: event['description'] = Remind._gen_description(text) tags = line[2].split(',') classes = ['PUBLIC', 'PRIVATE', 'CONFIDENTIAL'] for tag in tags[:-1]: if tag in classes: event['class'] = tag event['categories'] = [tag for tag in tags[:-1] if tag not in classes] event['uid'] = '%s@%s' % (tags[-1][7:], getfqdn()) return event @staticmethod def _interval(dates): """Return the distance between all dates and 0 if they are different""" interval = (dates[1] - dates[0]).days last = dates[0] for dat in dates[1:]: if (dat - last).days != interval: return 0 last = dat return interval @staticmethod def _gen_dtend_rrule(dtstarts, vevent): """Generate an rdate or rrule from a list of dates and add it to the vevent""" interval = Remind._interval(dtstarts) if interval > 0 and interval % 7 == 0: rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.WEEKLY, interval=interval // 7, count=len(dtstarts))) vevent.rruleset = rset elif interval > 1: rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.DAILY, interval=interval, count=len(dtstarts))) vevent.rruleset = rset elif interval > 0: if isinstance(dtstarts[0], datetime): rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.DAILY, count=len(dtstarts))) vevent.rruleset = rset else: vevent.add('dtend').value = dtstarts[-1] + timedelta(days=1) else: rset = rrule.rruleset() if isinstance(dtstarts[0], datetime): for dat in dtstarts: rset.rdate(dat) else: for dat in dtstarts: rset.rdate(datetime(dat.year, dat.month, dat.day)) # temporary set dtstart to a different date, so it's not # removed from rset by python-vobject works around bug in # Android: # https://github.com/rfc2822/davdroid/issues/340 vevent.dtstart.value = dtstarts[0] - timedelta(days=1) vevent.rruleset = rset vevent.dtstart.value = dtstarts[0] if not isinstance(dtstarts[0], datetime): vevent.add('dtend').value = dtstarts[0] + timedelta(days=1) def _gen_vevent(self, event, vevent): """Generate vevent from given event""" vevent.add('dtstart').value = event['dtstart'][0] vevent.add('dtstamp').value = datetime.fromtimestamp(self._mtime) vevent.add('summary').value = event['msg'] vevent.add('uid').value = event['uid'] if 'class' in event: vevent.add('class').value = event['class'] if 'categories' in event and len(event['categories']) > 0: vevent.add('categories').value = event['categories'] if 'location' in event: vevent.add('location').value = event['location'] if 'description' in event: vevent.add('description').value = event['description'] if isinstance(event['dtstart'][0], datetime): if self._alarm != timedelta(): valarm = vevent.add('valarm') valarm.add('trigger').value = self._alarm valarm.add('action').value = 'DISPLAY' valarm.add('description').value = event['msg'] if 'duration' in event: vevent.add('duration').value = event['duration'] else: vevent.add('dtend').value = event['dtstart'][0] elif len(event['dtstart']) == 1: vevent.add('dtend').value = event['dtstart'][0] + timedelta(days=1) if len(event['dtstart']) > 1: Remind._gen_dtend_rrule(event['dtstart'], vevent) def _update(self): """Reload Remind files if the mtime is newer""" update = not self._reminders with self._lock: for fname in self._reminders: if getmtime(fname) > self._mtime: update = True break if update: self._reminders = self._parse_remind(self._filename) def get_filesnames(self): """All filenames parsed by remind (including included files)""" self._update() return list(self._reminders.keys()) @staticmethod def _get_uid(line): """UID of a remind line""" return '%s@%s' % (md5(line[:-1].encode('utf-8')).hexdigest(), getfqdn()) def get_uids(self, filename=None): """UIDs of all reminders in the file excluding included files If a filename is specified, only it's UIDs are return, otherwise all. filename -- the remind file """ self._update() if filename: if filename not in self._reminders: return [] return self._reminders[filename].keys() return [uid for uids in self._reminders.values() for uid in uids] def to_vobject_etag(self, filename, uid): """Return iCal object and etag of one Remind entry filename -- the remind file uid -- the UID of the Remind line """ return self.to_vobjects(filename, [uid])[0][1:3] def to_vobjects(self, filename, uids=None): """Return iCal objects and etags of all Remind entries in uids filename -- the remind file uids -- the UIDs of the Remind lines (all if None) """ self._update() if not uids: uids = self._reminders[filename] items = [] for uid in uids: cal = iCalendar() self._gen_vevent(self._reminders[filename][uid], cal.add('vevent')) etag = md5() etag.update(self._reminders[filename][uid]['line'].encode("utf-8")) items.append((uid, cal, '"%s"' % etag.hexdigest())) return items def to_vobject(self, filename=None, uid=None): """Return iCal object of Remind lines If filename and UID are specified, the vObject only contains that event. If only a filename is specified, the vObject contains all events in the file. Otherwise the vObject contains all all objects of all files associated with the Remind object. filename -- the remind file uid -- the UID of the Remind line """ self._update() cal = iCalendar() if uid: self._gen_vevent(self._reminders[filename][uid], cal.add('vevent')) elif filename: for event in self._reminders[filename].values(): self._gen_vevent(event, cal.add('vevent')) else: for filename in self._reminders: for event in self._reminders[filename].values(): self._gen_vevent(event, cal.add('vevent')) return cal def stdin_to_vobject(self, lines): """Return iCal object of the Remind commands in lines""" cal = iCalendar() for event in self._parse_remind('-', lines)['-'].values(): self._gen_vevent(event, cal.add('vevent')) return cal @staticmethod def _parse_rdate(rdates): """Convert from iCal rdate to Remind trigdate syntax""" trigdates = [rdate.strftime("trigdate()=='%Y-%m-%d'") for rdate in rdates] return 'SATISFY [%s]' % '||'.join(trigdates) @staticmethod def _parse_rruleset(rruleset): """Convert from iCal rrule to Remind recurrence syntax""" # pylint: disable=protected-access if rruleset._rrule[0]._freq == 0: return [] rep = [] if rruleset._rrule[0]._byweekday and len(rruleset._rrule[0]._byweekday) > 1: rep.append('*1') elif rruleset._rrule[0]._freq == rrule.DAILY: rep.append('*%d' % rruleset._rrule[0]._interval) elif rruleset._rrule[0]._freq == rrule.WEEKLY: rep.append('*%d' % (7 * rruleset._rrule[0]._interval)) else: return Remind._parse_rdate(rruleset._rrule[0]) if rruleset._rrule[0]._byweekday and len(rruleset._rrule[0]._byweekday) > 1: daynums = set(range(7)) - set(rruleset._rrule[0]._byweekday) weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] days = [weekdays[day] for day in daynums] rep.append('SKIP OMIT %s' % ' '.join(days)) if rruleset._rrule[0]._until: rep.append(rruleset._rrule[0]._until.strftime('UNTIL %b %d %Y').replace(' 0', ' ')) elif rruleset._rrule[0]._count: rep.append(rruleset[-1].strftime('UNTIL %b %d %Y').replace(' 0', ' ')) return rep @staticmethod def _event_duration(vevent): """unify dtend and duration to the duration of the given vevent""" if hasattr(vevent, 'dtend'): return vevent.dtend.value - vevent.dtstart.value elif hasattr(vevent, 'duration') and vevent.duration.value: return vevent.duration.value return timedelta(0) @staticmethod def _gen_msg(vevent, label, tail, sep): """Generate a Remind MSG from the given vevent. Opposite of _gen_description() """ rem = ['MSG'] msg = [] if label: msg.append(label) if hasattr(vevent, 'summary') and vevent.summary.value: msg.append(Remind._rem_clean(vevent.summary.value)) else: msg.append('empty reminder') if hasattr(vevent, 'location') and vevent.location.value: msg.append('at %s' % Remind._rem_clean(vevent.location.value)) has_desc = hasattr(vevent, 'description') and vevent.description.value if tail or has_desc: rem.append('%%"%s%%"' % ' '.join(msg)) else: rem.append(' '.join(msg)) if tail: rem.append(tail) if has_desc: rem[-1] += sep + Remind._rem_clean(vevent.description.value) return ' '.join(rem) @staticmethod def _rem_clean(rem): """Strip, transform newlines, and escape '[' in string so it's acceptable as a remind entry.""" return rem.strip().replace('\n', '%_').replace('[', '["["]') @staticmethod def _abbr_tag(tag): """Transform a string so it's acceptable as a remind tag. """ return tag.replace(" ", "")[:48] def to_remind(self, vevent, label=None, priority=None, tags=None, tail=None, sep=" ", postdate=None, posttime=None): """Generate a Remind command from the given vevent""" remind = ['REM'] trigdates = None if hasattr(vevent, 'rrule'): trigdates = Remind._parse_rruleset(vevent.rruleset) dtstart = vevent.dtstart.value # If we don't get timezone information, handle it as a naive datetime. # See https://github.com/jspricke/python-remind/issues/2 for reference. if isinstance(dtstart, datetime) and dtstart.tzinfo: dtstart = dtstart.astimezone(self._localtz) dtend = None if hasattr(vevent, 'dtend'): dtend = vevent.dtend.value if isinstance(dtend, datetime) and dtend.tzinfo: dtend = dtend.astimezone(self._localtz) if not hasattr(vevent, 'rdate') and not isinstance(trigdates, str): remind.append(dtstart.strftime('%b %d %Y').replace(' 0', ' ')) if postdate: remind.append(postdate) if priority: remind.append('PRIORITY %s' % priority) if isinstance(trigdates, list): remind.extend(trigdates) duration = Remind._event_duration(vevent) if type(dtstart) is date and duration.days > 1: remind.append('*1') if dtend is not None: dtend -= timedelta(days=1) remind.append(dtend.strftime('UNTIL %b %d %Y').replace(' 0', ' ')) if isinstance(dtstart, datetime): remind.append(dtstart.strftime('AT %H:%M').replace(' 0', ' ')) if posttime: remind.append(posttime) if duration.total_seconds() > 0: remind.append('DURATION %d:%02d' % divmod(duration.total_seconds() / 60, 60)) if hasattr(vevent, 'rdate'): remind.append(Remind._parse_rdate(vevent.rdate.value)) elif isinstance(trigdates, str): remind.append(trigdates) if hasattr(vevent, 'class'): remind.append('TAG %s' % Remind._abbr_tag(vevent.getChildValue('class'))) if tags: remind.extend(['TAG %s' % Remind._abbr_tag(tag) for tag in tags]) if hasattr(vevent, 'categories_list'): for categories in vevent.categories_list: for category in categories.value: remind.append('TAG %s' % Remind._abbr_tag(category)) remind.append(Remind._gen_msg(vevent, label, tail, sep)) return ' '.join(remind) + '\n' def to_reminders(self, ical, label=None, priority=None, tags=None, tail=None, sep=" ", postdate=None, posttime=None): """Return Remind commands for all events of a iCalendar""" if not hasattr(ical, 'vevent_list'): return '' reminders = [self.to_remind(vevent, label, priority, tags, tail, sep, postdate, posttime) for vevent in ical.vevent_list] return ''.join(reminders) def append(self, ical, filename=None): """Append a Remind command generated from the iCalendar to the file""" return self.append_vobject(readOne(ical), filename) def remove(self, uid, filename=None): """Remove the Remind command with the uid from the file""" if not filename: filename = self._filename elif filename not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(filename).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): del rem[index] open(filename, 'w').writelines(rem) break def replace(self, uid, ical, filename=None): """Update the Remind command with the uid in the file with the new iCalendar""" return self.replace_vobject(uid, readOne(ical), filename) def replace_vobject(self, uid, ical, filename=None): """Update the Remind command with the uid in the file with the new iCalendar""" if not filename: filename = self._filename elif filename not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(filename).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): rem[index] = self.to_reminders(ical) new_uid = self._get_uid(rem[index]) open(filename, 'w').writelines(rem) return new_uid def move_vobject(self, uid, from_file, to_file): """Move the Remind command with the uid from from_file to to_file""" if from_file not in self._reminders or to_file not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(from_file).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): del rem[index] open(from_file, 'w').writelines(rem) open(to_file, 'a').write(line) break def get_meta(self): """Meta tags of the vObject collection""" return {'tag': 'VCALENDAR', 'C:supported-calendar-component-set': 'VEVENT'} def last_modified(self): """Last time the Remind files where parsed""" self._update() return self._mtime
jspricke/python-remind
remind.py
Remind.remove
python
def remove(self, uid, filename=None): if not filename: filename = self._filename elif filename not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(filename).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): del rem[index] open(filename, 'w').writelines(rem) break
Remove the Remind command with the uid from the file
train
https://github.com/jspricke/python-remind/blob/dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1/remind.py#L529-L544
null
class Remind(object): """Represents a collection of Remind files""" def __init__(self, filename=expanduser('~/.reminders'), localtz=None, startdate=date.today() - timedelta(weeks=12), month=15, alarm=timedelta(minutes=-10)): """Constructor filename -- the remind file (included files will be used as well) localtz -- the timezone of the remind file startdate -- the date to start parsing, will be passed to remind month -- how many month to parse, will be passed to remind -s """ self._localtz = localtz if localtz else get_localzone() self._filename = filename self._startdate = startdate self._month = month self._lock = Lock() self._reminders = {} self._mtime = 0 self._alarm = alarm self._update() def _parse_remind(self, filename, lines=''): """Calls remind and parses the output into a dict filename -- the remind file (included files will be used as well) lines -- used as stdin to remind (filename will be set to -) """ files = {} reminders = {} if lines: filename = '-' files[filename] = lines reminders[filename] = {} cmd = ['remind', '-l', '-s%d' % self._month, '-b1', '-y', '-r', filename, str(self._startdate)] try: rem = Popen(cmd, stdin=PIPE, stdout=PIPE).communicate(input=lines.encode('utf-8'))[0].decode('utf-8') except OSError: raise OSError('Error running: %s' % ' '.join(cmd)) rem = rem.splitlines() for (fileinfo, line) in zip(rem[::2], rem[1::2]): fileinfo = fileinfo.split() src_filename = fileinfo[3] if src_filename not in files: # There is a race condition with the remind call above here. # This could be solved by parsing the remind -de output, # but I don't see an easy way to do that. files[src_filename] = open(src_filename).readlines() reminders[src_filename] = {} mtime = getmtime(src_filename) if mtime > self._mtime: self._mtime = mtime text = files[src_filename][int(fileinfo[2]) - 1] event = self._parse_remind_line(line, text) if event['uid'] in reminders[src_filename]: reminders[src_filename][event['uid']]['dtstart'] += event['dtstart'] reminders[src_filename][event['uid']]['line'] += line else: reminders[src_filename][event['uid']] = event reminders[src_filename][event['uid']]['line'] = line # Find included files without reminders and add them to the file list for source in files.values(): for line in source: if line.startswith('include'): new_file = line.split(' ')[1].strip() if new_file not in reminders: reminders[new_file] = {} mtime = getmtime(new_file) if mtime > self._mtime: self._mtime = mtime return reminders @staticmethod def _gen_description(text): """Convert from Remind MSG to iCal description Opposite of _gen_msg() """ return text[text.rfind('%"') + 3:].replace('%_', '\n').replace('["["]', '[').strip() def _parse_remind_line(self, line, text): """Parse a line of remind output into a dict line -- the remind output text -- the original remind input """ event = {} line = line.split(None, 6) dat = [int(f) for f in line[0].split('/')] if line[4] != '*': start = divmod(int(line[4]), 60) event['dtstart'] = [datetime(dat[0], dat[1], dat[2], start[0], start[1], tzinfo=self._localtz)] if line[3] != '*': event['duration'] = timedelta(minutes=int(line[3])) else: event['dtstart'] = [date(dat[0], dat[1], dat[2])] msg = ' '.join(line[5:]) if line[4] == '*' else line[6] msg = msg.strip().replace('%_', '\n').replace('["["]', '[') if ' at ' in msg: (event['msg'], event['location']) = msg.rsplit(' at ', 1) else: event['msg'] = msg if '%"' in text: event['description'] = Remind._gen_description(text) tags = line[2].split(',') classes = ['PUBLIC', 'PRIVATE', 'CONFIDENTIAL'] for tag in tags[:-1]: if tag in classes: event['class'] = tag event['categories'] = [tag for tag in tags[:-1] if tag not in classes] event['uid'] = '%s@%s' % (tags[-1][7:], getfqdn()) return event @staticmethod def _interval(dates): """Return the distance between all dates and 0 if they are different""" interval = (dates[1] - dates[0]).days last = dates[0] for dat in dates[1:]: if (dat - last).days != interval: return 0 last = dat return interval @staticmethod def _gen_dtend_rrule(dtstarts, vevent): """Generate an rdate or rrule from a list of dates and add it to the vevent""" interval = Remind._interval(dtstarts) if interval > 0 and interval % 7 == 0: rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.WEEKLY, interval=interval // 7, count=len(dtstarts))) vevent.rruleset = rset elif interval > 1: rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.DAILY, interval=interval, count=len(dtstarts))) vevent.rruleset = rset elif interval > 0: if isinstance(dtstarts[0], datetime): rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.DAILY, count=len(dtstarts))) vevent.rruleset = rset else: vevent.add('dtend').value = dtstarts[-1] + timedelta(days=1) else: rset = rrule.rruleset() if isinstance(dtstarts[0], datetime): for dat in dtstarts: rset.rdate(dat) else: for dat in dtstarts: rset.rdate(datetime(dat.year, dat.month, dat.day)) # temporary set dtstart to a different date, so it's not # removed from rset by python-vobject works around bug in # Android: # https://github.com/rfc2822/davdroid/issues/340 vevent.dtstart.value = dtstarts[0] - timedelta(days=1) vevent.rruleset = rset vevent.dtstart.value = dtstarts[0] if not isinstance(dtstarts[0], datetime): vevent.add('dtend').value = dtstarts[0] + timedelta(days=1) def _gen_vevent(self, event, vevent): """Generate vevent from given event""" vevent.add('dtstart').value = event['dtstart'][0] vevent.add('dtstamp').value = datetime.fromtimestamp(self._mtime) vevent.add('summary').value = event['msg'] vevent.add('uid').value = event['uid'] if 'class' in event: vevent.add('class').value = event['class'] if 'categories' in event and len(event['categories']) > 0: vevent.add('categories').value = event['categories'] if 'location' in event: vevent.add('location').value = event['location'] if 'description' in event: vevent.add('description').value = event['description'] if isinstance(event['dtstart'][0], datetime): if self._alarm != timedelta(): valarm = vevent.add('valarm') valarm.add('trigger').value = self._alarm valarm.add('action').value = 'DISPLAY' valarm.add('description').value = event['msg'] if 'duration' in event: vevent.add('duration').value = event['duration'] else: vevent.add('dtend').value = event['dtstart'][0] elif len(event['dtstart']) == 1: vevent.add('dtend').value = event['dtstart'][0] + timedelta(days=1) if len(event['dtstart']) > 1: Remind._gen_dtend_rrule(event['dtstart'], vevent) def _update(self): """Reload Remind files if the mtime is newer""" update = not self._reminders with self._lock: for fname in self._reminders: if getmtime(fname) > self._mtime: update = True break if update: self._reminders = self._parse_remind(self._filename) def get_filesnames(self): """All filenames parsed by remind (including included files)""" self._update() return list(self._reminders.keys()) @staticmethod def _get_uid(line): """UID of a remind line""" return '%s@%s' % (md5(line[:-1].encode('utf-8')).hexdigest(), getfqdn()) def get_uids(self, filename=None): """UIDs of all reminders in the file excluding included files If a filename is specified, only it's UIDs are return, otherwise all. filename -- the remind file """ self._update() if filename: if filename not in self._reminders: return [] return self._reminders[filename].keys() return [uid for uids in self._reminders.values() for uid in uids] def to_vobject_etag(self, filename, uid): """Return iCal object and etag of one Remind entry filename -- the remind file uid -- the UID of the Remind line """ return self.to_vobjects(filename, [uid])[0][1:3] def to_vobjects(self, filename, uids=None): """Return iCal objects and etags of all Remind entries in uids filename -- the remind file uids -- the UIDs of the Remind lines (all if None) """ self._update() if not uids: uids = self._reminders[filename] items = [] for uid in uids: cal = iCalendar() self._gen_vevent(self._reminders[filename][uid], cal.add('vevent')) etag = md5() etag.update(self._reminders[filename][uid]['line'].encode("utf-8")) items.append((uid, cal, '"%s"' % etag.hexdigest())) return items def to_vobject(self, filename=None, uid=None): """Return iCal object of Remind lines If filename and UID are specified, the vObject only contains that event. If only a filename is specified, the vObject contains all events in the file. Otherwise the vObject contains all all objects of all files associated with the Remind object. filename -- the remind file uid -- the UID of the Remind line """ self._update() cal = iCalendar() if uid: self._gen_vevent(self._reminders[filename][uid], cal.add('vevent')) elif filename: for event in self._reminders[filename].values(): self._gen_vevent(event, cal.add('vevent')) else: for filename in self._reminders: for event in self._reminders[filename].values(): self._gen_vevent(event, cal.add('vevent')) return cal def stdin_to_vobject(self, lines): """Return iCal object of the Remind commands in lines""" cal = iCalendar() for event in self._parse_remind('-', lines)['-'].values(): self._gen_vevent(event, cal.add('vevent')) return cal @staticmethod def _parse_rdate(rdates): """Convert from iCal rdate to Remind trigdate syntax""" trigdates = [rdate.strftime("trigdate()=='%Y-%m-%d'") for rdate in rdates] return 'SATISFY [%s]' % '||'.join(trigdates) @staticmethod def _parse_rruleset(rruleset): """Convert from iCal rrule to Remind recurrence syntax""" # pylint: disable=protected-access if rruleset._rrule[0]._freq == 0: return [] rep = [] if rruleset._rrule[0]._byweekday and len(rruleset._rrule[0]._byweekday) > 1: rep.append('*1') elif rruleset._rrule[0]._freq == rrule.DAILY: rep.append('*%d' % rruleset._rrule[0]._interval) elif rruleset._rrule[0]._freq == rrule.WEEKLY: rep.append('*%d' % (7 * rruleset._rrule[0]._interval)) else: return Remind._parse_rdate(rruleset._rrule[0]) if rruleset._rrule[0]._byweekday and len(rruleset._rrule[0]._byweekday) > 1: daynums = set(range(7)) - set(rruleset._rrule[0]._byweekday) weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] days = [weekdays[day] for day in daynums] rep.append('SKIP OMIT %s' % ' '.join(days)) if rruleset._rrule[0]._until: rep.append(rruleset._rrule[0]._until.strftime('UNTIL %b %d %Y').replace(' 0', ' ')) elif rruleset._rrule[0]._count: rep.append(rruleset[-1].strftime('UNTIL %b %d %Y').replace(' 0', ' ')) return rep @staticmethod def _event_duration(vevent): """unify dtend and duration to the duration of the given vevent""" if hasattr(vevent, 'dtend'): return vevent.dtend.value - vevent.dtstart.value elif hasattr(vevent, 'duration') and vevent.duration.value: return vevent.duration.value return timedelta(0) @staticmethod def _gen_msg(vevent, label, tail, sep): """Generate a Remind MSG from the given vevent. Opposite of _gen_description() """ rem = ['MSG'] msg = [] if label: msg.append(label) if hasattr(vevent, 'summary') and vevent.summary.value: msg.append(Remind._rem_clean(vevent.summary.value)) else: msg.append('empty reminder') if hasattr(vevent, 'location') and vevent.location.value: msg.append('at %s' % Remind._rem_clean(vevent.location.value)) has_desc = hasattr(vevent, 'description') and vevent.description.value if tail or has_desc: rem.append('%%"%s%%"' % ' '.join(msg)) else: rem.append(' '.join(msg)) if tail: rem.append(tail) if has_desc: rem[-1] += sep + Remind._rem_clean(vevent.description.value) return ' '.join(rem) @staticmethod def _rem_clean(rem): """Strip, transform newlines, and escape '[' in string so it's acceptable as a remind entry.""" return rem.strip().replace('\n', '%_').replace('[', '["["]') @staticmethod def _abbr_tag(tag): """Transform a string so it's acceptable as a remind tag. """ return tag.replace(" ", "")[:48] def to_remind(self, vevent, label=None, priority=None, tags=None, tail=None, sep=" ", postdate=None, posttime=None): """Generate a Remind command from the given vevent""" remind = ['REM'] trigdates = None if hasattr(vevent, 'rrule'): trigdates = Remind._parse_rruleset(vevent.rruleset) dtstart = vevent.dtstart.value # If we don't get timezone information, handle it as a naive datetime. # See https://github.com/jspricke/python-remind/issues/2 for reference. if isinstance(dtstart, datetime) and dtstart.tzinfo: dtstart = dtstart.astimezone(self._localtz) dtend = None if hasattr(vevent, 'dtend'): dtend = vevent.dtend.value if isinstance(dtend, datetime) and dtend.tzinfo: dtend = dtend.astimezone(self._localtz) if not hasattr(vevent, 'rdate') and not isinstance(trigdates, str): remind.append(dtstart.strftime('%b %d %Y').replace(' 0', ' ')) if postdate: remind.append(postdate) if priority: remind.append('PRIORITY %s' % priority) if isinstance(trigdates, list): remind.extend(trigdates) duration = Remind._event_duration(vevent) if type(dtstart) is date and duration.days > 1: remind.append('*1') if dtend is not None: dtend -= timedelta(days=1) remind.append(dtend.strftime('UNTIL %b %d %Y').replace(' 0', ' ')) if isinstance(dtstart, datetime): remind.append(dtstart.strftime('AT %H:%M').replace(' 0', ' ')) if posttime: remind.append(posttime) if duration.total_seconds() > 0: remind.append('DURATION %d:%02d' % divmod(duration.total_seconds() / 60, 60)) if hasattr(vevent, 'rdate'): remind.append(Remind._parse_rdate(vevent.rdate.value)) elif isinstance(trigdates, str): remind.append(trigdates) if hasattr(vevent, 'class'): remind.append('TAG %s' % Remind._abbr_tag(vevent.getChildValue('class'))) if tags: remind.extend(['TAG %s' % Remind._abbr_tag(tag) for tag in tags]) if hasattr(vevent, 'categories_list'): for categories in vevent.categories_list: for category in categories.value: remind.append('TAG %s' % Remind._abbr_tag(category)) remind.append(Remind._gen_msg(vevent, label, tail, sep)) return ' '.join(remind) + '\n' def to_reminders(self, ical, label=None, priority=None, tags=None, tail=None, sep=" ", postdate=None, posttime=None): """Return Remind commands for all events of a iCalendar""" if not hasattr(ical, 'vevent_list'): return '' reminders = [self.to_remind(vevent, label, priority, tags, tail, sep, postdate, posttime) for vevent in ical.vevent_list] return ''.join(reminders) def append(self, ical, filename=None): """Append a Remind command generated from the iCalendar to the file""" return self.append_vobject(readOne(ical), filename) def append_vobject(self, ical, filename=None): """Append a Remind command generated from the iCalendar to the file""" if not filename: filename = self._filename elif filename not in self._reminders: return with self._lock: outdat = self.to_reminders(ical) open(filename, 'a').write(outdat) return Remind._get_uid(outdat) def replace(self, uid, ical, filename=None): """Update the Remind command with the uid in the file with the new iCalendar""" return self.replace_vobject(uid, readOne(ical), filename) def replace_vobject(self, uid, ical, filename=None): """Update the Remind command with the uid in the file with the new iCalendar""" if not filename: filename = self._filename elif filename not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(filename).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): rem[index] = self.to_reminders(ical) new_uid = self._get_uid(rem[index]) open(filename, 'w').writelines(rem) return new_uid def move_vobject(self, uid, from_file, to_file): """Move the Remind command with the uid from from_file to to_file""" if from_file not in self._reminders or to_file not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(from_file).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): del rem[index] open(from_file, 'w').writelines(rem) open(to_file, 'a').write(line) break def get_meta(self): """Meta tags of the vObject collection""" return {'tag': 'VCALENDAR', 'C:supported-calendar-component-set': 'VEVENT'} def last_modified(self): """Last time the Remind files where parsed""" self._update() return self._mtime
jspricke/python-remind
remind.py
Remind.replace
python
def replace(self, uid, ical, filename=None): return self.replace_vobject(uid, readOne(ical), filename)
Update the Remind command with the uid in the file with the new iCalendar
train
https://github.com/jspricke/python-remind/blob/dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1/remind.py#L546-L548
[ "def replace_vobject(self, uid, ical, filename=None):\n \"\"\"Update the Remind command with the uid in the file with the new iCalendar\"\"\"\n if not filename:\n filename = self._filename\n elif filename not in self._reminders:\n return\n\n uid = uid.split('@')[0]\n\n with self._lock:\...
class Remind(object): """Represents a collection of Remind files""" def __init__(self, filename=expanduser('~/.reminders'), localtz=None, startdate=date.today() - timedelta(weeks=12), month=15, alarm=timedelta(minutes=-10)): """Constructor filename -- the remind file (included files will be used as well) localtz -- the timezone of the remind file startdate -- the date to start parsing, will be passed to remind month -- how many month to parse, will be passed to remind -s """ self._localtz = localtz if localtz else get_localzone() self._filename = filename self._startdate = startdate self._month = month self._lock = Lock() self._reminders = {} self._mtime = 0 self._alarm = alarm self._update() def _parse_remind(self, filename, lines=''): """Calls remind and parses the output into a dict filename -- the remind file (included files will be used as well) lines -- used as stdin to remind (filename will be set to -) """ files = {} reminders = {} if lines: filename = '-' files[filename] = lines reminders[filename] = {} cmd = ['remind', '-l', '-s%d' % self._month, '-b1', '-y', '-r', filename, str(self._startdate)] try: rem = Popen(cmd, stdin=PIPE, stdout=PIPE).communicate(input=lines.encode('utf-8'))[0].decode('utf-8') except OSError: raise OSError('Error running: %s' % ' '.join(cmd)) rem = rem.splitlines() for (fileinfo, line) in zip(rem[::2], rem[1::2]): fileinfo = fileinfo.split() src_filename = fileinfo[3] if src_filename not in files: # There is a race condition with the remind call above here. # This could be solved by parsing the remind -de output, # but I don't see an easy way to do that. files[src_filename] = open(src_filename).readlines() reminders[src_filename] = {} mtime = getmtime(src_filename) if mtime > self._mtime: self._mtime = mtime text = files[src_filename][int(fileinfo[2]) - 1] event = self._parse_remind_line(line, text) if event['uid'] in reminders[src_filename]: reminders[src_filename][event['uid']]['dtstart'] += event['dtstart'] reminders[src_filename][event['uid']]['line'] += line else: reminders[src_filename][event['uid']] = event reminders[src_filename][event['uid']]['line'] = line # Find included files without reminders and add them to the file list for source in files.values(): for line in source: if line.startswith('include'): new_file = line.split(' ')[1].strip() if new_file not in reminders: reminders[new_file] = {} mtime = getmtime(new_file) if mtime > self._mtime: self._mtime = mtime return reminders @staticmethod def _gen_description(text): """Convert from Remind MSG to iCal description Opposite of _gen_msg() """ return text[text.rfind('%"') + 3:].replace('%_', '\n').replace('["["]', '[').strip() def _parse_remind_line(self, line, text): """Parse a line of remind output into a dict line -- the remind output text -- the original remind input """ event = {} line = line.split(None, 6) dat = [int(f) for f in line[0].split('/')] if line[4] != '*': start = divmod(int(line[4]), 60) event['dtstart'] = [datetime(dat[0], dat[1], dat[2], start[0], start[1], tzinfo=self._localtz)] if line[3] != '*': event['duration'] = timedelta(minutes=int(line[3])) else: event['dtstart'] = [date(dat[0], dat[1], dat[2])] msg = ' '.join(line[5:]) if line[4] == '*' else line[6] msg = msg.strip().replace('%_', '\n').replace('["["]', '[') if ' at ' in msg: (event['msg'], event['location']) = msg.rsplit(' at ', 1) else: event['msg'] = msg if '%"' in text: event['description'] = Remind._gen_description(text) tags = line[2].split(',') classes = ['PUBLIC', 'PRIVATE', 'CONFIDENTIAL'] for tag in tags[:-1]: if tag in classes: event['class'] = tag event['categories'] = [tag for tag in tags[:-1] if tag not in classes] event['uid'] = '%s@%s' % (tags[-1][7:], getfqdn()) return event @staticmethod def _interval(dates): """Return the distance between all dates and 0 if they are different""" interval = (dates[1] - dates[0]).days last = dates[0] for dat in dates[1:]: if (dat - last).days != interval: return 0 last = dat return interval @staticmethod def _gen_dtend_rrule(dtstarts, vevent): """Generate an rdate or rrule from a list of dates and add it to the vevent""" interval = Remind._interval(dtstarts) if interval > 0 and interval % 7 == 0: rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.WEEKLY, interval=interval // 7, count=len(dtstarts))) vevent.rruleset = rset elif interval > 1: rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.DAILY, interval=interval, count=len(dtstarts))) vevent.rruleset = rset elif interval > 0: if isinstance(dtstarts[0], datetime): rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.DAILY, count=len(dtstarts))) vevent.rruleset = rset else: vevent.add('dtend').value = dtstarts[-1] + timedelta(days=1) else: rset = rrule.rruleset() if isinstance(dtstarts[0], datetime): for dat in dtstarts: rset.rdate(dat) else: for dat in dtstarts: rset.rdate(datetime(dat.year, dat.month, dat.day)) # temporary set dtstart to a different date, so it's not # removed from rset by python-vobject works around bug in # Android: # https://github.com/rfc2822/davdroid/issues/340 vevent.dtstart.value = dtstarts[0] - timedelta(days=1) vevent.rruleset = rset vevent.dtstart.value = dtstarts[0] if not isinstance(dtstarts[0], datetime): vevent.add('dtend').value = dtstarts[0] + timedelta(days=1) def _gen_vevent(self, event, vevent): """Generate vevent from given event""" vevent.add('dtstart').value = event['dtstart'][0] vevent.add('dtstamp').value = datetime.fromtimestamp(self._mtime) vevent.add('summary').value = event['msg'] vevent.add('uid').value = event['uid'] if 'class' in event: vevent.add('class').value = event['class'] if 'categories' in event and len(event['categories']) > 0: vevent.add('categories').value = event['categories'] if 'location' in event: vevent.add('location').value = event['location'] if 'description' in event: vevent.add('description').value = event['description'] if isinstance(event['dtstart'][0], datetime): if self._alarm != timedelta(): valarm = vevent.add('valarm') valarm.add('trigger').value = self._alarm valarm.add('action').value = 'DISPLAY' valarm.add('description').value = event['msg'] if 'duration' in event: vevent.add('duration').value = event['duration'] else: vevent.add('dtend').value = event['dtstart'][0] elif len(event['dtstart']) == 1: vevent.add('dtend').value = event['dtstart'][0] + timedelta(days=1) if len(event['dtstart']) > 1: Remind._gen_dtend_rrule(event['dtstart'], vevent) def _update(self): """Reload Remind files if the mtime is newer""" update = not self._reminders with self._lock: for fname in self._reminders: if getmtime(fname) > self._mtime: update = True break if update: self._reminders = self._parse_remind(self._filename) def get_filesnames(self): """All filenames parsed by remind (including included files)""" self._update() return list(self._reminders.keys()) @staticmethod def _get_uid(line): """UID of a remind line""" return '%s@%s' % (md5(line[:-1].encode('utf-8')).hexdigest(), getfqdn()) def get_uids(self, filename=None): """UIDs of all reminders in the file excluding included files If a filename is specified, only it's UIDs are return, otherwise all. filename -- the remind file """ self._update() if filename: if filename not in self._reminders: return [] return self._reminders[filename].keys() return [uid for uids in self._reminders.values() for uid in uids] def to_vobject_etag(self, filename, uid): """Return iCal object and etag of one Remind entry filename -- the remind file uid -- the UID of the Remind line """ return self.to_vobjects(filename, [uid])[0][1:3] def to_vobjects(self, filename, uids=None): """Return iCal objects and etags of all Remind entries in uids filename -- the remind file uids -- the UIDs of the Remind lines (all if None) """ self._update() if not uids: uids = self._reminders[filename] items = [] for uid in uids: cal = iCalendar() self._gen_vevent(self._reminders[filename][uid], cal.add('vevent')) etag = md5() etag.update(self._reminders[filename][uid]['line'].encode("utf-8")) items.append((uid, cal, '"%s"' % etag.hexdigest())) return items def to_vobject(self, filename=None, uid=None): """Return iCal object of Remind lines If filename and UID are specified, the vObject only contains that event. If only a filename is specified, the vObject contains all events in the file. Otherwise the vObject contains all all objects of all files associated with the Remind object. filename -- the remind file uid -- the UID of the Remind line """ self._update() cal = iCalendar() if uid: self._gen_vevent(self._reminders[filename][uid], cal.add('vevent')) elif filename: for event in self._reminders[filename].values(): self._gen_vevent(event, cal.add('vevent')) else: for filename in self._reminders: for event in self._reminders[filename].values(): self._gen_vevent(event, cal.add('vevent')) return cal def stdin_to_vobject(self, lines): """Return iCal object of the Remind commands in lines""" cal = iCalendar() for event in self._parse_remind('-', lines)['-'].values(): self._gen_vevent(event, cal.add('vevent')) return cal @staticmethod def _parse_rdate(rdates): """Convert from iCal rdate to Remind trigdate syntax""" trigdates = [rdate.strftime("trigdate()=='%Y-%m-%d'") for rdate in rdates] return 'SATISFY [%s]' % '||'.join(trigdates) @staticmethod def _parse_rruleset(rruleset): """Convert from iCal rrule to Remind recurrence syntax""" # pylint: disable=protected-access if rruleset._rrule[0]._freq == 0: return [] rep = [] if rruleset._rrule[0]._byweekday and len(rruleset._rrule[0]._byweekday) > 1: rep.append('*1') elif rruleset._rrule[0]._freq == rrule.DAILY: rep.append('*%d' % rruleset._rrule[0]._interval) elif rruleset._rrule[0]._freq == rrule.WEEKLY: rep.append('*%d' % (7 * rruleset._rrule[0]._interval)) else: return Remind._parse_rdate(rruleset._rrule[0]) if rruleset._rrule[0]._byweekday and len(rruleset._rrule[0]._byweekday) > 1: daynums = set(range(7)) - set(rruleset._rrule[0]._byweekday) weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] days = [weekdays[day] for day in daynums] rep.append('SKIP OMIT %s' % ' '.join(days)) if rruleset._rrule[0]._until: rep.append(rruleset._rrule[0]._until.strftime('UNTIL %b %d %Y').replace(' 0', ' ')) elif rruleset._rrule[0]._count: rep.append(rruleset[-1].strftime('UNTIL %b %d %Y').replace(' 0', ' ')) return rep @staticmethod def _event_duration(vevent): """unify dtend and duration to the duration of the given vevent""" if hasattr(vevent, 'dtend'): return vevent.dtend.value - vevent.dtstart.value elif hasattr(vevent, 'duration') and vevent.duration.value: return vevent.duration.value return timedelta(0) @staticmethod def _gen_msg(vevent, label, tail, sep): """Generate a Remind MSG from the given vevent. Opposite of _gen_description() """ rem = ['MSG'] msg = [] if label: msg.append(label) if hasattr(vevent, 'summary') and vevent.summary.value: msg.append(Remind._rem_clean(vevent.summary.value)) else: msg.append('empty reminder') if hasattr(vevent, 'location') and vevent.location.value: msg.append('at %s' % Remind._rem_clean(vevent.location.value)) has_desc = hasattr(vevent, 'description') and vevent.description.value if tail or has_desc: rem.append('%%"%s%%"' % ' '.join(msg)) else: rem.append(' '.join(msg)) if tail: rem.append(tail) if has_desc: rem[-1] += sep + Remind._rem_clean(vevent.description.value) return ' '.join(rem) @staticmethod def _rem_clean(rem): """Strip, transform newlines, and escape '[' in string so it's acceptable as a remind entry.""" return rem.strip().replace('\n', '%_').replace('[', '["["]') @staticmethod def _abbr_tag(tag): """Transform a string so it's acceptable as a remind tag. """ return tag.replace(" ", "")[:48] def to_remind(self, vevent, label=None, priority=None, tags=None, tail=None, sep=" ", postdate=None, posttime=None): """Generate a Remind command from the given vevent""" remind = ['REM'] trigdates = None if hasattr(vevent, 'rrule'): trigdates = Remind._parse_rruleset(vevent.rruleset) dtstart = vevent.dtstart.value # If we don't get timezone information, handle it as a naive datetime. # See https://github.com/jspricke/python-remind/issues/2 for reference. if isinstance(dtstart, datetime) and dtstart.tzinfo: dtstart = dtstart.astimezone(self._localtz) dtend = None if hasattr(vevent, 'dtend'): dtend = vevent.dtend.value if isinstance(dtend, datetime) and dtend.tzinfo: dtend = dtend.astimezone(self._localtz) if not hasattr(vevent, 'rdate') and not isinstance(trigdates, str): remind.append(dtstart.strftime('%b %d %Y').replace(' 0', ' ')) if postdate: remind.append(postdate) if priority: remind.append('PRIORITY %s' % priority) if isinstance(trigdates, list): remind.extend(trigdates) duration = Remind._event_duration(vevent) if type(dtstart) is date and duration.days > 1: remind.append('*1') if dtend is not None: dtend -= timedelta(days=1) remind.append(dtend.strftime('UNTIL %b %d %Y').replace(' 0', ' ')) if isinstance(dtstart, datetime): remind.append(dtstart.strftime('AT %H:%M').replace(' 0', ' ')) if posttime: remind.append(posttime) if duration.total_seconds() > 0: remind.append('DURATION %d:%02d' % divmod(duration.total_seconds() / 60, 60)) if hasattr(vevent, 'rdate'): remind.append(Remind._parse_rdate(vevent.rdate.value)) elif isinstance(trigdates, str): remind.append(trigdates) if hasattr(vevent, 'class'): remind.append('TAG %s' % Remind._abbr_tag(vevent.getChildValue('class'))) if tags: remind.extend(['TAG %s' % Remind._abbr_tag(tag) for tag in tags]) if hasattr(vevent, 'categories_list'): for categories in vevent.categories_list: for category in categories.value: remind.append('TAG %s' % Remind._abbr_tag(category)) remind.append(Remind._gen_msg(vevent, label, tail, sep)) return ' '.join(remind) + '\n' def to_reminders(self, ical, label=None, priority=None, tags=None, tail=None, sep=" ", postdate=None, posttime=None): """Return Remind commands for all events of a iCalendar""" if not hasattr(ical, 'vevent_list'): return '' reminders = [self.to_remind(vevent, label, priority, tags, tail, sep, postdate, posttime) for vevent in ical.vevent_list] return ''.join(reminders) def append(self, ical, filename=None): """Append a Remind command generated from the iCalendar to the file""" return self.append_vobject(readOne(ical), filename) def append_vobject(self, ical, filename=None): """Append a Remind command generated from the iCalendar to the file""" if not filename: filename = self._filename elif filename not in self._reminders: return with self._lock: outdat = self.to_reminders(ical) open(filename, 'a').write(outdat) return Remind._get_uid(outdat) def remove(self, uid, filename=None): """Remove the Remind command with the uid from the file""" if not filename: filename = self._filename elif filename not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(filename).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): del rem[index] open(filename, 'w').writelines(rem) break def replace_vobject(self, uid, ical, filename=None): """Update the Remind command with the uid in the file with the new iCalendar""" if not filename: filename = self._filename elif filename not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(filename).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): rem[index] = self.to_reminders(ical) new_uid = self._get_uid(rem[index]) open(filename, 'w').writelines(rem) return new_uid def move_vobject(self, uid, from_file, to_file): """Move the Remind command with the uid from from_file to to_file""" if from_file not in self._reminders or to_file not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(from_file).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): del rem[index] open(from_file, 'w').writelines(rem) open(to_file, 'a').write(line) break def get_meta(self): """Meta tags of the vObject collection""" return {'tag': 'VCALENDAR', 'C:supported-calendar-component-set': 'VEVENT'} def last_modified(self): """Last time the Remind files where parsed""" self._update() return self._mtime
jspricke/python-remind
remind.py
Remind.replace_vobject
python
def replace_vobject(self, uid, ical, filename=None): if not filename: filename = self._filename elif filename not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(filename).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): rem[index] = self.to_reminders(ical) new_uid = self._get_uid(rem[index]) open(filename, 'w').writelines(rem) return new_uid
Update the Remind command with the uid in the file with the new iCalendar
train
https://github.com/jspricke/python-remind/blob/dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1/remind.py#L550-L566
[ "def _get_uid(line):\n \"\"\"UID of a remind line\"\"\"\n return '%s@%s' % (md5(line[:-1].encode('utf-8')).hexdigest(), getfqdn())\n", "def to_reminders(self, ical, label=None, priority=None, tags=None,\n tail=None, sep=\" \", postdate=None, posttime=None):\n \"\"\"Return Remind commands ...
class Remind(object): """Represents a collection of Remind files""" def __init__(self, filename=expanduser('~/.reminders'), localtz=None, startdate=date.today() - timedelta(weeks=12), month=15, alarm=timedelta(minutes=-10)): """Constructor filename -- the remind file (included files will be used as well) localtz -- the timezone of the remind file startdate -- the date to start parsing, will be passed to remind month -- how many month to parse, will be passed to remind -s """ self._localtz = localtz if localtz else get_localzone() self._filename = filename self._startdate = startdate self._month = month self._lock = Lock() self._reminders = {} self._mtime = 0 self._alarm = alarm self._update() def _parse_remind(self, filename, lines=''): """Calls remind and parses the output into a dict filename -- the remind file (included files will be used as well) lines -- used as stdin to remind (filename will be set to -) """ files = {} reminders = {} if lines: filename = '-' files[filename] = lines reminders[filename] = {} cmd = ['remind', '-l', '-s%d' % self._month, '-b1', '-y', '-r', filename, str(self._startdate)] try: rem = Popen(cmd, stdin=PIPE, stdout=PIPE).communicate(input=lines.encode('utf-8'))[0].decode('utf-8') except OSError: raise OSError('Error running: %s' % ' '.join(cmd)) rem = rem.splitlines() for (fileinfo, line) in zip(rem[::2], rem[1::2]): fileinfo = fileinfo.split() src_filename = fileinfo[3] if src_filename not in files: # There is a race condition with the remind call above here. # This could be solved by parsing the remind -de output, # but I don't see an easy way to do that. files[src_filename] = open(src_filename).readlines() reminders[src_filename] = {} mtime = getmtime(src_filename) if mtime > self._mtime: self._mtime = mtime text = files[src_filename][int(fileinfo[2]) - 1] event = self._parse_remind_line(line, text) if event['uid'] in reminders[src_filename]: reminders[src_filename][event['uid']]['dtstart'] += event['dtstart'] reminders[src_filename][event['uid']]['line'] += line else: reminders[src_filename][event['uid']] = event reminders[src_filename][event['uid']]['line'] = line # Find included files without reminders and add them to the file list for source in files.values(): for line in source: if line.startswith('include'): new_file = line.split(' ')[1].strip() if new_file not in reminders: reminders[new_file] = {} mtime = getmtime(new_file) if mtime > self._mtime: self._mtime = mtime return reminders @staticmethod def _gen_description(text): """Convert from Remind MSG to iCal description Opposite of _gen_msg() """ return text[text.rfind('%"') + 3:].replace('%_', '\n').replace('["["]', '[').strip() def _parse_remind_line(self, line, text): """Parse a line of remind output into a dict line -- the remind output text -- the original remind input """ event = {} line = line.split(None, 6) dat = [int(f) for f in line[0].split('/')] if line[4] != '*': start = divmod(int(line[4]), 60) event['dtstart'] = [datetime(dat[0], dat[1], dat[2], start[0], start[1], tzinfo=self._localtz)] if line[3] != '*': event['duration'] = timedelta(minutes=int(line[3])) else: event['dtstart'] = [date(dat[0], dat[1], dat[2])] msg = ' '.join(line[5:]) if line[4] == '*' else line[6] msg = msg.strip().replace('%_', '\n').replace('["["]', '[') if ' at ' in msg: (event['msg'], event['location']) = msg.rsplit(' at ', 1) else: event['msg'] = msg if '%"' in text: event['description'] = Remind._gen_description(text) tags = line[2].split(',') classes = ['PUBLIC', 'PRIVATE', 'CONFIDENTIAL'] for tag in tags[:-1]: if tag in classes: event['class'] = tag event['categories'] = [tag for tag in tags[:-1] if tag not in classes] event['uid'] = '%s@%s' % (tags[-1][7:], getfqdn()) return event @staticmethod def _interval(dates): """Return the distance between all dates and 0 if they are different""" interval = (dates[1] - dates[0]).days last = dates[0] for dat in dates[1:]: if (dat - last).days != interval: return 0 last = dat return interval @staticmethod def _gen_dtend_rrule(dtstarts, vevent): """Generate an rdate or rrule from a list of dates and add it to the vevent""" interval = Remind._interval(dtstarts) if interval > 0 and interval % 7 == 0: rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.WEEKLY, interval=interval // 7, count=len(dtstarts))) vevent.rruleset = rset elif interval > 1: rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.DAILY, interval=interval, count=len(dtstarts))) vevent.rruleset = rset elif interval > 0: if isinstance(dtstarts[0], datetime): rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.DAILY, count=len(dtstarts))) vevent.rruleset = rset else: vevent.add('dtend').value = dtstarts[-1] + timedelta(days=1) else: rset = rrule.rruleset() if isinstance(dtstarts[0], datetime): for dat in dtstarts: rset.rdate(dat) else: for dat in dtstarts: rset.rdate(datetime(dat.year, dat.month, dat.day)) # temporary set dtstart to a different date, so it's not # removed from rset by python-vobject works around bug in # Android: # https://github.com/rfc2822/davdroid/issues/340 vevent.dtstart.value = dtstarts[0] - timedelta(days=1) vevent.rruleset = rset vevent.dtstart.value = dtstarts[0] if not isinstance(dtstarts[0], datetime): vevent.add('dtend').value = dtstarts[0] + timedelta(days=1) def _gen_vevent(self, event, vevent): """Generate vevent from given event""" vevent.add('dtstart').value = event['dtstart'][0] vevent.add('dtstamp').value = datetime.fromtimestamp(self._mtime) vevent.add('summary').value = event['msg'] vevent.add('uid').value = event['uid'] if 'class' in event: vevent.add('class').value = event['class'] if 'categories' in event and len(event['categories']) > 0: vevent.add('categories').value = event['categories'] if 'location' in event: vevent.add('location').value = event['location'] if 'description' in event: vevent.add('description').value = event['description'] if isinstance(event['dtstart'][0], datetime): if self._alarm != timedelta(): valarm = vevent.add('valarm') valarm.add('trigger').value = self._alarm valarm.add('action').value = 'DISPLAY' valarm.add('description').value = event['msg'] if 'duration' in event: vevent.add('duration').value = event['duration'] else: vevent.add('dtend').value = event['dtstart'][0] elif len(event['dtstart']) == 1: vevent.add('dtend').value = event['dtstart'][0] + timedelta(days=1) if len(event['dtstart']) > 1: Remind._gen_dtend_rrule(event['dtstart'], vevent) def _update(self): """Reload Remind files if the mtime is newer""" update = not self._reminders with self._lock: for fname in self._reminders: if getmtime(fname) > self._mtime: update = True break if update: self._reminders = self._parse_remind(self._filename) def get_filesnames(self): """All filenames parsed by remind (including included files)""" self._update() return list(self._reminders.keys()) @staticmethod def _get_uid(line): """UID of a remind line""" return '%s@%s' % (md5(line[:-1].encode('utf-8')).hexdigest(), getfqdn()) def get_uids(self, filename=None): """UIDs of all reminders in the file excluding included files If a filename is specified, only it's UIDs are return, otherwise all. filename -- the remind file """ self._update() if filename: if filename not in self._reminders: return [] return self._reminders[filename].keys() return [uid for uids in self._reminders.values() for uid in uids] def to_vobject_etag(self, filename, uid): """Return iCal object and etag of one Remind entry filename -- the remind file uid -- the UID of the Remind line """ return self.to_vobjects(filename, [uid])[0][1:3] def to_vobjects(self, filename, uids=None): """Return iCal objects and etags of all Remind entries in uids filename -- the remind file uids -- the UIDs of the Remind lines (all if None) """ self._update() if not uids: uids = self._reminders[filename] items = [] for uid in uids: cal = iCalendar() self._gen_vevent(self._reminders[filename][uid], cal.add('vevent')) etag = md5() etag.update(self._reminders[filename][uid]['line'].encode("utf-8")) items.append((uid, cal, '"%s"' % etag.hexdigest())) return items def to_vobject(self, filename=None, uid=None): """Return iCal object of Remind lines If filename and UID are specified, the vObject only contains that event. If only a filename is specified, the vObject contains all events in the file. Otherwise the vObject contains all all objects of all files associated with the Remind object. filename -- the remind file uid -- the UID of the Remind line """ self._update() cal = iCalendar() if uid: self._gen_vevent(self._reminders[filename][uid], cal.add('vevent')) elif filename: for event in self._reminders[filename].values(): self._gen_vevent(event, cal.add('vevent')) else: for filename in self._reminders: for event in self._reminders[filename].values(): self._gen_vevent(event, cal.add('vevent')) return cal def stdin_to_vobject(self, lines): """Return iCal object of the Remind commands in lines""" cal = iCalendar() for event in self._parse_remind('-', lines)['-'].values(): self._gen_vevent(event, cal.add('vevent')) return cal @staticmethod def _parse_rdate(rdates): """Convert from iCal rdate to Remind trigdate syntax""" trigdates = [rdate.strftime("trigdate()=='%Y-%m-%d'") for rdate in rdates] return 'SATISFY [%s]' % '||'.join(trigdates) @staticmethod def _parse_rruleset(rruleset): """Convert from iCal rrule to Remind recurrence syntax""" # pylint: disable=protected-access if rruleset._rrule[0]._freq == 0: return [] rep = [] if rruleset._rrule[0]._byweekday and len(rruleset._rrule[0]._byweekday) > 1: rep.append('*1') elif rruleset._rrule[0]._freq == rrule.DAILY: rep.append('*%d' % rruleset._rrule[0]._interval) elif rruleset._rrule[0]._freq == rrule.WEEKLY: rep.append('*%d' % (7 * rruleset._rrule[0]._interval)) else: return Remind._parse_rdate(rruleset._rrule[0]) if rruleset._rrule[0]._byweekday and len(rruleset._rrule[0]._byweekday) > 1: daynums = set(range(7)) - set(rruleset._rrule[0]._byweekday) weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] days = [weekdays[day] for day in daynums] rep.append('SKIP OMIT %s' % ' '.join(days)) if rruleset._rrule[0]._until: rep.append(rruleset._rrule[0]._until.strftime('UNTIL %b %d %Y').replace(' 0', ' ')) elif rruleset._rrule[0]._count: rep.append(rruleset[-1].strftime('UNTIL %b %d %Y').replace(' 0', ' ')) return rep @staticmethod def _event_duration(vevent): """unify dtend and duration to the duration of the given vevent""" if hasattr(vevent, 'dtend'): return vevent.dtend.value - vevent.dtstart.value elif hasattr(vevent, 'duration') and vevent.duration.value: return vevent.duration.value return timedelta(0) @staticmethod def _gen_msg(vevent, label, tail, sep): """Generate a Remind MSG from the given vevent. Opposite of _gen_description() """ rem = ['MSG'] msg = [] if label: msg.append(label) if hasattr(vevent, 'summary') and vevent.summary.value: msg.append(Remind._rem_clean(vevent.summary.value)) else: msg.append('empty reminder') if hasattr(vevent, 'location') and vevent.location.value: msg.append('at %s' % Remind._rem_clean(vevent.location.value)) has_desc = hasattr(vevent, 'description') and vevent.description.value if tail or has_desc: rem.append('%%"%s%%"' % ' '.join(msg)) else: rem.append(' '.join(msg)) if tail: rem.append(tail) if has_desc: rem[-1] += sep + Remind._rem_clean(vevent.description.value) return ' '.join(rem) @staticmethod def _rem_clean(rem): """Strip, transform newlines, and escape '[' in string so it's acceptable as a remind entry.""" return rem.strip().replace('\n', '%_').replace('[', '["["]') @staticmethod def _abbr_tag(tag): """Transform a string so it's acceptable as a remind tag. """ return tag.replace(" ", "")[:48] def to_remind(self, vevent, label=None, priority=None, tags=None, tail=None, sep=" ", postdate=None, posttime=None): """Generate a Remind command from the given vevent""" remind = ['REM'] trigdates = None if hasattr(vevent, 'rrule'): trigdates = Remind._parse_rruleset(vevent.rruleset) dtstart = vevent.dtstart.value # If we don't get timezone information, handle it as a naive datetime. # See https://github.com/jspricke/python-remind/issues/2 for reference. if isinstance(dtstart, datetime) and dtstart.tzinfo: dtstart = dtstart.astimezone(self._localtz) dtend = None if hasattr(vevent, 'dtend'): dtend = vevent.dtend.value if isinstance(dtend, datetime) and dtend.tzinfo: dtend = dtend.astimezone(self._localtz) if not hasattr(vevent, 'rdate') and not isinstance(trigdates, str): remind.append(dtstart.strftime('%b %d %Y').replace(' 0', ' ')) if postdate: remind.append(postdate) if priority: remind.append('PRIORITY %s' % priority) if isinstance(trigdates, list): remind.extend(trigdates) duration = Remind._event_duration(vevent) if type(dtstart) is date and duration.days > 1: remind.append('*1') if dtend is not None: dtend -= timedelta(days=1) remind.append(dtend.strftime('UNTIL %b %d %Y').replace(' 0', ' ')) if isinstance(dtstart, datetime): remind.append(dtstart.strftime('AT %H:%M').replace(' 0', ' ')) if posttime: remind.append(posttime) if duration.total_seconds() > 0: remind.append('DURATION %d:%02d' % divmod(duration.total_seconds() / 60, 60)) if hasattr(vevent, 'rdate'): remind.append(Remind._parse_rdate(vevent.rdate.value)) elif isinstance(trigdates, str): remind.append(trigdates) if hasattr(vevent, 'class'): remind.append('TAG %s' % Remind._abbr_tag(vevent.getChildValue('class'))) if tags: remind.extend(['TAG %s' % Remind._abbr_tag(tag) for tag in tags]) if hasattr(vevent, 'categories_list'): for categories in vevent.categories_list: for category in categories.value: remind.append('TAG %s' % Remind._abbr_tag(category)) remind.append(Remind._gen_msg(vevent, label, tail, sep)) return ' '.join(remind) + '\n' def to_reminders(self, ical, label=None, priority=None, tags=None, tail=None, sep=" ", postdate=None, posttime=None): """Return Remind commands for all events of a iCalendar""" if not hasattr(ical, 'vevent_list'): return '' reminders = [self.to_remind(vevent, label, priority, tags, tail, sep, postdate, posttime) for vevent in ical.vevent_list] return ''.join(reminders) def append(self, ical, filename=None): """Append a Remind command generated from the iCalendar to the file""" return self.append_vobject(readOne(ical), filename) def append_vobject(self, ical, filename=None): """Append a Remind command generated from the iCalendar to the file""" if not filename: filename = self._filename elif filename not in self._reminders: return with self._lock: outdat = self.to_reminders(ical) open(filename, 'a').write(outdat) return Remind._get_uid(outdat) def remove(self, uid, filename=None): """Remove the Remind command with the uid from the file""" if not filename: filename = self._filename elif filename not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(filename).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): del rem[index] open(filename, 'w').writelines(rem) break def replace(self, uid, ical, filename=None): """Update the Remind command with the uid in the file with the new iCalendar""" return self.replace_vobject(uid, readOne(ical), filename) def move_vobject(self, uid, from_file, to_file): """Move the Remind command with the uid from from_file to to_file""" if from_file not in self._reminders or to_file not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(from_file).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): del rem[index] open(from_file, 'w').writelines(rem) open(to_file, 'a').write(line) break def get_meta(self): """Meta tags of the vObject collection""" return {'tag': 'VCALENDAR', 'C:supported-calendar-component-set': 'VEVENT'} def last_modified(self): """Last time the Remind files where parsed""" self._update() return self._mtime
jspricke/python-remind
remind.py
Remind.move_vobject
python
def move_vobject(self, uid, from_file, to_file): if from_file not in self._reminders or to_file not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(from_file).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): del rem[index] open(from_file, 'w').writelines(rem) open(to_file, 'a').write(line) break
Move the Remind command with the uid from from_file to to_file
train
https://github.com/jspricke/python-remind/blob/dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1/remind.py#L568-L582
null
class Remind(object): """Represents a collection of Remind files""" def __init__(self, filename=expanduser('~/.reminders'), localtz=None, startdate=date.today() - timedelta(weeks=12), month=15, alarm=timedelta(minutes=-10)): """Constructor filename -- the remind file (included files will be used as well) localtz -- the timezone of the remind file startdate -- the date to start parsing, will be passed to remind month -- how many month to parse, will be passed to remind -s """ self._localtz = localtz if localtz else get_localzone() self._filename = filename self._startdate = startdate self._month = month self._lock = Lock() self._reminders = {} self._mtime = 0 self._alarm = alarm self._update() def _parse_remind(self, filename, lines=''): """Calls remind and parses the output into a dict filename -- the remind file (included files will be used as well) lines -- used as stdin to remind (filename will be set to -) """ files = {} reminders = {} if lines: filename = '-' files[filename] = lines reminders[filename] = {} cmd = ['remind', '-l', '-s%d' % self._month, '-b1', '-y', '-r', filename, str(self._startdate)] try: rem = Popen(cmd, stdin=PIPE, stdout=PIPE).communicate(input=lines.encode('utf-8'))[0].decode('utf-8') except OSError: raise OSError('Error running: %s' % ' '.join(cmd)) rem = rem.splitlines() for (fileinfo, line) in zip(rem[::2], rem[1::2]): fileinfo = fileinfo.split() src_filename = fileinfo[3] if src_filename not in files: # There is a race condition with the remind call above here. # This could be solved by parsing the remind -de output, # but I don't see an easy way to do that. files[src_filename] = open(src_filename).readlines() reminders[src_filename] = {} mtime = getmtime(src_filename) if mtime > self._mtime: self._mtime = mtime text = files[src_filename][int(fileinfo[2]) - 1] event = self._parse_remind_line(line, text) if event['uid'] in reminders[src_filename]: reminders[src_filename][event['uid']]['dtstart'] += event['dtstart'] reminders[src_filename][event['uid']]['line'] += line else: reminders[src_filename][event['uid']] = event reminders[src_filename][event['uid']]['line'] = line # Find included files without reminders and add them to the file list for source in files.values(): for line in source: if line.startswith('include'): new_file = line.split(' ')[1].strip() if new_file not in reminders: reminders[new_file] = {} mtime = getmtime(new_file) if mtime > self._mtime: self._mtime = mtime return reminders @staticmethod def _gen_description(text): """Convert from Remind MSG to iCal description Opposite of _gen_msg() """ return text[text.rfind('%"') + 3:].replace('%_', '\n').replace('["["]', '[').strip() def _parse_remind_line(self, line, text): """Parse a line of remind output into a dict line -- the remind output text -- the original remind input """ event = {} line = line.split(None, 6) dat = [int(f) for f in line[0].split('/')] if line[4] != '*': start = divmod(int(line[4]), 60) event['dtstart'] = [datetime(dat[0], dat[1], dat[2], start[0], start[1], tzinfo=self._localtz)] if line[3] != '*': event['duration'] = timedelta(minutes=int(line[3])) else: event['dtstart'] = [date(dat[0], dat[1], dat[2])] msg = ' '.join(line[5:]) if line[4] == '*' else line[6] msg = msg.strip().replace('%_', '\n').replace('["["]', '[') if ' at ' in msg: (event['msg'], event['location']) = msg.rsplit(' at ', 1) else: event['msg'] = msg if '%"' in text: event['description'] = Remind._gen_description(text) tags = line[2].split(',') classes = ['PUBLIC', 'PRIVATE', 'CONFIDENTIAL'] for tag in tags[:-1]: if tag in classes: event['class'] = tag event['categories'] = [tag for tag in tags[:-1] if tag not in classes] event['uid'] = '%s@%s' % (tags[-1][7:], getfqdn()) return event @staticmethod def _interval(dates): """Return the distance between all dates and 0 if they are different""" interval = (dates[1] - dates[0]).days last = dates[0] for dat in dates[1:]: if (dat - last).days != interval: return 0 last = dat return interval @staticmethod def _gen_dtend_rrule(dtstarts, vevent): """Generate an rdate or rrule from a list of dates and add it to the vevent""" interval = Remind._interval(dtstarts) if interval > 0 and interval % 7 == 0: rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.WEEKLY, interval=interval // 7, count=len(dtstarts))) vevent.rruleset = rset elif interval > 1: rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.DAILY, interval=interval, count=len(dtstarts))) vevent.rruleset = rset elif interval > 0: if isinstance(dtstarts[0], datetime): rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.DAILY, count=len(dtstarts))) vevent.rruleset = rset else: vevent.add('dtend').value = dtstarts[-1] + timedelta(days=1) else: rset = rrule.rruleset() if isinstance(dtstarts[0], datetime): for dat in dtstarts: rset.rdate(dat) else: for dat in dtstarts: rset.rdate(datetime(dat.year, dat.month, dat.day)) # temporary set dtstart to a different date, so it's not # removed from rset by python-vobject works around bug in # Android: # https://github.com/rfc2822/davdroid/issues/340 vevent.dtstart.value = dtstarts[0] - timedelta(days=1) vevent.rruleset = rset vevent.dtstart.value = dtstarts[0] if not isinstance(dtstarts[0], datetime): vevent.add('dtend').value = dtstarts[0] + timedelta(days=1) def _gen_vevent(self, event, vevent): """Generate vevent from given event""" vevent.add('dtstart').value = event['dtstart'][0] vevent.add('dtstamp').value = datetime.fromtimestamp(self._mtime) vevent.add('summary').value = event['msg'] vevent.add('uid').value = event['uid'] if 'class' in event: vevent.add('class').value = event['class'] if 'categories' in event and len(event['categories']) > 0: vevent.add('categories').value = event['categories'] if 'location' in event: vevent.add('location').value = event['location'] if 'description' in event: vevent.add('description').value = event['description'] if isinstance(event['dtstart'][0], datetime): if self._alarm != timedelta(): valarm = vevent.add('valarm') valarm.add('trigger').value = self._alarm valarm.add('action').value = 'DISPLAY' valarm.add('description').value = event['msg'] if 'duration' in event: vevent.add('duration').value = event['duration'] else: vevent.add('dtend').value = event['dtstart'][0] elif len(event['dtstart']) == 1: vevent.add('dtend').value = event['dtstart'][0] + timedelta(days=1) if len(event['dtstart']) > 1: Remind._gen_dtend_rrule(event['dtstart'], vevent) def _update(self): """Reload Remind files if the mtime is newer""" update = not self._reminders with self._lock: for fname in self._reminders: if getmtime(fname) > self._mtime: update = True break if update: self._reminders = self._parse_remind(self._filename) def get_filesnames(self): """All filenames parsed by remind (including included files)""" self._update() return list(self._reminders.keys()) @staticmethod def _get_uid(line): """UID of a remind line""" return '%s@%s' % (md5(line[:-1].encode('utf-8')).hexdigest(), getfqdn()) def get_uids(self, filename=None): """UIDs of all reminders in the file excluding included files If a filename is specified, only it's UIDs are return, otherwise all. filename -- the remind file """ self._update() if filename: if filename not in self._reminders: return [] return self._reminders[filename].keys() return [uid for uids in self._reminders.values() for uid in uids] def to_vobject_etag(self, filename, uid): """Return iCal object and etag of one Remind entry filename -- the remind file uid -- the UID of the Remind line """ return self.to_vobjects(filename, [uid])[0][1:3] def to_vobjects(self, filename, uids=None): """Return iCal objects and etags of all Remind entries in uids filename -- the remind file uids -- the UIDs of the Remind lines (all if None) """ self._update() if not uids: uids = self._reminders[filename] items = [] for uid in uids: cal = iCalendar() self._gen_vevent(self._reminders[filename][uid], cal.add('vevent')) etag = md5() etag.update(self._reminders[filename][uid]['line'].encode("utf-8")) items.append((uid, cal, '"%s"' % etag.hexdigest())) return items def to_vobject(self, filename=None, uid=None): """Return iCal object of Remind lines If filename and UID are specified, the vObject only contains that event. If only a filename is specified, the vObject contains all events in the file. Otherwise the vObject contains all all objects of all files associated with the Remind object. filename -- the remind file uid -- the UID of the Remind line """ self._update() cal = iCalendar() if uid: self._gen_vevent(self._reminders[filename][uid], cal.add('vevent')) elif filename: for event in self._reminders[filename].values(): self._gen_vevent(event, cal.add('vevent')) else: for filename in self._reminders: for event in self._reminders[filename].values(): self._gen_vevent(event, cal.add('vevent')) return cal def stdin_to_vobject(self, lines): """Return iCal object of the Remind commands in lines""" cal = iCalendar() for event in self._parse_remind('-', lines)['-'].values(): self._gen_vevent(event, cal.add('vevent')) return cal @staticmethod def _parse_rdate(rdates): """Convert from iCal rdate to Remind trigdate syntax""" trigdates = [rdate.strftime("trigdate()=='%Y-%m-%d'") for rdate in rdates] return 'SATISFY [%s]' % '||'.join(trigdates) @staticmethod def _parse_rruleset(rruleset): """Convert from iCal rrule to Remind recurrence syntax""" # pylint: disable=protected-access if rruleset._rrule[0]._freq == 0: return [] rep = [] if rruleset._rrule[0]._byweekday and len(rruleset._rrule[0]._byweekday) > 1: rep.append('*1') elif rruleset._rrule[0]._freq == rrule.DAILY: rep.append('*%d' % rruleset._rrule[0]._interval) elif rruleset._rrule[0]._freq == rrule.WEEKLY: rep.append('*%d' % (7 * rruleset._rrule[0]._interval)) else: return Remind._parse_rdate(rruleset._rrule[0]) if rruleset._rrule[0]._byweekday and len(rruleset._rrule[0]._byweekday) > 1: daynums = set(range(7)) - set(rruleset._rrule[0]._byweekday) weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] days = [weekdays[day] for day in daynums] rep.append('SKIP OMIT %s' % ' '.join(days)) if rruleset._rrule[0]._until: rep.append(rruleset._rrule[0]._until.strftime('UNTIL %b %d %Y').replace(' 0', ' ')) elif rruleset._rrule[0]._count: rep.append(rruleset[-1].strftime('UNTIL %b %d %Y').replace(' 0', ' ')) return rep @staticmethod def _event_duration(vevent): """unify dtend and duration to the duration of the given vevent""" if hasattr(vevent, 'dtend'): return vevent.dtend.value - vevent.dtstart.value elif hasattr(vevent, 'duration') and vevent.duration.value: return vevent.duration.value return timedelta(0) @staticmethod def _gen_msg(vevent, label, tail, sep): """Generate a Remind MSG from the given vevent. Opposite of _gen_description() """ rem = ['MSG'] msg = [] if label: msg.append(label) if hasattr(vevent, 'summary') and vevent.summary.value: msg.append(Remind._rem_clean(vevent.summary.value)) else: msg.append('empty reminder') if hasattr(vevent, 'location') and vevent.location.value: msg.append('at %s' % Remind._rem_clean(vevent.location.value)) has_desc = hasattr(vevent, 'description') and vevent.description.value if tail or has_desc: rem.append('%%"%s%%"' % ' '.join(msg)) else: rem.append(' '.join(msg)) if tail: rem.append(tail) if has_desc: rem[-1] += sep + Remind._rem_clean(vevent.description.value) return ' '.join(rem) @staticmethod def _rem_clean(rem): """Strip, transform newlines, and escape '[' in string so it's acceptable as a remind entry.""" return rem.strip().replace('\n', '%_').replace('[', '["["]') @staticmethod def _abbr_tag(tag): """Transform a string so it's acceptable as a remind tag. """ return tag.replace(" ", "")[:48] def to_remind(self, vevent, label=None, priority=None, tags=None, tail=None, sep=" ", postdate=None, posttime=None): """Generate a Remind command from the given vevent""" remind = ['REM'] trigdates = None if hasattr(vevent, 'rrule'): trigdates = Remind._parse_rruleset(vevent.rruleset) dtstart = vevent.dtstart.value # If we don't get timezone information, handle it as a naive datetime. # See https://github.com/jspricke/python-remind/issues/2 for reference. if isinstance(dtstart, datetime) and dtstart.tzinfo: dtstart = dtstart.astimezone(self._localtz) dtend = None if hasattr(vevent, 'dtend'): dtend = vevent.dtend.value if isinstance(dtend, datetime) and dtend.tzinfo: dtend = dtend.astimezone(self._localtz) if not hasattr(vevent, 'rdate') and not isinstance(trigdates, str): remind.append(dtstart.strftime('%b %d %Y').replace(' 0', ' ')) if postdate: remind.append(postdate) if priority: remind.append('PRIORITY %s' % priority) if isinstance(trigdates, list): remind.extend(trigdates) duration = Remind._event_duration(vevent) if type(dtstart) is date and duration.days > 1: remind.append('*1') if dtend is not None: dtend -= timedelta(days=1) remind.append(dtend.strftime('UNTIL %b %d %Y').replace(' 0', ' ')) if isinstance(dtstart, datetime): remind.append(dtstart.strftime('AT %H:%M').replace(' 0', ' ')) if posttime: remind.append(posttime) if duration.total_seconds() > 0: remind.append('DURATION %d:%02d' % divmod(duration.total_seconds() / 60, 60)) if hasattr(vevent, 'rdate'): remind.append(Remind._parse_rdate(vevent.rdate.value)) elif isinstance(trigdates, str): remind.append(trigdates) if hasattr(vevent, 'class'): remind.append('TAG %s' % Remind._abbr_tag(vevent.getChildValue('class'))) if tags: remind.extend(['TAG %s' % Remind._abbr_tag(tag) for tag in tags]) if hasattr(vevent, 'categories_list'): for categories in vevent.categories_list: for category in categories.value: remind.append('TAG %s' % Remind._abbr_tag(category)) remind.append(Remind._gen_msg(vevent, label, tail, sep)) return ' '.join(remind) + '\n' def to_reminders(self, ical, label=None, priority=None, tags=None, tail=None, sep=" ", postdate=None, posttime=None): """Return Remind commands for all events of a iCalendar""" if not hasattr(ical, 'vevent_list'): return '' reminders = [self.to_remind(vevent, label, priority, tags, tail, sep, postdate, posttime) for vevent in ical.vevent_list] return ''.join(reminders) def append(self, ical, filename=None): """Append a Remind command generated from the iCalendar to the file""" return self.append_vobject(readOne(ical), filename) def append_vobject(self, ical, filename=None): """Append a Remind command generated from the iCalendar to the file""" if not filename: filename = self._filename elif filename not in self._reminders: return with self._lock: outdat = self.to_reminders(ical) open(filename, 'a').write(outdat) return Remind._get_uid(outdat) def remove(self, uid, filename=None): """Remove the Remind command with the uid from the file""" if not filename: filename = self._filename elif filename not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(filename).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): del rem[index] open(filename, 'w').writelines(rem) break def replace(self, uid, ical, filename=None): """Update the Remind command with the uid in the file with the new iCalendar""" return self.replace_vobject(uid, readOne(ical), filename) def replace_vobject(self, uid, ical, filename=None): """Update the Remind command with the uid in the file with the new iCalendar""" if not filename: filename = self._filename elif filename not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(filename).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): rem[index] = self.to_reminders(ical) new_uid = self._get_uid(rem[index]) open(filename, 'w').writelines(rem) return new_uid def get_meta(self): """Meta tags of the vObject collection""" return {'tag': 'VCALENDAR', 'C:supported-calendar-component-set': 'VEVENT'} def last_modified(self): """Last time the Remind files where parsed""" self._update() return self._mtime
tropo/tropo-webapi-python
samples/appengine/main.py
HelloWorld
python
def HelloWorld(handler, t): t.say (["Hello, World", "How ya doing?"]) json = t.RenderJson() logging.info ("HelloWorld json: %s" % json) handler.response.out.write(json)
This is the traditional "Hello, World" function. The idiom is used throughout the API. We construct a Tropo object, and then flesh out that object by calling "action" functions (in this case, tropo.say). Then call tropo.Render, which translates the Tropo object into JSON format. Finally, we write the JSON object to the standard output, so that it will get POSTed back to the API.
train
https://github.com/tropo/tropo-webapi-python/blob/f87772644a6b45066a4c5218f0c1f6467b64ab3c/samples/appengine/main.py#L19-L26
null
""" This script is intended to be used with Google Appengine. It contains a number of demos that illustrate the Tropo Web API for Python. """ from google.appengine.ext import webapp from google.appengine.ext.webapp import util import cgi import logging import tropo import GoogleS3 from xml.dom import minidom from google.appengine.api import urlfetch from xml.etree import ElementTree from setup import * def WeatherDemo(handler, t): """ """ choices = tropo.Choices("[5 DIGITS]") t.ask(choices, say="Please enter your 5 digit zip code.", attempts=3, bargein=True, name="zip", timeout=5, voice="dave") t.on(event="continue", next="/weather.py?uri=end", say="Please hold.") t.on(event="error", next="/weather.py?uri=error", say="Ann error occurred.") json = t.RenderJson() logging.info ("Json result: %s " % json) logging.info ("WeatherDemo json: %s" % json) handler.response.out.write(json) def RecordDemo(handler, t): url = "%s/receive_recording.py" % THIS_URL choices_obj = tropo.Choices("", terminator="#").json t.record(say="Tell us about yourself", url=url, choices=choices_obj) json = t.RenderJson() logging.info ("Json result: %s " % json) handler.response.out.write(json) def SMSDemo(handler, t): t.message("Hello World", MY_PHONE, channel='TEXT', network='SMS', timeout=5) json = t.RenderJson() logging.info ("Json result: %s " % json) handler.response.out.write(json) def RecordHelloWorld(handler, t): """ Demonstration of recording a message. """ url = "%s/receive_recording.py" % THIS_URL t.startRecording(url) t.say ("Hello, World.") t.stopRecording() json = t.RenderJson() logging.info ("RecordHelloWorld json: %s" % json) handler.response.out.write(json) def RedirectDemo(handler, t): """ Demonstration of redirecting to another number. """ # t.say ("One moment please.") t.redirect(SIP_PHONE) json = t.RenderJson() logging.info ("RedirectDemo json: %s" % json) handler.response.out.write(json) def TransferDemo(handler, t): """ Demonstration of transfering to another number """ t.say ("One moment please.") t.transfer(MY_PHONE) t.say("Hi. I am a robot") json = t.RenderJson() logging.info ("TransferDemo json: %s" % json) handler.response.out.write(json) def CallDemo(handler, t): t.call(THEIR_PHONE) json = t.RenderJson() logging.info ("CallDemo json: %s " % json) handler.response.out.write(json) def ConferenceDemo(handler, t): t.say ("Have some of your friends launch this demo. You'll be on the world's simplest conference call.") t.conference("partyline", terminator="#", name="Family Meeting") json = t.RenderJson() logging.info ("ConferenceDemo json: %s " % json) handler.response.out.write(json) # List of Demos DEMOS = { '1' : ('Hello World', HelloWorld), '2' : ('Weather Demo', WeatherDemo), '3' : ('Record Demo', RecordDemo), '4' : ('SMS Demo', SMSDemo), '5' : ('Record Conversation Demo', RecordHelloWorld), '6' : ('Redirect Demo', RedirectDemo), '7' : ('Transfer Demo', TransferDemo), '8' : ('Call Demo', CallDemo), '9' : ('Conference Demo', ConferenceDemo) } class TropoDemo(webapp.RequestHandler): """ This class is the entry point to the Tropo Web API for Python demos. Note that it's only method is a POST method, since this is how Tropo kicks off. A bundle of information about the call, such as who is calling, is passed in via the POST data. """ def post(self): t = tropo.Tropo() t.say ("Welcome to the Tropo web API demo") request = "Please press" choices_string = "" choices_counter = 1 for key in sorted(DEMOS.iterkeys()): if (len(choices_string) > 0): choices_string = "%s,%s" % (choices_string, choices_counter) else: choices_string = "%s" % (choices_counter) demo_name = DEMOS[key][0] demo = DEMOS[key][1] request = "%s %s for %s," % (request, key, demo_name) choices_counter += 1 choices = tropo.Choices(choices_string) t.ask(choices, say=request, attempts=3, bargein=True, name="zip", timeout=5, voice="dave") t.on(event="continue", next="/demo_continue.py", say="Please hold.") t.on(event="error", next="/demo_continue.py", say="An error occurred.") json = t.RenderJson() logging.info ("Json result: %s " % json) self.response.out.write(json) class TropoDemoContinue(webapp.RequestHandler): """ This class implements all the top-level demo functions. Data is POSTed to the application, to start tings off. After retrieving the result value, which is a digit indicating the user's choice of demo function, the POST method dispatches to the chosen demo. """ def post (self): json = self.request.body logging.info ("json: %s" % json) t = tropo.Tropo() result = tropo.Result(json) choice = result.getValue() logging.info ("Choice of demo is: %s" % choice) for key in DEMOS: if (choice == key): demo_name = DEMOS[key][0] demo = DEMOS[key][1] demo(self, t) break class Weather(webapp.RequestHandler): def post (self): json = self.request.body logging.info ("json: %s" % json) uri = self.request.get ('uri') logging.info ("uri: %s" % uri) t = tropo.Tropo() if (uri == "error"): t.say ("Oops. There was some kind of error") json = t.RenderJson() self.response.out.write(json) return result = tropo.Result(json); zip = result.getValue() google_weather_url = "%s?weather=%s&hl=en" % (GOOGLE_WEATHER_API_URL, zip) resp = urlfetch.fetch(google_weather_url) logging.info ("weather url: %s " % google_weather_url) if (resp.status_code == 200): xml = resp.content logging.info ("weather xml: %s " % xml) doc = ElementTree.fromstring(xml) logging.info ("doc: %s " % doc) condition = doc.find("weather/current_conditions/condition").attrib['data'] temp_f = doc.find("weather/current_conditions/temp_f").attrib['data'] wind_condition = doc.find("weather/current_conditions/wind_condition").attrib['data'] city = doc.find("weather/forecast_information/city").attrib['data'] logging.info ("condition: %s temp_f: %s wind_condition: %s city: %s" % (condition, temp_f, wind_condition, city)) t = tropo.Tropo() # condition: Partly Cloudy temp_f: 73 wind_condition: Wind: NW at 10 mph city: Portsmouth, NH temp = "%s degrees" % temp_f wind = self.english_expand (wind_condition) t.say("Current city is %s . Weather conditions are %s. Temperature is %s. %s ." % (city, condition, temp, wind)) json = t.RenderJson() self.response.out.write(json) # Wind: N at 0 mph def english_expand(self, expr): logging.info ("expr is : %s" % expr) expr = expr.replace("Wind: NW", "Wind is from the North West") expr = expr.replace("Wind: NE", "Wind is from the North East") expr = expr.replace("Wind: N", "Wind is from the North") expr = expr.replace("Wind: SW", "Wind is from the South West") expr = expr.replace("Wind: SE", "Wind is from the South East") expr = expr.replace("Wind: S", "Wind is from the South") expr = expr.replace("mph", "miles per hour") return expr class ReceiveRecording(webapp.RequestHandler): def post(self): logging.info ("I just received a post recording") # wav = self.request.body wav = self.request.get ('filename') logging.info ("Just got the wav as %s" % wav) self.put_in_s3(wav) logging.info ("I just put the wav in s3") def put_in_s3 (self, wav): conn = GoogleS3.AWSAuthConnection(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) key_name = "testing.wav" logging.info ("Putting content in %s in %s bucket" % (key_name, S3_BUCKET_NAME)) responsedict={} logging.info ("really putting stuff in %s %s" % (S3_BUCKET_NAME, key_name)) audio_type = 'audio/wav' response = conn.put( S3_BUCKET_NAME, key_name, GoogleS3.S3Object(wav), {'Content-Type' : audio_type, 'x-amz-acl' : 'public-read'}) responsedict["response"] = response responsedict["url"] = "%s/%s/%s" % (AMAZON_S3_URL, S3_BUCKET_NAME, key_name) return responsedict class CallWorld(webapp.RequestHandler): def post(self): t = tropo.Tropo() t.call(MY_PHONE, channel='TEXT', network='SMS', answerOnMedia='True') t.say ("Wish you were here") json = t.RenderJson() logging.info ("Json result: %s " % json) self.response.out.write(json) class MainHandler(webapp.RequestHandler): def get(self): self.response.out.write('Hello world!') def main(): application = webapp.WSGIApplication([('/', MainHandler), ('/hello_tropo.py', TropoDemo), ('/weather.py', Weather), ('/receive_recording.py', ReceiveRecording), ('/demo_continue.py', TropoDemoContinue), # ('/tropo_web_api.html', ShowDoc) ], debug=True) util.run_wsgi_app(application) if __name__ == '__main__': main()
tropo/tropo-webapi-python
samples/appengine/main.py
RecordHelloWorld
python
def RecordHelloWorld(handler, t): url = "%s/receive_recording.py" % THIS_URL t.startRecording(url) t.say ("Hello, World.") t.stopRecording() json = t.RenderJson() logging.info ("RecordHelloWorld json: %s" % json) handler.response.out.write(json)
Demonstration of recording a message.
train
https://github.com/tropo/tropo-webapi-python/blob/f87772644a6b45066a4c5218f0c1f6467b64ab3c/samples/appengine/main.py#L69-L79
null
""" This script is intended to be used with Google Appengine. It contains a number of demos that illustrate the Tropo Web API for Python. """ from google.appengine.ext import webapp from google.appengine.ext.webapp import util import cgi import logging import tropo import GoogleS3 from xml.dom import minidom from google.appengine.api import urlfetch from xml.etree import ElementTree from setup import * def HelloWorld(handler, t): """ This is the traditional "Hello, World" function. The idiom is used throughout the API. We construct a Tropo object, and then flesh out that object by calling "action" functions (in this case, tropo.say). Then call tropo.Render, which translates the Tropo object into JSON format. Finally, we write the JSON object to the standard output, so that it will get POSTed back to the API. """ t.say (["Hello, World", "How ya doing?"]) json = t.RenderJson() logging.info ("HelloWorld json: %s" % json) handler.response.out.write(json) def WeatherDemo(handler, t): """ """ choices = tropo.Choices("[5 DIGITS]") t.ask(choices, say="Please enter your 5 digit zip code.", attempts=3, bargein=True, name="zip", timeout=5, voice="dave") t.on(event="continue", next="/weather.py?uri=end", say="Please hold.") t.on(event="error", next="/weather.py?uri=error", say="Ann error occurred.") json = t.RenderJson() logging.info ("Json result: %s " % json) logging.info ("WeatherDemo json: %s" % json) handler.response.out.write(json) def RecordDemo(handler, t): url = "%s/receive_recording.py" % THIS_URL choices_obj = tropo.Choices("", terminator="#").json t.record(say="Tell us about yourself", url=url, choices=choices_obj) json = t.RenderJson() logging.info ("Json result: %s " % json) handler.response.out.write(json) def SMSDemo(handler, t): t.message("Hello World", MY_PHONE, channel='TEXT', network='SMS', timeout=5) json = t.RenderJson() logging.info ("Json result: %s " % json) handler.response.out.write(json) def RedirectDemo(handler, t): """ Demonstration of redirecting to another number. """ # t.say ("One moment please.") t.redirect(SIP_PHONE) json = t.RenderJson() logging.info ("RedirectDemo json: %s" % json) handler.response.out.write(json) def TransferDemo(handler, t): """ Demonstration of transfering to another number """ t.say ("One moment please.") t.transfer(MY_PHONE) t.say("Hi. I am a robot") json = t.RenderJson() logging.info ("TransferDemo json: %s" % json) handler.response.out.write(json) def CallDemo(handler, t): t.call(THEIR_PHONE) json = t.RenderJson() logging.info ("CallDemo json: %s " % json) handler.response.out.write(json) def ConferenceDemo(handler, t): t.say ("Have some of your friends launch this demo. You'll be on the world's simplest conference call.") t.conference("partyline", terminator="#", name="Family Meeting") json = t.RenderJson() logging.info ("ConferenceDemo json: %s " % json) handler.response.out.write(json) # List of Demos DEMOS = { '1' : ('Hello World', HelloWorld), '2' : ('Weather Demo', WeatherDemo), '3' : ('Record Demo', RecordDemo), '4' : ('SMS Demo', SMSDemo), '5' : ('Record Conversation Demo', RecordHelloWorld), '6' : ('Redirect Demo', RedirectDemo), '7' : ('Transfer Demo', TransferDemo), '8' : ('Call Demo', CallDemo), '9' : ('Conference Demo', ConferenceDemo) } class TropoDemo(webapp.RequestHandler): """ This class is the entry point to the Tropo Web API for Python demos. Note that it's only method is a POST method, since this is how Tropo kicks off. A bundle of information about the call, such as who is calling, is passed in via the POST data. """ def post(self): t = tropo.Tropo() t.say ("Welcome to the Tropo web API demo") request = "Please press" choices_string = "" choices_counter = 1 for key in sorted(DEMOS.iterkeys()): if (len(choices_string) > 0): choices_string = "%s,%s" % (choices_string, choices_counter) else: choices_string = "%s" % (choices_counter) demo_name = DEMOS[key][0] demo = DEMOS[key][1] request = "%s %s for %s," % (request, key, demo_name) choices_counter += 1 choices = tropo.Choices(choices_string) t.ask(choices, say=request, attempts=3, bargein=True, name="zip", timeout=5, voice="dave") t.on(event="continue", next="/demo_continue.py", say="Please hold.") t.on(event="error", next="/demo_continue.py", say="An error occurred.") json = t.RenderJson() logging.info ("Json result: %s " % json) self.response.out.write(json) class TropoDemoContinue(webapp.RequestHandler): """ This class implements all the top-level demo functions. Data is POSTed to the application, to start tings off. After retrieving the result value, which is a digit indicating the user's choice of demo function, the POST method dispatches to the chosen demo. """ def post (self): json = self.request.body logging.info ("json: %s" % json) t = tropo.Tropo() result = tropo.Result(json) choice = result.getValue() logging.info ("Choice of demo is: %s" % choice) for key in DEMOS: if (choice == key): demo_name = DEMOS[key][0] demo = DEMOS[key][1] demo(self, t) break class Weather(webapp.RequestHandler): def post (self): json = self.request.body logging.info ("json: %s" % json) uri = self.request.get ('uri') logging.info ("uri: %s" % uri) t = tropo.Tropo() if (uri == "error"): t.say ("Oops. There was some kind of error") json = t.RenderJson() self.response.out.write(json) return result = tropo.Result(json); zip = result.getValue() google_weather_url = "%s?weather=%s&hl=en" % (GOOGLE_WEATHER_API_URL, zip) resp = urlfetch.fetch(google_weather_url) logging.info ("weather url: %s " % google_weather_url) if (resp.status_code == 200): xml = resp.content logging.info ("weather xml: %s " % xml) doc = ElementTree.fromstring(xml) logging.info ("doc: %s " % doc) condition = doc.find("weather/current_conditions/condition").attrib['data'] temp_f = doc.find("weather/current_conditions/temp_f").attrib['data'] wind_condition = doc.find("weather/current_conditions/wind_condition").attrib['data'] city = doc.find("weather/forecast_information/city").attrib['data'] logging.info ("condition: %s temp_f: %s wind_condition: %s city: %s" % (condition, temp_f, wind_condition, city)) t = tropo.Tropo() # condition: Partly Cloudy temp_f: 73 wind_condition: Wind: NW at 10 mph city: Portsmouth, NH temp = "%s degrees" % temp_f wind = self.english_expand (wind_condition) t.say("Current city is %s . Weather conditions are %s. Temperature is %s. %s ." % (city, condition, temp, wind)) json = t.RenderJson() self.response.out.write(json) # Wind: N at 0 mph def english_expand(self, expr): logging.info ("expr is : %s" % expr) expr = expr.replace("Wind: NW", "Wind is from the North West") expr = expr.replace("Wind: NE", "Wind is from the North East") expr = expr.replace("Wind: N", "Wind is from the North") expr = expr.replace("Wind: SW", "Wind is from the South West") expr = expr.replace("Wind: SE", "Wind is from the South East") expr = expr.replace("Wind: S", "Wind is from the South") expr = expr.replace("mph", "miles per hour") return expr class ReceiveRecording(webapp.RequestHandler): def post(self): logging.info ("I just received a post recording") # wav = self.request.body wav = self.request.get ('filename') logging.info ("Just got the wav as %s" % wav) self.put_in_s3(wav) logging.info ("I just put the wav in s3") def put_in_s3 (self, wav): conn = GoogleS3.AWSAuthConnection(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) key_name = "testing.wav" logging.info ("Putting content in %s in %s bucket" % (key_name, S3_BUCKET_NAME)) responsedict={} logging.info ("really putting stuff in %s %s" % (S3_BUCKET_NAME, key_name)) audio_type = 'audio/wav' response = conn.put( S3_BUCKET_NAME, key_name, GoogleS3.S3Object(wav), {'Content-Type' : audio_type, 'x-amz-acl' : 'public-read'}) responsedict["response"] = response responsedict["url"] = "%s/%s/%s" % (AMAZON_S3_URL, S3_BUCKET_NAME, key_name) return responsedict class CallWorld(webapp.RequestHandler): def post(self): t = tropo.Tropo() t.call(MY_PHONE, channel='TEXT', network='SMS', answerOnMedia='True') t.say ("Wish you were here") json = t.RenderJson() logging.info ("Json result: %s " % json) self.response.out.write(json) class MainHandler(webapp.RequestHandler): def get(self): self.response.out.write('Hello world!') def main(): application = webapp.WSGIApplication([('/', MainHandler), ('/hello_tropo.py', TropoDemo), ('/weather.py', Weather), ('/receive_recording.py', ReceiveRecording), ('/demo_continue.py', TropoDemoContinue), # ('/tropo_web_api.html', ShowDoc) ], debug=True) util.run_wsgi_app(application) if __name__ == '__main__': main()
tropo/tropo-webapi-python
samples/appengine/main.py
RedirectDemo
python
def RedirectDemo(handler, t): # t.say ("One moment please.") t.redirect(SIP_PHONE) json = t.RenderJson() logging.info ("RedirectDemo json: %s" % json) handler.response.out.write(json)
Demonstration of redirecting to another number.
train
https://github.com/tropo/tropo-webapi-python/blob/f87772644a6b45066a4c5218f0c1f6467b64ab3c/samples/appengine/main.py#L81-L89
null
""" This script is intended to be used with Google Appengine. It contains a number of demos that illustrate the Tropo Web API for Python. """ from google.appengine.ext import webapp from google.appengine.ext.webapp import util import cgi import logging import tropo import GoogleS3 from xml.dom import minidom from google.appengine.api import urlfetch from xml.etree import ElementTree from setup import * def HelloWorld(handler, t): """ This is the traditional "Hello, World" function. The idiom is used throughout the API. We construct a Tropo object, and then flesh out that object by calling "action" functions (in this case, tropo.say). Then call tropo.Render, which translates the Tropo object into JSON format. Finally, we write the JSON object to the standard output, so that it will get POSTed back to the API. """ t.say (["Hello, World", "How ya doing?"]) json = t.RenderJson() logging.info ("HelloWorld json: %s" % json) handler.response.out.write(json) def WeatherDemo(handler, t): """ """ choices = tropo.Choices("[5 DIGITS]") t.ask(choices, say="Please enter your 5 digit zip code.", attempts=3, bargein=True, name="zip", timeout=5, voice="dave") t.on(event="continue", next="/weather.py?uri=end", say="Please hold.") t.on(event="error", next="/weather.py?uri=error", say="Ann error occurred.") json = t.RenderJson() logging.info ("Json result: %s " % json) logging.info ("WeatherDemo json: %s" % json) handler.response.out.write(json) def RecordDemo(handler, t): url = "%s/receive_recording.py" % THIS_URL choices_obj = tropo.Choices("", terminator="#").json t.record(say="Tell us about yourself", url=url, choices=choices_obj) json = t.RenderJson() logging.info ("Json result: %s " % json) handler.response.out.write(json) def SMSDemo(handler, t): t.message("Hello World", MY_PHONE, channel='TEXT', network='SMS', timeout=5) json = t.RenderJson() logging.info ("Json result: %s " % json) handler.response.out.write(json) def RecordHelloWorld(handler, t): """ Demonstration of recording a message. """ url = "%s/receive_recording.py" % THIS_URL t.startRecording(url) t.say ("Hello, World.") t.stopRecording() json = t.RenderJson() logging.info ("RecordHelloWorld json: %s" % json) handler.response.out.write(json) def TransferDemo(handler, t): """ Demonstration of transfering to another number """ t.say ("One moment please.") t.transfer(MY_PHONE) t.say("Hi. I am a robot") json = t.RenderJson() logging.info ("TransferDemo json: %s" % json) handler.response.out.write(json) def CallDemo(handler, t): t.call(THEIR_PHONE) json = t.RenderJson() logging.info ("CallDemo json: %s " % json) handler.response.out.write(json) def ConferenceDemo(handler, t): t.say ("Have some of your friends launch this demo. You'll be on the world's simplest conference call.") t.conference("partyline", terminator="#", name="Family Meeting") json = t.RenderJson() logging.info ("ConferenceDemo json: %s " % json) handler.response.out.write(json) # List of Demos DEMOS = { '1' : ('Hello World', HelloWorld), '2' : ('Weather Demo', WeatherDemo), '3' : ('Record Demo', RecordDemo), '4' : ('SMS Demo', SMSDemo), '5' : ('Record Conversation Demo', RecordHelloWorld), '6' : ('Redirect Demo', RedirectDemo), '7' : ('Transfer Demo', TransferDemo), '8' : ('Call Demo', CallDemo), '9' : ('Conference Demo', ConferenceDemo) } class TropoDemo(webapp.RequestHandler): """ This class is the entry point to the Tropo Web API for Python demos. Note that it's only method is a POST method, since this is how Tropo kicks off. A bundle of information about the call, such as who is calling, is passed in via the POST data. """ def post(self): t = tropo.Tropo() t.say ("Welcome to the Tropo web API demo") request = "Please press" choices_string = "" choices_counter = 1 for key in sorted(DEMOS.iterkeys()): if (len(choices_string) > 0): choices_string = "%s,%s" % (choices_string, choices_counter) else: choices_string = "%s" % (choices_counter) demo_name = DEMOS[key][0] demo = DEMOS[key][1] request = "%s %s for %s," % (request, key, demo_name) choices_counter += 1 choices = tropo.Choices(choices_string) t.ask(choices, say=request, attempts=3, bargein=True, name="zip", timeout=5, voice="dave") t.on(event="continue", next="/demo_continue.py", say="Please hold.") t.on(event="error", next="/demo_continue.py", say="An error occurred.") json = t.RenderJson() logging.info ("Json result: %s " % json) self.response.out.write(json) class TropoDemoContinue(webapp.RequestHandler): """ This class implements all the top-level demo functions. Data is POSTed to the application, to start tings off. After retrieving the result value, which is a digit indicating the user's choice of demo function, the POST method dispatches to the chosen demo. """ def post (self): json = self.request.body logging.info ("json: %s" % json) t = tropo.Tropo() result = tropo.Result(json) choice = result.getValue() logging.info ("Choice of demo is: %s" % choice) for key in DEMOS: if (choice == key): demo_name = DEMOS[key][0] demo = DEMOS[key][1] demo(self, t) break class Weather(webapp.RequestHandler): def post (self): json = self.request.body logging.info ("json: %s" % json) uri = self.request.get ('uri') logging.info ("uri: %s" % uri) t = tropo.Tropo() if (uri == "error"): t.say ("Oops. There was some kind of error") json = t.RenderJson() self.response.out.write(json) return result = tropo.Result(json); zip = result.getValue() google_weather_url = "%s?weather=%s&hl=en" % (GOOGLE_WEATHER_API_URL, zip) resp = urlfetch.fetch(google_weather_url) logging.info ("weather url: %s " % google_weather_url) if (resp.status_code == 200): xml = resp.content logging.info ("weather xml: %s " % xml) doc = ElementTree.fromstring(xml) logging.info ("doc: %s " % doc) condition = doc.find("weather/current_conditions/condition").attrib['data'] temp_f = doc.find("weather/current_conditions/temp_f").attrib['data'] wind_condition = doc.find("weather/current_conditions/wind_condition").attrib['data'] city = doc.find("weather/forecast_information/city").attrib['data'] logging.info ("condition: %s temp_f: %s wind_condition: %s city: %s" % (condition, temp_f, wind_condition, city)) t = tropo.Tropo() # condition: Partly Cloudy temp_f: 73 wind_condition: Wind: NW at 10 mph city: Portsmouth, NH temp = "%s degrees" % temp_f wind = self.english_expand (wind_condition) t.say("Current city is %s . Weather conditions are %s. Temperature is %s. %s ." % (city, condition, temp, wind)) json = t.RenderJson() self.response.out.write(json) # Wind: N at 0 mph def english_expand(self, expr): logging.info ("expr is : %s" % expr) expr = expr.replace("Wind: NW", "Wind is from the North West") expr = expr.replace("Wind: NE", "Wind is from the North East") expr = expr.replace("Wind: N", "Wind is from the North") expr = expr.replace("Wind: SW", "Wind is from the South West") expr = expr.replace("Wind: SE", "Wind is from the South East") expr = expr.replace("Wind: S", "Wind is from the South") expr = expr.replace("mph", "miles per hour") return expr class ReceiveRecording(webapp.RequestHandler): def post(self): logging.info ("I just received a post recording") # wav = self.request.body wav = self.request.get ('filename') logging.info ("Just got the wav as %s" % wav) self.put_in_s3(wav) logging.info ("I just put the wav in s3") def put_in_s3 (self, wav): conn = GoogleS3.AWSAuthConnection(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) key_name = "testing.wav" logging.info ("Putting content in %s in %s bucket" % (key_name, S3_BUCKET_NAME)) responsedict={} logging.info ("really putting stuff in %s %s" % (S3_BUCKET_NAME, key_name)) audio_type = 'audio/wav' response = conn.put( S3_BUCKET_NAME, key_name, GoogleS3.S3Object(wav), {'Content-Type' : audio_type, 'x-amz-acl' : 'public-read'}) responsedict["response"] = response responsedict["url"] = "%s/%s/%s" % (AMAZON_S3_URL, S3_BUCKET_NAME, key_name) return responsedict class CallWorld(webapp.RequestHandler): def post(self): t = tropo.Tropo() t.call(MY_PHONE, channel='TEXT', network='SMS', answerOnMedia='True') t.say ("Wish you were here") json = t.RenderJson() logging.info ("Json result: %s " % json) self.response.out.write(json) class MainHandler(webapp.RequestHandler): def get(self): self.response.out.write('Hello world!') def main(): application = webapp.WSGIApplication([('/', MainHandler), ('/hello_tropo.py', TropoDemo), ('/weather.py', Weather), ('/receive_recording.py', ReceiveRecording), ('/demo_continue.py', TropoDemoContinue), # ('/tropo_web_api.html', ShowDoc) ], debug=True) util.run_wsgi_app(application) if __name__ == '__main__': main()
tropo/tropo-webapi-python
samples/appengine/main.py
TransferDemo
python
def TransferDemo(handler, t): t.say ("One moment please.") t.transfer(MY_PHONE) t.say("Hi. I am a robot") json = t.RenderJson() logging.info ("TransferDemo json: %s" % json) handler.response.out.write(json)
Demonstration of transfering to another number
train
https://github.com/tropo/tropo-webapi-python/blob/f87772644a6b45066a4c5218f0c1f6467b64ab3c/samples/appengine/main.py#L91-L100
null
""" This script is intended to be used with Google Appengine. It contains a number of demos that illustrate the Tropo Web API for Python. """ from google.appengine.ext import webapp from google.appengine.ext.webapp import util import cgi import logging import tropo import GoogleS3 from xml.dom import minidom from google.appengine.api import urlfetch from xml.etree import ElementTree from setup import * def HelloWorld(handler, t): """ This is the traditional "Hello, World" function. The idiom is used throughout the API. We construct a Tropo object, and then flesh out that object by calling "action" functions (in this case, tropo.say). Then call tropo.Render, which translates the Tropo object into JSON format. Finally, we write the JSON object to the standard output, so that it will get POSTed back to the API. """ t.say (["Hello, World", "How ya doing?"]) json = t.RenderJson() logging.info ("HelloWorld json: %s" % json) handler.response.out.write(json) def WeatherDemo(handler, t): """ """ choices = tropo.Choices("[5 DIGITS]") t.ask(choices, say="Please enter your 5 digit zip code.", attempts=3, bargein=True, name="zip", timeout=5, voice="dave") t.on(event="continue", next="/weather.py?uri=end", say="Please hold.") t.on(event="error", next="/weather.py?uri=error", say="Ann error occurred.") json = t.RenderJson() logging.info ("Json result: %s " % json) logging.info ("WeatherDemo json: %s" % json) handler.response.out.write(json) def RecordDemo(handler, t): url = "%s/receive_recording.py" % THIS_URL choices_obj = tropo.Choices("", terminator="#").json t.record(say="Tell us about yourself", url=url, choices=choices_obj) json = t.RenderJson() logging.info ("Json result: %s " % json) handler.response.out.write(json) def SMSDemo(handler, t): t.message("Hello World", MY_PHONE, channel='TEXT', network='SMS', timeout=5) json = t.RenderJson() logging.info ("Json result: %s " % json) handler.response.out.write(json) def RecordHelloWorld(handler, t): """ Demonstration of recording a message. """ url = "%s/receive_recording.py" % THIS_URL t.startRecording(url) t.say ("Hello, World.") t.stopRecording() json = t.RenderJson() logging.info ("RecordHelloWorld json: %s" % json) handler.response.out.write(json) def RedirectDemo(handler, t): """ Demonstration of redirecting to another number. """ # t.say ("One moment please.") t.redirect(SIP_PHONE) json = t.RenderJson() logging.info ("RedirectDemo json: %s" % json) handler.response.out.write(json) def CallDemo(handler, t): t.call(THEIR_PHONE) json = t.RenderJson() logging.info ("CallDemo json: %s " % json) handler.response.out.write(json) def ConferenceDemo(handler, t): t.say ("Have some of your friends launch this demo. You'll be on the world's simplest conference call.") t.conference("partyline", terminator="#", name="Family Meeting") json = t.RenderJson() logging.info ("ConferenceDemo json: %s " % json) handler.response.out.write(json) # List of Demos DEMOS = { '1' : ('Hello World', HelloWorld), '2' : ('Weather Demo', WeatherDemo), '3' : ('Record Demo', RecordDemo), '4' : ('SMS Demo', SMSDemo), '5' : ('Record Conversation Demo', RecordHelloWorld), '6' : ('Redirect Demo', RedirectDemo), '7' : ('Transfer Demo', TransferDemo), '8' : ('Call Demo', CallDemo), '9' : ('Conference Demo', ConferenceDemo) } class TropoDemo(webapp.RequestHandler): """ This class is the entry point to the Tropo Web API for Python demos. Note that it's only method is a POST method, since this is how Tropo kicks off. A bundle of information about the call, such as who is calling, is passed in via the POST data. """ def post(self): t = tropo.Tropo() t.say ("Welcome to the Tropo web API demo") request = "Please press" choices_string = "" choices_counter = 1 for key in sorted(DEMOS.iterkeys()): if (len(choices_string) > 0): choices_string = "%s,%s" % (choices_string, choices_counter) else: choices_string = "%s" % (choices_counter) demo_name = DEMOS[key][0] demo = DEMOS[key][1] request = "%s %s for %s," % (request, key, demo_name) choices_counter += 1 choices = tropo.Choices(choices_string) t.ask(choices, say=request, attempts=3, bargein=True, name="zip", timeout=5, voice="dave") t.on(event="continue", next="/demo_continue.py", say="Please hold.") t.on(event="error", next="/demo_continue.py", say="An error occurred.") json = t.RenderJson() logging.info ("Json result: %s " % json) self.response.out.write(json) class TropoDemoContinue(webapp.RequestHandler): """ This class implements all the top-level demo functions. Data is POSTed to the application, to start tings off. After retrieving the result value, which is a digit indicating the user's choice of demo function, the POST method dispatches to the chosen demo. """ def post (self): json = self.request.body logging.info ("json: %s" % json) t = tropo.Tropo() result = tropo.Result(json) choice = result.getValue() logging.info ("Choice of demo is: %s" % choice) for key in DEMOS: if (choice == key): demo_name = DEMOS[key][0] demo = DEMOS[key][1] demo(self, t) break class Weather(webapp.RequestHandler): def post (self): json = self.request.body logging.info ("json: %s" % json) uri = self.request.get ('uri') logging.info ("uri: %s" % uri) t = tropo.Tropo() if (uri == "error"): t.say ("Oops. There was some kind of error") json = t.RenderJson() self.response.out.write(json) return result = tropo.Result(json); zip = result.getValue() google_weather_url = "%s?weather=%s&hl=en" % (GOOGLE_WEATHER_API_URL, zip) resp = urlfetch.fetch(google_weather_url) logging.info ("weather url: %s " % google_weather_url) if (resp.status_code == 200): xml = resp.content logging.info ("weather xml: %s " % xml) doc = ElementTree.fromstring(xml) logging.info ("doc: %s " % doc) condition = doc.find("weather/current_conditions/condition").attrib['data'] temp_f = doc.find("weather/current_conditions/temp_f").attrib['data'] wind_condition = doc.find("weather/current_conditions/wind_condition").attrib['data'] city = doc.find("weather/forecast_information/city").attrib['data'] logging.info ("condition: %s temp_f: %s wind_condition: %s city: %s" % (condition, temp_f, wind_condition, city)) t = tropo.Tropo() # condition: Partly Cloudy temp_f: 73 wind_condition: Wind: NW at 10 mph city: Portsmouth, NH temp = "%s degrees" % temp_f wind = self.english_expand (wind_condition) t.say("Current city is %s . Weather conditions are %s. Temperature is %s. %s ." % (city, condition, temp, wind)) json = t.RenderJson() self.response.out.write(json) # Wind: N at 0 mph def english_expand(self, expr): logging.info ("expr is : %s" % expr) expr = expr.replace("Wind: NW", "Wind is from the North West") expr = expr.replace("Wind: NE", "Wind is from the North East") expr = expr.replace("Wind: N", "Wind is from the North") expr = expr.replace("Wind: SW", "Wind is from the South West") expr = expr.replace("Wind: SE", "Wind is from the South East") expr = expr.replace("Wind: S", "Wind is from the South") expr = expr.replace("mph", "miles per hour") return expr class ReceiveRecording(webapp.RequestHandler): def post(self): logging.info ("I just received a post recording") # wav = self.request.body wav = self.request.get ('filename') logging.info ("Just got the wav as %s" % wav) self.put_in_s3(wav) logging.info ("I just put the wav in s3") def put_in_s3 (self, wav): conn = GoogleS3.AWSAuthConnection(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) key_name = "testing.wav" logging.info ("Putting content in %s in %s bucket" % (key_name, S3_BUCKET_NAME)) responsedict={} logging.info ("really putting stuff in %s %s" % (S3_BUCKET_NAME, key_name)) audio_type = 'audio/wav' response = conn.put( S3_BUCKET_NAME, key_name, GoogleS3.S3Object(wav), {'Content-Type' : audio_type, 'x-amz-acl' : 'public-read'}) responsedict["response"] = response responsedict["url"] = "%s/%s/%s" % (AMAZON_S3_URL, S3_BUCKET_NAME, key_name) return responsedict class CallWorld(webapp.RequestHandler): def post(self): t = tropo.Tropo() t.call(MY_PHONE, channel='TEXT', network='SMS', answerOnMedia='True') t.say ("Wish you were here") json = t.RenderJson() logging.info ("Json result: %s " % json) self.response.out.write(json) class MainHandler(webapp.RequestHandler): def get(self): self.response.out.write('Hello world!') def main(): application = webapp.WSGIApplication([('/', MainHandler), ('/hello_tropo.py', TropoDemo), ('/weather.py', Weather), ('/receive_recording.py', ReceiveRecording), ('/demo_continue.py', TropoDemoContinue), # ('/tropo_web_api.html', ShowDoc) ], debug=True) util.run_wsgi_app(application) if __name__ == '__main__': main()
tropo/tropo-webapi-python
samples/ReceiveSMS.py
index
python
def index(request): session = Session(request.body) print 'request.body begin' print request.body print 'request.body end' t = Tropo() smsContent = session.initialText #t.call(to=session.parameters['callToNumber'], network='SIP') #t.say(session.parameters['message']) #base_url = 'http://192.168.26.21:8080/gateway/sessions' base_url = 'https://api.tropo.com/1.0/sessions' #token = '4c586866434c4c59746f4361796b634477600d49434d434874584d4546496e70536c706749436841476b684371' # Insert your token here Application ID: 301 token = '6c77565670494a6b474f646a5658436b514658724a0055674f4e735041764f665463626b535472616869746768' # Insert your fire-app-with-token.py token here action = 'create' #number = 'sip:xiangjun_yu@10.140.254.55:5678' # change to the Jabber ID to which you want to send the message #number = 'sip:frank@172.16.22.128:5678' # change to the Jabber ID to which you want to send the message #number = '+861891020382' # change to the Jabber ID to which you want to send the message number = '+86134766549249' # change to the Jabber ID to which you want to send the message message = 'redirect by Python content is ' + str(smsContent) params = urlencode([('action', action), ('token', token), ('callToNumber', number), ('message252121', message)]) data = urlopen('%s?%s' % (base_url, params)).read() print 'data is ' print data #return t.RenderJson() return "receive SMS successfully"
t = Tropo() t.call(to="xiangjun_yu@192.168.26.1:5678") t.say("wo shi yi ke xiao xiao cao")
train
https://github.com/tropo/tropo-webapi-python/blob/f87772644a6b45066a4c5218f0c1f6467b64ab3c/samples/ReceiveSMS.py#L11-L42
null
#!/usr/bin/env python from itty import * from tropo import Tropo, Session, JoinPrompt, LeavePrompt from urllib import urlencode from urllib2 import urlopen @post('/index.json') def index(request): session = Session(request.body) print 'request.body begin' print request.body print 'request.body end' t = Tropo() smsContent = session.initialText #t.call(to=session.parameters['callToNumber'], network='SIP') #t.say(session.parameters['message']) """ t = Tropo() t.call(to="xiangjun_yu@192.168.26.1:5678") t.say("wo shi yi ke xiao xiao cao") """ #base_url = 'http://192.168.26.21:8080/gateway/sessions' base_url = 'https://api.tropo.com/1.0/sessions' #token = '4c586866434c4c59746f4361796b634477600d49434d434874584d4546496e70536c706749436841476b684371' # Insert your token here Application ID: 301 token = '6c77565670494a6b474f646a5658436b514658724a0055674f4e735041764f665463626b535472616869746768' # Insert your fire-app-with-token.py token here action = 'create' #number = 'sip:xiangjun_yu@10.140.254.55:5678' # change to the Jabber ID to which you want to send the message #number = 'sip:frank@172.16.22.128:5678' # change to the Jabber ID to which you want to send the message #number = '+861891020382' # change to the Jabber ID to which you want to send the message number = '+86134766549249' # change to the Jabber ID to which you want to send the message message = 'redirect by Python content is ' + str(smsContent) params = urlencode([('action', action), ('token', token), ('callToNumber', number), ('message252121', message)]) data = urlopen('%s?%s' % (base_url, params)).read() print 'data is ' print data #return t.RenderJson() return "receive SMS successfully" run_itty(server='wsgiref', host='192.168.26.1', port=8042) #run_itty(config='sample_conf')
tropo/tropo-webapi-python
tropo.py
Result.getValue
python
def getValue(self): actions = self._actions if (type (actions) is list): dict = actions[0] else: dict = actions return dict.get('value', 'NoValue')
Get the value of the previously POSTed Tropo action.
train
https://github.com/tropo/tropo-webapi-python/blob/f87772644a6b45066a4c5218f0c1f6467b64ab3c/tropo.py#L712-L722
null
class Result(object): """ Returned anytime a request is made to the Tropo Web API. Method: getValue (See https://www.tropo.com/docs/webapi/result) { "result": { "actions": Array or Object, "calledId": String, "callId": String, "complete": Boolean, "connectedDuration": Integer, "duration": Integer, "error": String, "sequence": Integer, "sessionDuration": Integer, "sessionId": String, "state": String, "userType": String} } """ options_array = ['actions','complete','error','sequence', 'sessionDuration', 'sessionId', 'state', 'userType', 'connectedDuration', 'duration', 'calledID', 'callId'] def __init__(self, result_json): result_data = jsonlib.loads(result_json) result_dict = result_data['result'] for opt in self.options_array: if result_dict.get(opt, False): setattr(self, '_%s' % opt, result_dict[opt]) def getActions(self): actions = self._actions return actions def getActionsCount(self): actions = self._actions if actions is None: count = 0 return count if (type (actions) is list): count = len(actions) else: count = 1 return count def getIndexedValue(self, index): """ Get the value of the indexed Tropo action. """ actions = self._actions if (type (actions) is list): dict = actions[index] else: dict = actions return dict.get('value', 'NoValue') def getNamedActionValue(self, name): """ Get the value of the named Tropo action. """ actions = self._actions if (type (actions) is list): for a in actions: if a.get('name', 'NoValue') == name: dict =a else: dict = actions return dict.get('value', 'NoValue') def getUserType(self): """ Get the userType of the previously POSTed Tropo action. """ userType = self._userType return userType # # **Tue May 17 07:17:38 2011** -- egilchri def getInterpretation(self): """ Get the value of the previously POSTed Tropo action. """ actions = self._actions if (type (actions) is list): dict = actions[0] else: dict = actions return dict.get('interpretation', 'NoValue') def getIndexdedInterpretation(self, index): """ Get the value of the indexed Tropo action. """ actions = self._actions if (type (actions) is list): dict = actions[index] else: dict = actions return dict.get('interpretation', 'NoValue') def getNamedActionInterpretation(self, name): """ Get the value of the named Tropo action. """ actions = self._actions if (type (actions) is list): for a in actions: if a.get('name', 'NoValue') == name: dict =a else: dict = actions return dict.get('interpretation', 'NoValue')
tropo/tropo-webapi-python
tropo.py
Result.getIndexedValue
python
def getIndexedValue(self, index): actions = self._actions if (type (actions) is list): dict = actions[index] else: dict = actions return dict.get('value', 'NoValue')
Get the value of the indexed Tropo action.
train
https://github.com/tropo/tropo-webapi-python/blob/f87772644a6b45066a4c5218f0c1f6467b64ab3c/tropo.py#L724-L734
null
class Result(object): """ Returned anytime a request is made to the Tropo Web API. Method: getValue (See https://www.tropo.com/docs/webapi/result) { "result": { "actions": Array or Object, "calledId": String, "callId": String, "complete": Boolean, "connectedDuration": Integer, "duration": Integer, "error": String, "sequence": Integer, "sessionDuration": Integer, "sessionId": String, "state": String, "userType": String} } """ options_array = ['actions','complete','error','sequence', 'sessionDuration', 'sessionId', 'state', 'userType', 'connectedDuration', 'duration', 'calledID', 'callId'] def __init__(self, result_json): result_data = jsonlib.loads(result_json) result_dict = result_data['result'] for opt in self.options_array: if result_dict.get(opt, False): setattr(self, '_%s' % opt, result_dict[opt]) def getActions(self): actions = self._actions return actions def getActionsCount(self): actions = self._actions if actions is None: count = 0 return count if (type (actions) is list): count = len(actions) else: count = 1 return count def getValue(self): """ Get the value of the previously POSTed Tropo action. """ actions = self._actions if (type (actions) is list): dict = actions[0] else: dict = actions return dict.get('value', 'NoValue') def getNamedActionValue(self, name): """ Get the value of the named Tropo action. """ actions = self._actions if (type (actions) is list): for a in actions: if a.get('name', 'NoValue') == name: dict =a else: dict = actions return dict.get('value', 'NoValue') def getUserType(self): """ Get the userType of the previously POSTed Tropo action. """ userType = self._userType return userType # # **Tue May 17 07:17:38 2011** -- egilchri def getInterpretation(self): """ Get the value of the previously POSTed Tropo action. """ actions = self._actions if (type (actions) is list): dict = actions[0] else: dict = actions return dict.get('interpretation', 'NoValue') def getIndexdedInterpretation(self, index): """ Get the value of the indexed Tropo action. """ actions = self._actions if (type (actions) is list): dict = actions[index] else: dict = actions return dict.get('interpretation', 'NoValue') def getNamedActionInterpretation(self, name): """ Get the value of the named Tropo action. """ actions = self._actions if (type (actions) is list): for a in actions: if a.get('name', 'NoValue') == name: dict =a else: dict = actions return dict.get('interpretation', 'NoValue')
tropo/tropo-webapi-python
tropo.py
Result.getNamedActionValue
python
def getNamedActionValue(self, name): actions = self._actions if (type (actions) is list): for a in actions: if a.get('name', 'NoValue') == name: dict =a else: dict = actions return dict.get('value', 'NoValue')
Get the value of the named Tropo action.
train
https://github.com/tropo/tropo-webapi-python/blob/f87772644a6b45066a4c5218f0c1f6467b64ab3c/tropo.py#L736-L748
null
class Result(object): """ Returned anytime a request is made to the Tropo Web API. Method: getValue (See https://www.tropo.com/docs/webapi/result) { "result": { "actions": Array or Object, "calledId": String, "callId": String, "complete": Boolean, "connectedDuration": Integer, "duration": Integer, "error": String, "sequence": Integer, "sessionDuration": Integer, "sessionId": String, "state": String, "userType": String} } """ options_array = ['actions','complete','error','sequence', 'sessionDuration', 'sessionId', 'state', 'userType', 'connectedDuration', 'duration', 'calledID', 'callId'] def __init__(self, result_json): result_data = jsonlib.loads(result_json) result_dict = result_data['result'] for opt in self.options_array: if result_dict.get(opt, False): setattr(self, '_%s' % opt, result_dict[opt]) def getActions(self): actions = self._actions return actions def getActionsCount(self): actions = self._actions if actions is None: count = 0 return count if (type (actions) is list): count = len(actions) else: count = 1 return count def getValue(self): """ Get the value of the previously POSTed Tropo action. """ actions = self._actions if (type (actions) is list): dict = actions[0] else: dict = actions return dict.get('value', 'NoValue') def getIndexedValue(self, index): """ Get the value of the indexed Tropo action. """ actions = self._actions if (type (actions) is list): dict = actions[index] else: dict = actions return dict.get('value', 'NoValue') def getUserType(self): """ Get the userType of the previously POSTed Tropo action. """ userType = self._userType return userType # # **Tue May 17 07:17:38 2011** -- egilchri def getInterpretation(self): """ Get the value of the previously POSTed Tropo action. """ actions = self._actions if (type (actions) is list): dict = actions[0] else: dict = actions return dict.get('interpretation', 'NoValue') def getIndexdedInterpretation(self, index): """ Get the value of the indexed Tropo action. """ actions = self._actions if (type (actions) is list): dict = actions[index] else: dict = actions return dict.get('interpretation', 'NoValue') def getNamedActionInterpretation(self, name): """ Get the value of the named Tropo action. """ actions = self._actions if (type (actions) is list): for a in actions: if a.get('name', 'NoValue') == name: dict =a else: dict = actions return dict.get('interpretation', 'NoValue')
tropo/tropo-webapi-python
tropo.py
Tropo.answer
python
def answer (self, headers, **options): self._steps.append(Answer (headers, **options).obj)
Places a call or sends an an IM, Twitter, or SMS message. To start a call, use the Session API headers tell Tropo headers launch your code. Arguments: headers is a String. Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/answer
train
https://github.com/tropo/tropo-webapi-python/blob/f87772644a6b45066a4c5218f0c1f6467b64ab3c/tropo.py#L862-L869
null
class Tropo(object): """ This is the top level class for all the Tropo web api actions. The methods of this class implement individual Tropo actions. Individual actions are each methods on this class. Each method takes one or more required arguments, followed by optional arguments expressed as key=value pairs. The optional arguments for these methods are described here: https://www.tropo.com/docs/webapi/ """ def __init__(self): self._steps = [] # # **Sun May 15 21:05:01 2011** -- egilchri def setVoice(self, voice): self.voice = voice # # end **Sun May 15 21:05:01 2011** -- egilchri def ask(self, choices, **options): """ Sends a prompt to the user and optionally waits for a response. Arguments: "choices" is a Choices object See https://www.tropo.com/docs/webapi/ask """ # # **Sun May 15 21:21:29 2011** -- egilchri # Settng the voice in this method call has priority. # Otherwise, we can pick up the voice from the Tropo object, # if it is set there. if hasattr (self, 'voice'): if (not 'voice' in options): options['voice'] = self.voice # # **Sun May 15 21:21:29 2011** -- egilchri self._steps.append(Ask(choices, **options).obj) def call (self, to, **options): """ Places a call or sends an an IM, Twitter, or SMS message. To start a call, use the Session API to tell Tropo to launch your code. Arguments: to is a String. Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/call """ self._steps.append(Call (to, **options).obj) def conference(self, id, **options): """ This object allows multiple lines in separate sessions to be conferenced together so that the parties on each line can talk to each other simultaneously. This is a voice channel only feature. Argument: "id" is a String Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/conference """ self._steps.append(Conference(id, **options).obj) def hangup(self): """ This method instructs Tropo to "hang-up" or disconnect the session associated with the current session. See https://www.tropo.com/docs/webapi/hangup """ self._steps.append(Hangup().obj) def message (self, say_obj, to, **options): """ A shortcut method to create a session, say something, and hang up, all in one step. This is particularly useful for sending out a quick SMS or IM. Argument: "say_obj" is a Say object Argument: "to" is a String Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/message """ if isinstance(say_obj, basestring): say = Say(say_obj).obj else: say = say_obj self._steps.append(Message(say, to, **options).obj) def on(self, event, **options): """ Adds an event callback so that your application may be notified when a particular event occurs. Possible events are: "continue", "error", "incomplete" and "hangup". Argument: event is an event Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/on """ if hasattr (self, 'voice'): if (not 'voice' in options): options['voice'] = self.voice self._steps.append(On(event, **options).obj) def record(self, **options): """ Plays a prompt (audio file or text to speech) and optionally waits for a response from the caller that is recorded. Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/record """ self._steps.append(Record(**options).obj) def redirect(self, id, name, **options): """ Forwards an incoming call to another destination / phone number before answering it. Argument: id is a String Argument: name is a String Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/redirect """ self._steps.append(Redirect(id, name, **options).obj) def reject(self): """ Allows Tropo applications to reject incoming sessions before they are answered. See https://www.tropo.com/docs/webapi/reject """ self._steps.append(Reject().obj) def say(self, message, **options): """ When the current session is a voice channel this key will either play a message or an audio file from a URL. In the case of an text channel it will send the text back to the user via i nstant messaging or SMS. Argument: message is a string Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/say """ #voice = self.voice # # **Sun May 15 21:21:29 2011** -- egilchri # Settng the voice in this method call has priority. # Otherwise, we can pick up the voice from the Tropo object, # if it is set there. if hasattr (self, 'voice'): if (not 'voice' in options): options['voice'] = self.voice # # **Sun May 15 21:21:29 2011** -- egilchri self._steps.append(Say(message, **options).obj) def startRecording(self, url, **options): """ Allows Tropo applications to begin recording the current session. Argument: url is a string Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/startrecording """ self._steps.append(StartRecording(url, **options).obj) def stopRecording(self): """ Stops a previously started recording. See https://www.tropo.com/docs/webapi/stoprecording """ self._steps.append(StopRecording().obj) def transfer(self, to, **options): """ Transfers an already answered call to another destination / phone number. Argument: to is a string Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/transfer """ self._steps.append(Transfer(to, **options).obj) def wait(self, milliseconds, **options): """ Allows the thread to sleep for a given amount of time in milliseconds Argument: milliseconds is an Integer Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/wait """ self._steps.append(Wait(milliseconds, **options).obj) def generalLogSecurity(self, state, **options): """ Turn on/off all logging on the Tropo platform Argument: state is a String See https://www.tropo.com/docs/webapi/generallogsecurity """ self._steps.append(GeneralLogSecurity(state).obj) def RenderJson(self, pretty=False): """ Render a Tropo object into a Json string. """ steps = self._steps topdict = {} topdict['tropo'] = steps if pretty: try: json = jsonlib.dumps(topdict, indent=4, sort_keys=False) except TypeError: json = jsonlib.dumps(topdict) else: json = jsonlib.dumps(topdict) return json
tropo/tropo-webapi-python
tropo.py
Tropo.redirect
python
def redirect(self, id, name, **options): self._steps.append(Redirect(id, name, **options).obj)
Forwards an incoming call to another destination / phone number before answering it. Argument: id is a String Argument: name is a String Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/redirect
train
https://github.com/tropo/tropo-webapi-python/blob/f87772644a6b45066a4c5218f0c1f6467b64ab3c/tropo.py#L934-L942
null
class Tropo(object): """ This is the top level class for all the Tropo web api actions. The methods of this class implement individual Tropo actions. Individual actions are each methods on this class. Each method takes one or more required arguments, followed by optional arguments expressed as key=value pairs. The optional arguments for these methods are described here: https://www.tropo.com/docs/webapi/ """ def __init__(self): self._steps = [] # # **Sun May 15 21:05:01 2011** -- egilchri def setVoice(self, voice): self.voice = voice # # end **Sun May 15 21:05:01 2011** -- egilchri def ask(self, choices, **options): """ Sends a prompt to the user and optionally waits for a response. Arguments: "choices" is a Choices object See https://www.tropo.com/docs/webapi/ask """ # # **Sun May 15 21:21:29 2011** -- egilchri # Settng the voice in this method call has priority. # Otherwise, we can pick up the voice from the Tropo object, # if it is set there. if hasattr (self, 'voice'): if (not 'voice' in options): options['voice'] = self.voice # # **Sun May 15 21:21:29 2011** -- egilchri self._steps.append(Ask(choices, **options).obj) def answer (self, headers, **options): """ Places a call or sends an an IM, Twitter, or SMS message. To start a call, use the Session API headers tell Tropo headers launch your code. Arguments: headers is a String. Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/answer """ self._steps.append(Answer (headers, **options).obj) def call (self, to, **options): """ Places a call or sends an an IM, Twitter, or SMS message. To start a call, use the Session API to tell Tropo to launch your code. Arguments: to is a String. Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/call """ self._steps.append(Call (to, **options).obj) def conference(self, id, **options): """ This object allows multiple lines in separate sessions to be conferenced together so that the parties on each line can talk to each other simultaneously. This is a voice channel only feature. Argument: "id" is a String Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/conference """ self._steps.append(Conference(id, **options).obj) def hangup(self): """ This method instructs Tropo to "hang-up" or disconnect the session associated with the current session. See https://www.tropo.com/docs/webapi/hangup """ self._steps.append(Hangup().obj) def message (self, say_obj, to, **options): """ A shortcut method to create a session, say something, and hang up, all in one step. This is particularly useful for sending out a quick SMS or IM. Argument: "say_obj" is a Say object Argument: "to" is a String Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/message """ if isinstance(say_obj, basestring): say = Say(say_obj).obj else: say = say_obj self._steps.append(Message(say, to, **options).obj) def on(self, event, **options): """ Adds an event callback so that your application may be notified when a particular event occurs. Possible events are: "continue", "error", "incomplete" and "hangup". Argument: event is an event Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/on """ if hasattr (self, 'voice'): if (not 'voice' in options): options['voice'] = self.voice self._steps.append(On(event, **options).obj) def record(self, **options): """ Plays a prompt (audio file or text to speech) and optionally waits for a response from the caller that is recorded. Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/record """ self._steps.append(Record(**options).obj) def reject(self): """ Allows Tropo applications to reject incoming sessions before they are answered. See https://www.tropo.com/docs/webapi/reject """ self._steps.append(Reject().obj) def say(self, message, **options): """ When the current session is a voice channel this key will either play a message or an audio file from a URL. In the case of an text channel it will send the text back to the user via i nstant messaging or SMS. Argument: message is a string Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/say """ #voice = self.voice # # **Sun May 15 21:21:29 2011** -- egilchri # Settng the voice in this method call has priority. # Otherwise, we can pick up the voice from the Tropo object, # if it is set there. if hasattr (self, 'voice'): if (not 'voice' in options): options['voice'] = self.voice # # **Sun May 15 21:21:29 2011** -- egilchri self._steps.append(Say(message, **options).obj) def startRecording(self, url, **options): """ Allows Tropo applications to begin recording the current session. Argument: url is a string Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/startrecording """ self._steps.append(StartRecording(url, **options).obj) def stopRecording(self): """ Stops a previously started recording. See https://www.tropo.com/docs/webapi/stoprecording """ self._steps.append(StopRecording().obj) def transfer(self, to, **options): """ Transfers an already answered call to another destination / phone number. Argument: to is a string Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/transfer """ self._steps.append(Transfer(to, **options).obj) def wait(self, milliseconds, **options): """ Allows the thread to sleep for a given amount of time in milliseconds Argument: milliseconds is an Integer Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/wait """ self._steps.append(Wait(milliseconds, **options).obj) def generalLogSecurity(self, state, **options): """ Turn on/off all logging on the Tropo platform Argument: state is a String See https://www.tropo.com/docs/webapi/generallogsecurity """ self._steps.append(GeneralLogSecurity(state).obj) def RenderJson(self, pretty=False): """ Render a Tropo object into a Json string. """ steps = self._steps topdict = {} topdict['tropo'] = steps if pretty: try: json = jsonlib.dumps(topdict, indent=4, sort_keys=False) except TypeError: json = jsonlib.dumps(topdict) else: json = jsonlib.dumps(topdict) return json
tropo/tropo-webapi-python
tropo.py
Tropo.generalLogSecurity
python
def generalLogSecurity(self, state, **options): self._steps.append(GeneralLogSecurity(state).obj)
Turn on/off all logging on the Tropo platform Argument: state is a String See https://www.tropo.com/docs/webapi/generallogsecurity
train
https://github.com/tropo/tropo-webapi-python/blob/f87772644a6b45066a4c5218f0c1f6467b64ab3c/tropo.py#L1006-L1012
null
class Tropo(object): """ This is the top level class for all the Tropo web api actions. The methods of this class implement individual Tropo actions. Individual actions are each methods on this class. Each method takes one or more required arguments, followed by optional arguments expressed as key=value pairs. The optional arguments for these methods are described here: https://www.tropo.com/docs/webapi/ """ def __init__(self): self._steps = [] # # **Sun May 15 21:05:01 2011** -- egilchri def setVoice(self, voice): self.voice = voice # # end **Sun May 15 21:05:01 2011** -- egilchri def ask(self, choices, **options): """ Sends a prompt to the user and optionally waits for a response. Arguments: "choices" is a Choices object See https://www.tropo.com/docs/webapi/ask """ # # **Sun May 15 21:21:29 2011** -- egilchri # Settng the voice in this method call has priority. # Otherwise, we can pick up the voice from the Tropo object, # if it is set there. if hasattr (self, 'voice'): if (not 'voice' in options): options['voice'] = self.voice # # **Sun May 15 21:21:29 2011** -- egilchri self._steps.append(Ask(choices, **options).obj) def answer (self, headers, **options): """ Places a call or sends an an IM, Twitter, or SMS message. To start a call, use the Session API headers tell Tropo headers launch your code. Arguments: headers is a String. Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/answer """ self._steps.append(Answer (headers, **options).obj) def call (self, to, **options): """ Places a call or sends an an IM, Twitter, or SMS message. To start a call, use the Session API to tell Tropo to launch your code. Arguments: to is a String. Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/call """ self._steps.append(Call (to, **options).obj) def conference(self, id, **options): """ This object allows multiple lines in separate sessions to be conferenced together so that the parties on each line can talk to each other simultaneously. This is a voice channel only feature. Argument: "id" is a String Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/conference """ self._steps.append(Conference(id, **options).obj) def hangup(self): """ This method instructs Tropo to "hang-up" or disconnect the session associated with the current session. See https://www.tropo.com/docs/webapi/hangup """ self._steps.append(Hangup().obj) def message (self, say_obj, to, **options): """ A shortcut method to create a session, say something, and hang up, all in one step. This is particularly useful for sending out a quick SMS or IM. Argument: "say_obj" is a Say object Argument: "to" is a String Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/message """ if isinstance(say_obj, basestring): say = Say(say_obj).obj else: say = say_obj self._steps.append(Message(say, to, **options).obj) def on(self, event, **options): """ Adds an event callback so that your application may be notified when a particular event occurs. Possible events are: "continue", "error", "incomplete" and "hangup". Argument: event is an event Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/on """ if hasattr (self, 'voice'): if (not 'voice' in options): options['voice'] = self.voice self._steps.append(On(event, **options).obj) def record(self, **options): """ Plays a prompt (audio file or text to speech) and optionally waits for a response from the caller that is recorded. Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/record """ self._steps.append(Record(**options).obj) def redirect(self, id, name, **options): """ Forwards an incoming call to another destination / phone number before answering it. Argument: id is a String Argument: name is a String Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/redirect """ self._steps.append(Redirect(id, name, **options).obj) def reject(self): """ Allows Tropo applications to reject incoming sessions before they are answered. See https://www.tropo.com/docs/webapi/reject """ self._steps.append(Reject().obj) def say(self, message, **options): """ When the current session is a voice channel this key will either play a message or an audio file from a URL. In the case of an text channel it will send the text back to the user via i nstant messaging or SMS. Argument: message is a string Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/say """ #voice = self.voice # # **Sun May 15 21:21:29 2011** -- egilchri # Settng the voice in this method call has priority. # Otherwise, we can pick up the voice from the Tropo object, # if it is set there. if hasattr (self, 'voice'): if (not 'voice' in options): options['voice'] = self.voice # # **Sun May 15 21:21:29 2011** -- egilchri self._steps.append(Say(message, **options).obj) def startRecording(self, url, **options): """ Allows Tropo applications to begin recording the current session. Argument: url is a string Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/startrecording """ self._steps.append(StartRecording(url, **options).obj) def stopRecording(self): """ Stops a previously started recording. See https://www.tropo.com/docs/webapi/stoprecording """ self._steps.append(StopRecording().obj) def transfer(self, to, **options): """ Transfers an already answered call to another destination / phone number. Argument: to is a string Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/transfer """ self._steps.append(Transfer(to, **options).obj) def wait(self, milliseconds, **options): """ Allows the thread to sleep for a given amount of time in milliseconds Argument: milliseconds is an Integer Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/wait """ self._steps.append(Wait(milliseconds, **options).obj) def RenderJson(self, pretty=False): """ Render a Tropo object into a Json string. """ steps = self._steps topdict = {} topdict['tropo'] = steps if pretty: try: json = jsonlib.dumps(topdict, indent=4, sort_keys=False) except TypeError: json = jsonlib.dumps(topdict) else: json = jsonlib.dumps(topdict) return json
AASHE/python-membersuite-api-client
membersuite_api_client/subscriptions/services.py
SubscriptionService.get_subscriptions
python
def get_subscriptions(self, publication_id=None, owner_id=None, since_when=None, limit_to=200, max_calls=None, start_record=0, verbose=False): query = "SELECT Objects() FROM Subscription" # collect all where parameters into a list of # (key, operator, value) tuples where_params = [] if owner_id: where_params.append(('owner', '=', "'%s'" % owner_id)) if publication_id: where_params.append(('publication', '=', "'%s'" % publication_id)) if since_when: d = datetime.date.today() - datetime.timedelta(days=since_when) where_params.append( ('LastModifiedDate', ">", "'%s 00:00:00'" % d)) if where_params: query += " WHERE " query += " AND ".join( ["%s %s %s" % (p[0], p[1], p[2]) for p in where_params]) subscription_list = self.get_long_query( query, limit_to=limit_to, max_calls=max_calls, start_record=start_record, verbose=verbose) return subscription_list
Fetches all subscriptions from Membersuite of a particular `publication_id` if set.
train
https://github.com/AASHE/python-membersuite-api-client/blob/221f5ed8bc7d4424237a4669c5af9edc11819ee9/membersuite_api_client/subscriptions/services.py#L27-L58
[ "def get_long_query(self, base_object_query, limit_to=100, max_calls=None,\n start_record=0, verbose=False):\n \"\"\"\n Takes a base query for all objects and recursively requests them\n\n :param str base_object_query: the base query to be executed\n :param int limit_to: how many rows ...
class SubscriptionService(ChunkQueryMixin, object): def __init__(self, client=None): """ Accepts a ConciergeClient to connect with MemberSuite """ super(SubscriptionService, self).__init__() self.client = client or get_new_client() def ms_object_to_model(self, ms_obj): " Converts an individual result to a Subscription Model " return Subscription(membersuite_object_data=ms_obj)
AASHE/python-membersuite-api-client
membersuite_api_client/orders/services.py
get_order
python
def get_order(membersuite_id, client=None): if not membersuite_id: return None client = client or get_new_client(request_session=True) if not client.session_id: client.request_session() object_query = "SELECT Object() FROM ORDER WHERE ID = '{}'".format( membersuite_id) result = client.execute_object_query(object_query) msql_result = result["body"]["ExecuteMSQLResult"] if msql_result["Success"]: membersuite_object_data = (msql_result["ResultValue"] ["SingleObject"]) else: raise ExecuteMSQLError(result=result) return Order(membersuite_object_data=membersuite_object_data)
Get an Order by ID.
train
https://github.com/AASHE/python-membersuite-api-client/blob/221f5ed8bc7d4424237a4669c5af9edc11819ee9/membersuite_api_client/orders/services.py#L6-L29
[ "def get_new_client(request_session=False):\n \"\"\"Return a new ConciergeClient, pulling secrets from the environment.\n\n \"\"\"\n from .client import ConciergeClient\n client = ConciergeClient(access_key=os.environ[\"MS_ACCESS_KEY\"],\n secret_key=os.environ[\"MS_SECRET_KE...
from ..exceptions import ExecuteMSQLError from ..utils import get_new_client from .models import Order
AASHE/python-membersuite-api-client
membersuite_api_client/organizations/services.py
OrganizationService.get_org_types
python
def get_org_types(self): if not self.client.session_id: self.client.request_session() object_query = "SELECT Objects() FROM OrganizationType" result = self.client.execute_object_query(object_query=object_query) msql_result = result['body']["ExecuteMSQLResult"] return self.package_org_types(msql_result["ResultValue"] ["ObjectSearchResult"] ["Objects"]["MemberSuiteObject"] )
Retrieves all current OrganizationType objects
train
https://github.com/AASHE/python-membersuite-api-client/blob/221f5ed8bc7d4424237a4669c5af9edc11819ee9/membersuite_api_client/organizations/services.py#L80-L93
[ "def package_org_types(self, obj_list):\n \"\"\"\n Loops through MS objects returned from queries to turn them into\n OrganizationType objects and pack them into a list for later use.\n \"\"\"\n org_type_list = []\n for obj in obj_list:\n sane_obj = convert_ms_object(\n obj['Fiel...
class OrganizationService(ChunkQueryMixin, object): def __init__(self, client=None): """ Accepts a ConciergeClient to connect with MemberSuite """ self.client = client or get_new_client(request_session=True) def get_orgs( self, limit_to=100, max_calls=None, parameters=None, since_when=None, start_record=0, verbose=False): """ Constructs request to MemberSuite to query organization objects. :param int limit_to: number of records to fetch with each chunk :param int max_calls: the maximum number of calls (chunks) to request :param str parameters: additional query parameter dictionary :param date since_when: fetch records modified after this date :param int start_record: the first record to return from the query :param bool verbose: print progress to stdout :return: a list of Organization objects """ if not self.client.session_id: self.client.request_session() query = "SELECT Objects() FROM Organization" # collect all where parameters into a list of # (key, operator, value) tuples where_params = [] if parameters: for k, v in parameters.items(): where_params.append((k, "=", v)) if since_when: d = datetime.date.today() - datetime.timedelta(days=since_when) where_params.append( ('LastModifiedDate', ">", "'%s 00:00:00'" % d)) if where_params: query += " WHERE " query += " AND ".join( ["%s %s %s" % (p[0], p[1], p[2]) for p in where_params]) if verbose: print("Fetching Organizations...") # note, get_long_query is overkill when just looking at # one org, but it still only executes once # `get_long_query` uses `ms_object_to_model` to return Organizations org_list = self.get_long_query( query, limit_to=limit_to, max_calls=max_calls, start_record=start_record, verbose=verbose) return org_list def ms_object_to_model(self, ms_obj): " Converts an individual result to an Organization Model " sane_obj = convert_ms_object( ms_obj['Fields']['KeyValueOfstringanyType']) return Organization(sane_obj) def package_org_types(self, obj_list): """ Loops through MS objects returned from queries to turn them into OrganizationType objects and pack them into a list for later use. """ org_type_list = [] for obj in obj_list: sane_obj = convert_ms_object( obj['Fields']['KeyValueOfstringanyType'] ) org = OrganizationType(sane_obj) org_type_list.append(org) return org_type_list def get_individuals_for_primary_organization(self, organization): """ Returns all Individuals that have `organization` as a primary org. """ if not self.client.session_id: self.client.request_session() object_query = ("SELECT Objects() FROM Individual WHERE " "PrimaryOrganization = '{}'".format( organization.membersuite_account_num)) result = self.client.execute_object_query(object_query) msql_result = result["body"]["ExecuteMSQLResult"] if msql_result["Success"]: membersuite_objects = (msql_result["ResultValue"] ["ObjectSearchResult"] ["Objects"]) else: raise ExecuteMSQLError(result=result) individuals = [] if membersuite_objects is not None: for membersuite_object in membersuite_objects["MemberSuiteObject"]: individuals.append( Individual(membersuite_object_data=membersuite_object)) return individuals # get_stars_liaison_for_organization doesn't belong here. It should # live in some AASHE-specific place, not in OrganizationService. def get_stars_liaison_for_organization(self, organization): candidates = self.get_individuals_for_primary_organization( organization=organization) # Check for a STARS Primary Contact first: for candidate in candidates: if "StarsPrimaryContact__rt" in candidate.fields: return candidate # No STARS Primary Contact? Try the account's primary contact: for candidate in candidates: if "Primary_Contact__rt" in candidate.fields: return candidate # No primary contact? Try billing contact: for candidate in candidates: if "Billing_Contact__rt" in candidate.fields: return candidate return None
AASHE/python-membersuite-api-client
membersuite_api_client/organizations/services.py
OrganizationService.package_org_types
python
def package_org_types(self, obj_list): org_type_list = [] for obj in obj_list: sane_obj = convert_ms_object( obj['Fields']['KeyValueOfstringanyType'] ) org = OrganizationType(sane_obj) org_type_list.append(org) return org_type_list
Loops through MS objects returned from queries to turn them into OrganizationType objects and pack them into a list for later use.
train
https://github.com/AASHE/python-membersuite-api-client/blob/221f5ed8bc7d4424237a4669c5af9edc11819ee9/membersuite_api_client/organizations/services.py#L95-L107
[ "def convert_ms_object(ms_object):\n \"\"\"\n Converts the list of dictionaries with keys \"key\" and \"value\" into\n more logical value-key pairs in a plain dictionary.\n \"\"\"\n out_dict = {}\n for item in ms_object:\n out_dict[item[\"Key\"]] = item[\"Value\"]\n return out_dict\n" ]
class OrganizationService(ChunkQueryMixin, object): def __init__(self, client=None): """ Accepts a ConciergeClient to connect with MemberSuite """ self.client = client or get_new_client(request_session=True) def get_orgs( self, limit_to=100, max_calls=None, parameters=None, since_when=None, start_record=0, verbose=False): """ Constructs request to MemberSuite to query organization objects. :param int limit_to: number of records to fetch with each chunk :param int max_calls: the maximum number of calls (chunks) to request :param str parameters: additional query parameter dictionary :param date since_when: fetch records modified after this date :param int start_record: the first record to return from the query :param bool verbose: print progress to stdout :return: a list of Organization objects """ if not self.client.session_id: self.client.request_session() query = "SELECT Objects() FROM Organization" # collect all where parameters into a list of # (key, operator, value) tuples where_params = [] if parameters: for k, v in parameters.items(): where_params.append((k, "=", v)) if since_when: d = datetime.date.today() - datetime.timedelta(days=since_when) where_params.append( ('LastModifiedDate', ">", "'%s 00:00:00'" % d)) if where_params: query += " WHERE " query += " AND ".join( ["%s %s %s" % (p[0], p[1], p[2]) for p in where_params]) if verbose: print("Fetching Organizations...") # note, get_long_query is overkill when just looking at # one org, but it still only executes once # `get_long_query` uses `ms_object_to_model` to return Organizations org_list = self.get_long_query( query, limit_to=limit_to, max_calls=max_calls, start_record=start_record, verbose=verbose) return org_list def ms_object_to_model(self, ms_obj): " Converts an individual result to an Organization Model " sane_obj = convert_ms_object( ms_obj['Fields']['KeyValueOfstringanyType']) return Organization(sane_obj) def get_org_types(self): """ Retrieves all current OrganizationType objects """ if not self.client.session_id: self.client.request_session() object_query = "SELECT Objects() FROM OrganizationType" result = self.client.execute_object_query(object_query=object_query) msql_result = result['body']["ExecuteMSQLResult"] return self.package_org_types(msql_result["ResultValue"] ["ObjectSearchResult"] ["Objects"]["MemberSuiteObject"] ) def get_individuals_for_primary_organization(self, organization): """ Returns all Individuals that have `organization` as a primary org. """ if not self.client.session_id: self.client.request_session() object_query = ("SELECT Objects() FROM Individual WHERE " "PrimaryOrganization = '{}'".format( organization.membersuite_account_num)) result = self.client.execute_object_query(object_query) msql_result = result["body"]["ExecuteMSQLResult"] if msql_result["Success"]: membersuite_objects = (msql_result["ResultValue"] ["ObjectSearchResult"] ["Objects"]) else: raise ExecuteMSQLError(result=result) individuals = [] if membersuite_objects is not None: for membersuite_object in membersuite_objects["MemberSuiteObject"]: individuals.append( Individual(membersuite_object_data=membersuite_object)) return individuals # get_stars_liaison_for_organization doesn't belong here. It should # live in some AASHE-specific place, not in OrganizationService. def get_stars_liaison_for_organization(self, organization): candidates = self.get_individuals_for_primary_organization( organization=organization) # Check for a STARS Primary Contact first: for candidate in candidates: if "StarsPrimaryContact__rt" in candidate.fields: return candidate # No STARS Primary Contact? Try the account's primary contact: for candidate in candidates: if "Primary_Contact__rt" in candidate.fields: return candidate # No primary contact? Try billing contact: for candidate in candidates: if "Billing_Contact__rt" in candidate.fields: return candidate return None
AASHE/python-membersuite-api-client
membersuite_api_client/organizations/services.py
OrganizationService.get_individuals_for_primary_organization
python
def get_individuals_for_primary_organization(self, organization): if not self.client.session_id: self.client.request_session() object_query = ("SELECT Objects() FROM Individual WHERE " "PrimaryOrganization = '{}'".format( organization.membersuite_account_num)) result = self.client.execute_object_query(object_query) msql_result = result["body"]["ExecuteMSQLResult"] if msql_result["Success"]: membersuite_objects = (msql_result["ResultValue"] ["ObjectSearchResult"] ["Objects"]) else: raise ExecuteMSQLError(result=result) individuals = [] if membersuite_objects is not None: for membersuite_object in membersuite_objects["MemberSuiteObject"]: individuals.append( Individual(membersuite_object_data=membersuite_object)) return individuals
Returns all Individuals that have `organization` as a primary org.
train
https://github.com/AASHE/python-membersuite-api-client/blob/221f5ed8bc7d4424237a4669c5af9edc11819ee9/membersuite_api_client/organizations/services.py#L109-L140
null
class OrganizationService(ChunkQueryMixin, object): def __init__(self, client=None): """ Accepts a ConciergeClient to connect with MemberSuite """ self.client = client or get_new_client(request_session=True) def get_orgs( self, limit_to=100, max_calls=None, parameters=None, since_when=None, start_record=0, verbose=False): """ Constructs request to MemberSuite to query organization objects. :param int limit_to: number of records to fetch with each chunk :param int max_calls: the maximum number of calls (chunks) to request :param str parameters: additional query parameter dictionary :param date since_when: fetch records modified after this date :param int start_record: the first record to return from the query :param bool verbose: print progress to stdout :return: a list of Organization objects """ if not self.client.session_id: self.client.request_session() query = "SELECT Objects() FROM Organization" # collect all where parameters into a list of # (key, operator, value) tuples where_params = [] if parameters: for k, v in parameters.items(): where_params.append((k, "=", v)) if since_when: d = datetime.date.today() - datetime.timedelta(days=since_when) where_params.append( ('LastModifiedDate', ">", "'%s 00:00:00'" % d)) if where_params: query += " WHERE " query += " AND ".join( ["%s %s %s" % (p[0], p[1], p[2]) for p in where_params]) if verbose: print("Fetching Organizations...") # note, get_long_query is overkill when just looking at # one org, but it still only executes once # `get_long_query` uses `ms_object_to_model` to return Organizations org_list = self.get_long_query( query, limit_to=limit_to, max_calls=max_calls, start_record=start_record, verbose=verbose) return org_list def ms_object_to_model(self, ms_obj): " Converts an individual result to an Organization Model " sane_obj = convert_ms_object( ms_obj['Fields']['KeyValueOfstringanyType']) return Organization(sane_obj) def get_org_types(self): """ Retrieves all current OrganizationType objects """ if not self.client.session_id: self.client.request_session() object_query = "SELECT Objects() FROM OrganizationType" result = self.client.execute_object_query(object_query=object_query) msql_result = result['body']["ExecuteMSQLResult"] return self.package_org_types(msql_result["ResultValue"] ["ObjectSearchResult"] ["Objects"]["MemberSuiteObject"] ) def package_org_types(self, obj_list): """ Loops through MS objects returned from queries to turn them into OrganizationType objects and pack them into a list for later use. """ org_type_list = [] for obj in obj_list: sane_obj = convert_ms_object( obj['Fields']['KeyValueOfstringanyType'] ) org = OrganizationType(sane_obj) org_type_list.append(org) return org_type_list # get_stars_liaison_for_organization doesn't belong here. It should # live in some AASHE-specific place, not in OrganizationService. def get_stars_liaison_for_organization(self, organization): candidates = self.get_individuals_for_primary_organization( organization=organization) # Check for a STARS Primary Contact first: for candidate in candidates: if "StarsPrimaryContact__rt" in candidate.fields: return candidate # No STARS Primary Contact? Try the account's primary contact: for candidate in candidates: if "Primary_Contact__rt" in candidate.fields: return candidate # No primary contact? Try billing contact: for candidate in candidates: if "Billing_Contact__rt" in candidate.fields: return candidate return None
AASHE/python-membersuite-api-client
membersuite_api_client/mixins.py
run_object_query
python
def run_object_query(client, base_object_query, start_record, limit_to, verbose=False): if verbose: print("[start: %d limit: %d]" % (start_record, limit_to)) start = datetime.datetime.now() result = client.execute_object_query( object_query=base_object_query, start_record=start_record, limit_to=limit_to) end = datetime.datetime.now() if verbose: print("[%s - %s]" % (start, end)) return result
inline method to take advantage of retry
train
https://github.com/AASHE/python-membersuite-api-client/blob/221f5ed8bc7d4424237a4669c5af9edc11819ee9/membersuite_api_client/mixins.py#L10-L23
null
from retrying import retry import datetime from .exceptions import ExecuteMSQLError RETRY_ATTEMPTS = 10 @retry(stop_max_attempt_number=RETRY_ATTEMPTS, wait_fixed=2000) class ChunkQueryMixin(object): """ A mixin for API client service classes that makes it easy to consistently request multiple queries from a MemberSuite endpoint. Membersuite will often time out on big queries, so this allows us to break it up into smaller requests. """ def get_long_query(self, base_object_query, limit_to=100, max_calls=None, start_record=0, verbose=False): """ Takes a base query for all objects and recursively requests them :param str base_object_query: the base query to be executed :param int limit_to: how many rows to query for in each chunk :param int max_calls: the max calls(chunks to request) None is infinite :param int start_record: the first record to return from the query :param bool verbose: print progress to stdout :return: a list of Organization objects """ if verbose: print(base_object_query) record_index = start_record result = run_object_query(self.client, base_object_query, record_index, limit_to, verbose) obj_search_result = (result['body']["ExecuteMSQLResult"]["ResultValue"] ["ObjectSearchResult"]) if obj_search_result is not None: search_results = obj_search_result["Objects"] else: return [] if search_results is None: return [] result_set = search_results["MemberSuiteObject"] all_objects = self.result_to_models(result) call_count = 1 """ continue to run queries as long as we - don't exceed the call call_count - don't see results that are less than the limited length (the end) """ while call_count != max_calls and len(result_set) >= limit_to: record_index += len(result_set) # should be `limit_to` result = run_object_query(self.client, base_object_query, record_index, limit_to, verbose) obj_search_result = (result['body']["ExecuteMSQLResult"] ["ResultValue"]["ObjectSearchResult"]) if obj_search_result is not None: search_results = obj_search_result["Objects"] else: search_results = None if search_results is None: result_set = [] else: result_set = search_results["MemberSuiteObject"] all_objects += self.result_to_models(result) call_count += 1 return all_objects def result_to_models(self, result): """ this is the 'transorm' part of ETL: converts the result of the SQL to Models """ mysql_result = result['body']['ExecuteMSQLResult'] if not mysql_result['Errors']: obj_result = mysql_result['ResultValue']['ObjectSearchResult'] if not obj_result['Objects']: return [] objects = obj_result['Objects']['MemberSuiteObject'] model_list = [] for obj in objects: model = self.ms_object_to_model(obj) model_list.append(model) return model_list else: raise ExecuteMSQLError(result)
AASHE/python-membersuite-api-client
membersuite_api_client/mixins.py
ChunkQueryMixin.get_long_query
python
def get_long_query(self, base_object_query, limit_to=100, max_calls=None, start_record=0, verbose=False): if verbose: print(base_object_query) record_index = start_record result = run_object_query(self.client, base_object_query, record_index, limit_to, verbose) obj_search_result = (result['body']["ExecuteMSQLResult"]["ResultValue"] ["ObjectSearchResult"]) if obj_search_result is not None: search_results = obj_search_result["Objects"] else: return [] if search_results is None: return [] result_set = search_results["MemberSuiteObject"] all_objects = self.result_to_models(result) call_count = 1 """ continue to run queries as long as we - don't exceed the call call_count - don't see results that are less than the limited length (the end) """ while call_count != max_calls and len(result_set) >= limit_to: record_index += len(result_set) # should be `limit_to` result = run_object_query(self.client, base_object_query, record_index, limit_to, verbose) obj_search_result = (result['body']["ExecuteMSQLResult"] ["ResultValue"]["ObjectSearchResult"]) if obj_search_result is not None: search_results = obj_search_result["Objects"] else: search_results = None if search_results is None: result_set = [] else: result_set = search_results["MemberSuiteObject"] all_objects += self.result_to_models(result) call_count += 1 return all_objects
Takes a base query for all objects and recursively requests them :param str base_object_query: the base query to be executed :param int limit_to: how many rows to query for in each chunk :param int max_calls: the max calls(chunks to request) None is infinite :param int start_record: the first record to return from the query :param bool verbose: print progress to stdout :return: a list of Organization objects
train
https://github.com/AASHE/python-membersuite-api-client/blob/221f5ed8bc7d4424237a4669c5af9edc11819ee9/membersuite_api_client/mixins.py#L35-L95
[ "def result_to_models(self, result):\n \"\"\"\n this is the 'transorm' part of ETL:\n converts the result of the SQL to Models\n \"\"\"\n mysql_result = result['body']['ExecuteMSQLResult']\n\n if not mysql_result['Errors']:\n obj_result = mysql_result['ResultValue']['ObjectSearchRes...
class ChunkQueryMixin(object): """ A mixin for API client service classes that makes it easy to consistently request multiple queries from a MemberSuite endpoint. Membersuite will often time out on big queries, so this allows us to break it up into smaller requests. """ def result_to_models(self, result): """ this is the 'transorm' part of ETL: converts the result of the SQL to Models """ mysql_result = result['body']['ExecuteMSQLResult'] if not mysql_result['Errors']: obj_result = mysql_result['ResultValue']['ObjectSearchResult'] if not obj_result['Objects']: return [] objects = obj_result['Objects']['MemberSuiteObject'] model_list = [] for obj in objects: model = self.ms_object_to_model(obj) model_list.append(model) return model_list else: raise ExecuteMSQLError(result)
AASHE/python-membersuite-api-client
membersuite_api_client/mixins.py
ChunkQueryMixin.result_to_models
python
def result_to_models(self, result): mysql_result = result['body']['ExecuteMSQLResult'] if not mysql_result['Errors']: obj_result = mysql_result['ResultValue']['ObjectSearchResult'] if not obj_result['Objects']: return [] objects = obj_result['Objects']['MemberSuiteObject'] model_list = [] for obj in objects: model = self.ms_object_to_model(obj) model_list.append(model) return model_list else: raise ExecuteMSQLError(result)
this is the 'transorm' part of ETL: converts the result of the SQL to Models
train
https://github.com/AASHE/python-membersuite-api-client/blob/221f5ed8bc7d4424237a4669c5af9edc11819ee9/membersuite_api_client/mixins.py#L97-L118
null
class ChunkQueryMixin(object): """ A mixin for API client service classes that makes it easy to consistently request multiple queries from a MemberSuite endpoint. Membersuite will often time out on big queries, so this allows us to break it up into smaller requests. """ def get_long_query(self, base_object_query, limit_to=100, max_calls=None, start_record=0, verbose=False): """ Takes a base query for all objects and recursively requests them :param str base_object_query: the base query to be executed :param int limit_to: how many rows to query for in each chunk :param int max_calls: the max calls(chunks to request) None is infinite :param int start_record: the first record to return from the query :param bool verbose: print progress to stdout :return: a list of Organization objects """ if verbose: print(base_object_query) record_index = start_record result = run_object_query(self.client, base_object_query, record_index, limit_to, verbose) obj_search_result = (result['body']["ExecuteMSQLResult"]["ResultValue"] ["ObjectSearchResult"]) if obj_search_result is not None: search_results = obj_search_result["Objects"] else: return [] if search_results is None: return [] result_set = search_results["MemberSuiteObject"] all_objects = self.result_to_models(result) call_count = 1 """ continue to run queries as long as we - don't exceed the call call_count - don't see results that are less than the limited length (the end) """ while call_count != max_calls and len(result_set) >= limit_to: record_index += len(result_set) # should be `limit_to` result = run_object_query(self.client, base_object_query, record_index, limit_to, verbose) obj_search_result = (result['body']["ExecuteMSQLResult"] ["ResultValue"]["ObjectSearchResult"]) if obj_search_result is not None: search_results = obj_search_result["Objects"] else: search_results = None if search_results is None: result_set = [] else: result_set = search_results["MemberSuiteObject"] all_objects += self.result_to_models(result) call_count += 1 return all_objects
AASHE/python-membersuite-api-client
membersuite_api_client/financial/services.py
get_product
python
def get_product(membersuite_id, client=None): if not membersuite_id: return None client = client or get_new_client(request_session=True) object_query = "SELECT Object() FROM PRODUCT WHERE ID = '{}'".format( membersuite_id) result = client.execute_object_query(object_query) msql_result = result["body"]["ExecuteMSQLResult"] if msql_result["Success"]: membersuite_object_data = (msql_result["ResultValue"] ["SingleObject"]) else: raise ExecuteMSQLError(result=result) return Product(membersuite_object_data=membersuite_object_data)
Return a Product object by ID.
train
https://github.com/AASHE/python-membersuite-api-client/blob/221f5ed8bc7d4424237a4669c5af9edc11819ee9/membersuite_api_client/financial/services.py#L6-L27
[ "def get_new_client(request_session=False):\n \"\"\"Return a new ConciergeClient, pulling secrets from the environment.\n\n \"\"\"\n from .client import ConciergeClient\n client = ConciergeClient(access_key=os.environ[\"MS_ACCESS_KEY\"],\n secret_key=os.environ[\"MS_SECRET_KE...
from ..exceptions import ExecuteMSQLError from ..utils import get_new_client from .models import Product
AASHE/python-membersuite-api-client
membersuite_api_client/memberships/services.py
MembershipService.get_current_membership_for_org
python
def get_current_membership_for_org(self, account_num, verbose=False): all_memberships = self.get_memberships_for_org( account_num=account_num, verbose=verbose) # Look for first membership that hasn't expired yet. for membership in all_memberships: if (membership.expiration_date and membership.expiration_date > datetime.datetime.now()): # noqa return membership # noqa return None
Return a current membership for this org, or, None if there is none.
train
https://github.com/AASHE/python-membersuite-api-client/blob/221f5ed8bc7d4424237a4669c5af9edc11819ee9/membersuite_api_client/memberships/services.py#L22-L34
[ "def get_memberships_for_org(self, account_num, verbose=False):\n \"\"\"\n Retrieve all memberships associated with an organization,\n ordered by expiration date.\n \"\"\"\n if not self.client.session_id:\n self.client.request_session()\n\n query = \"SELECT Objects() FROM Membership \" \\\n...
class MembershipService(ChunkQueryMixin, object): def __init__(self, client): """ Requires a ConciergeClient to connect with MemberSuite """ self.client = client def get_memberships_for_org(self, account_num, verbose=False): """ Retrieve all memberships associated with an organization, ordered by expiration date. """ if not self.client.session_id: self.client.request_session() query = "SELECT Objects() FROM Membership " \ "WHERE Owner = '%s' ORDER BY ExpirationDate" % account_num membership_list = self.get_long_query(query, verbose=verbose) return membership_list or [] def get_all_memberships( self, limit_to=100, max_calls=None, parameters=None, since_when=None, start_record=0, verbose=False): """ Retrieve all memberships updated since "since_when" Loop over queries of size limit_to until either a non-full queryset is returned, or max_depth is reached (used in tests). Then the recursion collapses to return a single concatenated list. """ if not self.client.session_id: self.client.request_session() query = "SELECT Objects() FROM Membership" # collect all where parameters into a list of # (key, operator, value) tuples where_params = [] if parameters: for k, v in parameters.items(): where_params.append((k, "=", v)) if since_when: d = datetime.date.today() - datetime.timedelta(days=since_when) where_params.append( ('LastModifiedDate', ">", "'%s 00:00:00'" % d)) if where_params: query += " WHERE " query += " AND ".join( ["%s %s %s" % (p[0], p[1], p[2]) for p in where_params]) query += " ORDER BY LocalID" # note, get_long_query is overkill when just looking at # one org, but it still only executes once # `get_long_query` uses `ms_object_to_model` to return Organizations membership_list = self.get_long_query( query, limit_to=limit_to, max_calls=max_calls, start_record=start_record, verbose=verbose) return membership_list or [] def ms_object_to_model(self, ms_obj): " Converts an individual result to a Subscription Model " sane_obj = convert_ms_object( ms_obj['Fields']['KeyValueOfstringanyType']) return Membership(sane_obj)
AASHE/python-membersuite-api-client
membersuite_api_client/memberships/services.py
MembershipService.get_memberships_for_org
python
def get_memberships_for_org(self, account_num, verbose=False): if not self.client.session_id: self.client.request_session() query = "SELECT Objects() FROM Membership " \ "WHERE Owner = '%s' ORDER BY ExpirationDate" % account_num membership_list = self.get_long_query(query, verbose=verbose) return membership_list or []
Retrieve all memberships associated with an organization, ordered by expiration date.
train
https://github.com/AASHE/python-membersuite-api-client/blob/221f5ed8bc7d4424237a4669c5af9edc11819ee9/membersuite_api_client/memberships/services.py#L36-L48
[ "def get_long_query(self, base_object_query, limit_to=100, max_calls=None,\n start_record=0, verbose=False):\n \"\"\"\n Takes a base query for all objects and recursively requests them\n\n :param str base_object_query: the base query to be executed\n :param int limit_to: how many rows ...
class MembershipService(ChunkQueryMixin, object): def __init__(self, client): """ Requires a ConciergeClient to connect with MemberSuite """ self.client = client def get_current_membership_for_org(self, account_num, verbose=False): """Return a current membership for this org, or, None if there is none. """ all_memberships = self.get_memberships_for_org( account_num=account_num, verbose=verbose) # Look for first membership that hasn't expired yet. for membership in all_memberships: if (membership.expiration_date and membership.expiration_date > datetime.datetime.now()): # noqa return membership # noqa return None def get_all_memberships( self, limit_to=100, max_calls=None, parameters=None, since_when=None, start_record=0, verbose=False): """ Retrieve all memberships updated since "since_when" Loop over queries of size limit_to until either a non-full queryset is returned, or max_depth is reached (used in tests). Then the recursion collapses to return a single concatenated list. """ if not self.client.session_id: self.client.request_session() query = "SELECT Objects() FROM Membership" # collect all where parameters into a list of # (key, operator, value) tuples where_params = [] if parameters: for k, v in parameters.items(): where_params.append((k, "=", v)) if since_when: d = datetime.date.today() - datetime.timedelta(days=since_when) where_params.append( ('LastModifiedDate', ">", "'%s 00:00:00'" % d)) if where_params: query += " WHERE " query += " AND ".join( ["%s %s %s" % (p[0], p[1], p[2]) for p in where_params]) query += " ORDER BY LocalID" # note, get_long_query is overkill when just looking at # one org, but it still only executes once # `get_long_query` uses `ms_object_to_model` to return Organizations membership_list = self.get_long_query( query, limit_to=limit_to, max_calls=max_calls, start_record=start_record, verbose=verbose) return membership_list or [] def ms_object_to_model(self, ms_obj): " Converts an individual result to a Subscription Model " sane_obj = convert_ms_object( ms_obj['Fields']['KeyValueOfstringanyType']) return Membership(sane_obj)
AASHE/python-membersuite-api-client
membersuite_api_client/memberships/services.py
MembershipService.get_all_memberships
python
def get_all_memberships( self, limit_to=100, max_calls=None, parameters=None, since_when=None, start_record=0, verbose=False): if not self.client.session_id: self.client.request_session() query = "SELECT Objects() FROM Membership" # collect all where parameters into a list of # (key, operator, value) tuples where_params = [] if parameters: for k, v in parameters.items(): where_params.append((k, "=", v)) if since_when: d = datetime.date.today() - datetime.timedelta(days=since_when) where_params.append( ('LastModifiedDate', ">", "'%s 00:00:00'" % d)) if where_params: query += " WHERE " query += " AND ".join( ["%s %s %s" % (p[0], p[1], p[2]) for p in where_params]) query += " ORDER BY LocalID" # note, get_long_query is overkill when just looking at # one org, but it still only executes once # `get_long_query` uses `ms_object_to_model` to return Organizations membership_list = self.get_long_query( query, limit_to=limit_to, max_calls=max_calls, start_record=start_record, verbose=verbose) return membership_list or []
Retrieve all memberships updated since "since_when" Loop over queries of size limit_to until either a non-full queryset is returned, or max_depth is reached (used in tests). Then the recursion collapses to return a single concatenated list.
train
https://github.com/AASHE/python-membersuite-api-client/blob/221f5ed8bc7d4424237a4669c5af9edc11819ee9/membersuite_api_client/memberships/services.py#L50-L92
[ "def get_long_query(self, base_object_query, limit_to=100, max_calls=None,\n start_record=0, verbose=False):\n \"\"\"\n Takes a base query for all objects and recursively requests them\n\n :param str base_object_query: the base query to be executed\n :param int limit_to: how many rows ...
class MembershipService(ChunkQueryMixin, object): def __init__(self, client): """ Requires a ConciergeClient to connect with MemberSuite """ self.client = client def get_current_membership_for_org(self, account_num, verbose=False): """Return a current membership for this org, or, None if there is none. """ all_memberships = self.get_memberships_for_org( account_num=account_num, verbose=verbose) # Look for first membership that hasn't expired yet. for membership in all_memberships: if (membership.expiration_date and membership.expiration_date > datetime.datetime.now()): # noqa return membership # noqa return None def get_memberships_for_org(self, account_num, verbose=False): """ Retrieve all memberships associated with an organization, ordered by expiration date. """ if not self.client.session_id: self.client.request_session() query = "SELECT Objects() FROM Membership " \ "WHERE Owner = '%s' ORDER BY ExpirationDate" % account_num membership_list = self.get_long_query(query, verbose=verbose) return membership_list or [] def ms_object_to_model(self, ms_obj): " Converts an individual result to a Subscription Model " sane_obj = convert_ms_object( ms_obj['Fields']['KeyValueOfstringanyType']) return Membership(sane_obj)
AASHE/python-membersuite-api-client
membersuite_api_client/memberships/services.py
MembershipProductService.get_all_membership_products
python
def get_all_membership_products(self, verbose=False): if not self.client.session_id: self.client.request_session() query = "SELECT Objects() FROM MembershipDuesProduct" membership_product_list = self.get_long_query(query, verbose=verbose) return membership_product_list or []
Retrieves membership product objects
train
https://github.com/AASHE/python-membersuite-api-client/blob/221f5ed8bc7d4424237a4669c5af9edc11819ee9/membersuite_api_client/memberships/services.py#L109-L119
[ "def get_long_query(self, base_object_query, limit_to=100, max_calls=None,\n start_record=0, verbose=False):\n \"\"\"\n Takes a base query for all objects and recursively requests them\n\n :param str base_object_query: the base query to be executed\n :param int limit_to: how many rows ...
class MembershipProductService(ChunkQueryMixin, object): def __init__(self, client): """ Accepts a ConciergeClient to connect with MemberSuite """ self.client = client def ms_object_to_model(self, ms_obj): " Converts an individual result to a Subscription Model " sane_obj = convert_ms_object( ms_obj['Fields']['KeyValueOfstringanyType']) return MembershipProduct(sane_obj)
AASHE/python-membersuite-api-client
membersuite_api_client/utils.py
get_new_client
python
def get_new_client(request_session=False): from .client import ConciergeClient client = ConciergeClient(access_key=os.environ["MS_ACCESS_KEY"], secret_key=os.environ["MS_SECRET_KEY"], association_id=os.environ["MS_ASSOCIATION_ID"]) if request_session: client.request_session() return client
Return a new ConciergeClient, pulling secrets from the environment.
train
https://github.com/AASHE/python-membersuite-api-client/blob/221f5ed8bc7d4424237a4669c5af9edc11819ee9/membersuite_api_client/utils.py#L44-L54
[ "def request_session(self):\n \"\"\"\n Performs initial request to initialize session and get session id\n necessary to construct all future requests.\n :return: Session ID to be placed in header of all other requests.\n \"\"\"\n concierge_request_header = self.construct_concierge_header(\n ...
import os from .exceptions import ExecuteMSQLError, NoResultsError def convert_ms_object(ms_object): """ Converts the list of dictionaries with keys "key" and "value" into more logical value-key pairs in a plain dictionary. """ out_dict = {} for item in ms_object: out_dict[item["Key"]] = item["Value"] return out_dict def get_session_id(result): """Returns the Session ID for an API result. When there's no Session ID, returns None. """ try: return result["header"]["header"]["SessionId"] except TypeError: return None def membersuite_object_factory(membersuite_object_data): from .models import MemberSuiteObject import membersuite_api_client.security.models as security_models klasses = {"Individual": security_models.Individual, "PortalUser": security_models.PortalUser} try: klass = klasses[membersuite_object_data["ClassType"]] except KeyError: return MemberSuiteObject( membersuite_object_data=membersuite_object_data) else: return klass(membersuite_object_data=membersuite_object_data) def submit_msql_object_query(object_query, client=None): """Submit `object_query` to MemberSuite, returning .models.MemberSuiteObjects. So this is a converter from MSQL to .models.MemberSuiteObjects. Returns query results as a list of MemberSuiteObjects. """ client = client or get_new_client() if not client.session_id: client.request_session() result = client.execute_object_query(object_query) execute_msql_result = result["body"]["ExecuteMSQLResult"] membersuite_object_list = [] if execute_msql_result["Success"]: result_value = execute_msql_result["ResultValue"] if result_value["ObjectSearchResult"]["Objects"]: # Multiple results. membersuite_object_list = [] for obj in (result_value["ObjectSearchResult"]["Objects"] ["MemberSuiteObject"]): membersuite_object = membersuite_object_factory(obj) membersuite_object_list.append(membersuite_object) elif result_value["SingleObject"]["ClassType"]: # Only one result. membersuite_object = membersuite_object_factory( execute_msql_result["ResultValue"]["SingleObject"]) membersuite_object_list.append(membersuite_object) elif (result_value["ObjectSearchResult"]["Objects"] is None and result_value["SingleObject"]["ClassType"] is None): raise NoResultsError(result=execute_msql_result) return membersuite_object_list else: # @TODO Fix - exposing only the first of possibly many errors here. raise ExecuteMSQLError(result=execute_msql_result) def value_for_key(membersuite_object_data, key): """Return the value for `key` of membersuite_object_data. """ key_value_dicts = { d['Key']: d['Value'] for d in membersuite_object_data["Fields"]["KeyValueOfstringanyType"]} return key_value_dicts[key]
AASHE/python-membersuite-api-client
membersuite_api_client/utils.py
submit_msql_object_query
python
def submit_msql_object_query(object_query, client=None): client = client or get_new_client() if not client.session_id: client.request_session() result = client.execute_object_query(object_query) execute_msql_result = result["body"]["ExecuteMSQLResult"] membersuite_object_list = [] if execute_msql_result["Success"]: result_value = execute_msql_result["ResultValue"] if result_value["ObjectSearchResult"]["Objects"]: # Multiple results. membersuite_object_list = [] for obj in (result_value["ObjectSearchResult"]["Objects"] ["MemberSuiteObject"]): membersuite_object = membersuite_object_factory(obj) membersuite_object_list.append(membersuite_object) elif result_value["SingleObject"]["ClassType"]: # Only one result. membersuite_object = membersuite_object_factory( execute_msql_result["ResultValue"]["SingleObject"]) membersuite_object_list.append(membersuite_object) elif (result_value["ObjectSearchResult"]["Objects"] is None and result_value["SingleObject"]["ClassType"] is None): raise NoResultsError(result=execute_msql_result) return membersuite_object_list else: # @TODO Fix - exposing only the first of possibly many errors here. raise ExecuteMSQLError(result=execute_msql_result)
Submit `object_query` to MemberSuite, returning .models.MemberSuiteObjects. So this is a converter from MSQL to .models.MemberSuiteObjects. Returns query results as a list of MemberSuiteObjects.
train
https://github.com/AASHE/python-membersuite-api-client/blob/221f5ed8bc7d4424237a4669c5af9edc11819ee9/membersuite_api_client/utils.py#L57-L99
[ "def get_new_client(request_session=False):\n \"\"\"Return a new ConciergeClient, pulling secrets from the environment.\n\n \"\"\"\n from .client import ConciergeClient\n client = ConciergeClient(access_key=os.environ[\"MS_ACCESS_KEY\"],\n secret_key=os.environ[\"MS_SECRET_KE...
import os from .exceptions import ExecuteMSQLError, NoResultsError def convert_ms_object(ms_object): """ Converts the list of dictionaries with keys "key" and "value" into more logical value-key pairs in a plain dictionary. """ out_dict = {} for item in ms_object: out_dict[item["Key"]] = item["Value"] return out_dict def get_session_id(result): """Returns the Session ID for an API result. When there's no Session ID, returns None. """ try: return result["header"]["header"]["SessionId"] except TypeError: return None def membersuite_object_factory(membersuite_object_data): from .models import MemberSuiteObject import membersuite_api_client.security.models as security_models klasses = {"Individual": security_models.Individual, "PortalUser": security_models.PortalUser} try: klass = klasses[membersuite_object_data["ClassType"]] except KeyError: return MemberSuiteObject( membersuite_object_data=membersuite_object_data) else: return klass(membersuite_object_data=membersuite_object_data) def get_new_client(request_session=False): """Return a new ConciergeClient, pulling secrets from the environment. """ from .client import ConciergeClient client = ConciergeClient(access_key=os.environ["MS_ACCESS_KEY"], secret_key=os.environ["MS_SECRET_KEY"], association_id=os.environ["MS_ASSOCIATION_ID"]) if request_session: client.request_session() return client def value_for_key(membersuite_object_data, key): """Return the value for `key` of membersuite_object_data. """ key_value_dicts = { d['Key']: d['Value'] for d in membersuite_object_data["Fields"]["KeyValueOfstringanyType"]} return key_value_dicts[key]
AASHE/python-membersuite-api-client
membersuite_api_client/utils.py
value_for_key
python
def value_for_key(membersuite_object_data, key): key_value_dicts = { d['Key']: d['Value'] for d in membersuite_object_data["Fields"]["KeyValueOfstringanyType"]} return key_value_dicts[key]
Return the value for `key` of membersuite_object_data.
train
https://github.com/AASHE/python-membersuite-api-client/blob/221f5ed8bc7d4424237a4669c5af9edc11819ee9/membersuite_api_client/utils.py#L102-L108
null
import os from .exceptions import ExecuteMSQLError, NoResultsError def convert_ms_object(ms_object): """ Converts the list of dictionaries with keys "key" and "value" into more logical value-key pairs in a plain dictionary. """ out_dict = {} for item in ms_object: out_dict[item["Key"]] = item["Value"] return out_dict def get_session_id(result): """Returns the Session ID for an API result. When there's no Session ID, returns None. """ try: return result["header"]["header"]["SessionId"] except TypeError: return None def membersuite_object_factory(membersuite_object_data): from .models import MemberSuiteObject import membersuite_api_client.security.models as security_models klasses = {"Individual": security_models.Individual, "PortalUser": security_models.PortalUser} try: klass = klasses[membersuite_object_data["ClassType"]] except KeyError: return MemberSuiteObject( membersuite_object_data=membersuite_object_data) else: return klass(membersuite_object_data=membersuite_object_data) def get_new_client(request_session=False): """Return a new ConciergeClient, pulling secrets from the environment. """ from .client import ConciergeClient client = ConciergeClient(access_key=os.environ["MS_ACCESS_KEY"], secret_key=os.environ["MS_SECRET_KEY"], association_id=os.environ["MS_ASSOCIATION_ID"]) if request_session: client.request_session() return client def submit_msql_object_query(object_query, client=None): """Submit `object_query` to MemberSuite, returning .models.MemberSuiteObjects. So this is a converter from MSQL to .models.MemberSuiteObjects. Returns query results as a list of MemberSuiteObjects. """ client = client or get_new_client() if not client.session_id: client.request_session() result = client.execute_object_query(object_query) execute_msql_result = result["body"]["ExecuteMSQLResult"] membersuite_object_list = [] if execute_msql_result["Success"]: result_value = execute_msql_result["ResultValue"] if result_value["ObjectSearchResult"]["Objects"]: # Multiple results. membersuite_object_list = [] for obj in (result_value["ObjectSearchResult"]["Objects"] ["MemberSuiteObject"]): membersuite_object = membersuite_object_factory(obj) membersuite_object_list.append(membersuite_object) elif result_value["SingleObject"]["ClassType"]: # Only one result. membersuite_object = membersuite_object_factory( execute_msql_result["ResultValue"]["SingleObject"]) membersuite_object_list.append(membersuite_object) elif (result_value["ObjectSearchResult"]["Objects"] is None and result_value["SingleObject"]["ClassType"] is None): raise NoResultsError(result=execute_msql_result) return membersuite_object_list else: # @TODO Fix - exposing only the first of possibly many errors here. raise ExecuteMSQLError(result=execute_msql_result)
AASHE/python-membersuite-api-client
membersuite_api_client/client.py
ConciergeClient.get_hashed_signature
python
def get_hashed_signature(self, url): data = "%s%s" % (url, self.association_id) if self.session_id: data = "%s%s" % (data, self.session_id) data_b = bytearray(data, 'utf-8') secret_key = base64.b64decode(self.secret_key) secret_b = bytearray(secret_key) hashed = hmac.new(secret_b, data_b, sha1).digest() return base64.b64encode(hashed).decode("utf-8")
Process from Membersuite Docs: http://bit.ly/2eSIDxz
train
https://github.com/AASHE/python-membersuite-api-client/blob/221f5ed8bc7d4424237a4669c5af9edc11819ee9/membersuite_api_client/client.py#L31-L43
null
class ConciergeClient(object): def __init__(self, access_key, secret_key, association_id): """ Initializes Client object by pulling in authentication credentials. Altered to make "request_session" a manual call to facilitate testing. """ self.access_key = access_key self.secret_key = secret_key self.association_id = association_id self.session_id = None self.client = Client('https://soap.membersuite.com/mex') def request_session(self): """ Performs initial request to initialize session and get session id necessary to construct all future requests. :return: Session ID to be placed in header of all other requests. """ concierge_request_header = self.construct_concierge_header( url="http://membersuite.com/contracts/IConciergeAPIService/WhoAmI") result = self.client.service.WhoAmI( _soapheaders=[concierge_request_header]) self.session_id = get_session_id(result=result) if not self.session_id: raise MembersuiteLoginError( result["body"]["WhoAmIResult"]["Errors"]) return self.session_id def construct_concierge_header(self, url): """ Constructs the Concierge Request Header lxml object to be used as the '_soapheaders' argument for WSDL methods. """ concierge_request_header = ( etree.Element( etree.QName(XHTML_NAMESPACE, "ConciergeRequestHeader"), nsmap={'sch': XHTML_NAMESPACE})) if self.session_id: session = ( etree.SubElement(concierge_request_header, etree.QName(XHTML_NAMESPACE, "SessionId"))) session.text = self.session_id access_key = ( etree.SubElement(concierge_request_header, etree.QName(XHTML_NAMESPACE, "AccessKeyId"))) access_key.text = self.access_key association_id = (etree.SubElement(concierge_request_header, etree.QName(XHTML_NAMESPACE, "AssociationId"))) association_id.text = self.association_id signature = ( etree.SubElement(concierge_request_header, etree.QName(XHTML_NAMESPACE, "Signature"))) signature.text = self.get_hashed_signature(url=url) return concierge_request_header def execute_object_query(self, object_query, start_record=0, limit_to=400): concierge_request_header = self.construct_concierge_header( url="http://membersuite.com/contracts/" "IConciergeAPIService/ExecuteMSQL") result = self.client.service.ExecuteMSQL( _soapheaders=[concierge_request_header], msqlStatement=object_query, startRecord=start_record, maximumNumberOfRecordsToReturn=limit_to, ) return result
AASHE/python-membersuite-api-client
membersuite_api_client/client.py
ConciergeClient.request_session
python
def request_session(self): concierge_request_header = self.construct_concierge_header( url="http://membersuite.com/contracts/IConciergeAPIService/WhoAmI") result = self.client.service.WhoAmI( _soapheaders=[concierge_request_header]) self.session_id = get_session_id(result=result) if not self.session_id: raise MembersuiteLoginError( result["body"]["WhoAmIResult"]["Errors"]) return self.session_id
Performs initial request to initialize session and get session id necessary to construct all future requests. :return: Session ID to be placed in header of all other requests.
train
https://github.com/AASHE/python-membersuite-api-client/blob/221f5ed8bc7d4424237a4669c5af9edc11819ee9/membersuite_api_client/client.py#L45-L63
[ "def get_session_id(result):\n \"\"\"Returns the Session ID for an API result.\n\n When there's no Session ID, returns None.\n \"\"\"\n try:\n return result[\"header\"][\"header\"][\"SessionId\"]\n except TypeError:\n return None\n", "def construct_concierge_header(self, url):\n \"...
class ConciergeClient(object): def __init__(self, access_key, secret_key, association_id): """ Initializes Client object by pulling in authentication credentials. Altered to make "request_session" a manual call to facilitate testing. """ self.access_key = access_key self.secret_key = secret_key self.association_id = association_id self.session_id = None self.client = Client('https://soap.membersuite.com/mex') def get_hashed_signature(self, url): """ Process from Membersuite Docs: http://bit.ly/2eSIDxz """ data = "%s%s" % (url, self.association_id) if self.session_id: data = "%s%s" % (data, self.session_id) data_b = bytearray(data, 'utf-8') secret_key = base64.b64decode(self.secret_key) secret_b = bytearray(secret_key) hashed = hmac.new(secret_b, data_b, sha1).digest() return base64.b64encode(hashed).decode("utf-8") def construct_concierge_header(self, url): """ Constructs the Concierge Request Header lxml object to be used as the '_soapheaders' argument for WSDL methods. """ concierge_request_header = ( etree.Element( etree.QName(XHTML_NAMESPACE, "ConciergeRequestHeader"), nsmap={'sch': XHTML_NAMESPACE})) if self.session_id: session = ( etree.SubElement(concierge_request_header, etree.QName(XHTML_NAMESPACE, "SessionId"))) session.text = self.session_id access_key = ( etree.SubElement(concierge_request_header, etree.QName(XHTML_NAMESPACE, "AccessKeyId"))) access_key.text = self.access_key association_id = (etree.SubElement(concierge_request_header, etree.QName(XHTML_NAMESPACE, "AssociationId"))) association_id.text = self.association_id signature = ( etree.SubElement(concierge_request_header, etree.QName(XHTML_NAMESPACE, "Signature"))) signature.text = self.get_hashed_signature(url=url) return concierge_request_header def execute_object_query(self, object_query, start_record=0, limit_to=400): concierge_request_header = self.construct_concierge_header( url="http://membersuite.com/contracts/" "IConciergeAPIService/ExecuteMSQL") result = self.client.service.ExecuteMSQL( _soapheaders=[concierge_request_header], msqlStatement=object_query, startRecord=start_record, maximumNumberOfRecordsToReturn=limit_to, ) return result
AASHE/python-membersuite-api-client
membersuite_api_client/client.py
ConciergeClient.construct_concierge_header
python
def construct_concierge_header(self, url): concierge_request_header = ( etree.Element( etree.QName(XHTML_NAMESPACE, "ConciergeRequestHeader"), nsmap={'sch': XHTML_NAMESPACE})) if self.session_id: session = ( etree.SubElement(concierge_request_header, etree.QName(XHTML_NAMESPACE, "SessionId"))) session.text = self.session_id access_key = ( etree.SubElement(concierge_request_header, etree.QName(XHTML_NAMESPACE, "AccessKeyId"))) access_key.text = self.access_key association_id = (etree.SubElement(concierge_request_header, etree.QName(XHTML_NAMESPACE, "AssociationId"))) association_id.text = self.association_id signature = ( etree.SubElement(concierge_request_header, etree.QName(XHTML_NAMESPACE, "Signature"))) signature.text = self.get_hashed_signature(url=url) return concierge_request_header
Constructs the Concierge Request Header lxml object to be used as the '_soapheaders' argument for WSDL methods.
train
https://github.com/AASHE/python-membersuite-api-client/blob/221f5ed8bc7d4424237a4669c5af9edc11819ee9/membersuite_api_client/client.py#L65-L96
[ "def get_hashed_signature(self, url):\n \"\"\"\n Process from Membersuite Docs: http://bit.ly/2eSIDxz\n \"\"\"\n data = \"%s%s\" % (url, self.association_id)\n if self.session_id:\n data = \"%s%s\" % (data, self.session_id)\n data_b = bytearray(data, 'utf-8')\n secret_key = base64.b64dec...
class ConciergeClient(object): def __init__(self, access_key, secret_key, association_id): """ Initializes Client object by pulling in authentication credentials. Altered to make "request_session" a manual call to facilitate testing. """ self.access_key = access_key self.secret_key = secret_key self.association_id = association_id self.session_id = None self.client = Client('https://soap.membersuite.com/mex') def get_hashed_signature(self, url): """ Process from Membersuite Docs: http://bit.ly/2eSIDxz """ data = "%s%s" % (url, self.association_id) if self.session_id: data = "%s%s" % (data, self.session_id) data_b = bytearray(data, 'utf-8') secret_key = base64.b64decode(self.secret_key) secret_b = bytearray(secret_key) hashed = hmac.new(secret_b, data_b, sha1).digest() return base64.b64encode(hashed).decode("utf-8") def request_session(self): """ Performs initial request to initialize session and get session id necessary to construct all future requests. :return: Session ID to be placed in header of all other requests. """ concierge_request_header = self.construct_concierge_header( url="http://membersuite.com/contracts/IConciergeAPIService/WhoAmI") result = self.client.service.WhoAmI( _soapheaders=[concierge_request_header]) self.session_id = get_session_id(result=result) if not self.session_id: raise MembersuiteLoginError( result["body"]["WhoAmIResult"]["Errors"]) return self.session_id def execute_object_query(self, object_query, start_record=0, limit_to=400): concierge_request_header = self.construct_concierge_header( url="http://membersuite.com/contracts/" "IConciergeAPIService/ExecuteMSQL") result = self.client.service.ExecuteMSQL( _soapheaders=[concierge_request_header], msqlStatement=object_query, startRecord=start_record, maximumNumberOfRecordsToReturn=limit_to, ) return result
AASHE/python-membersuite-api-client
membersuite_api_client/security/services.py
login_to_portal
python
def login_to_portal(username, password, client, retries=2, delay=0): if not client.session_id: client.request_session() concierge_request_header = client.construct_concierge_header( url=("http://membersuite.com/contracts/IConciergeAPIService/" "LoginToPortal")) attempts = 0 while attempts < retries: if attempts: time.sleep(delay) result = client.client.service.LoginToPortal( _soapheaders=[concierge_request_header], portalUserName=username, portalPassword=password) login_to_portal_result = result["body"]["LoginToPortalResult"] if login_to_portal_result["Success"]: portal_user = login_to_portal_result["ResultValue"]["PortalUser"] session_id = get_session_id(result=result) return PortalUser(membersuite_object_data=portal_user, session_id=session_id) else: attempts += 1 try: error_code = login_to_portal_result[ "Errors"]["ConciergeError"][0]["Code"] except IndexError: # Not a ConciergeError continue else: if attempts < retries and error_code == "GeneralException": continue raise LoginToPortalError(result=result)
Log `username` into the MemberSuite Portal. Returns a PortalUser object if successful, raises LoginToPortalError if not. Will retry logging in if a GeneralException occurs, up to `retries`. Will pause `delay` seconds between retries.
train
https://github.com/AASHE/python-membersuite-api-client/blob/221f5ed8bc7d4424237a4669c5af9edc11819ee9/membersuite_api_client/security/services.py#L10-L56
[ "def get_session_id(result):\n \"\"\"Returns the Session ID for an API result.\n\n When there's no Session ID, returns None.\n \"\"\"\n try:\n return result[\"header\"][\"header\"][\"SessionId\"]\n except TypeError:\n return None\n" ]
import time from django.contrib.auth.models import User from .models import PortalUser, generate_username from ..exceptions import LoginToPortalError, LogoutError from ..utils import get_session_id def logout(client): """Log out the currently logged-in user. There's a really crappy side-effect here - the session_id attribute of the `client` passed in will be reset to None if the logout succeeds, which is going to be almost always, let's hope. """ if not client.session_id: client.request_session() concierge_request_header = client.construct_concierge_header( url=("http://membersuite.com/contracts/IConciergeAPIService/" "Logout")) logout_result = client.client.service.Logout( _soapheaders=[concierge_request_header]) result = logout_result["body"]["LogoutResult"] if result["SessionID"] is None: # Success! client.session_id = None else: # Failure . . . raise LogoutError(result=result) # get_user_for_membersuite_entity introduces a dependency on # Django (django.contrib.auth.models, to be precise). That's # quite a drag. Goes someplace else. Need to drop dependency # on Django. def get_user_for_membersuite_entity(membersuite_entity): """Returns a User for `membersuite_entity`. membersuite_entity is any MemberSuite object that has the fields membersuite_id, email_address, first_name, and last_name, e.g., PortalUser or Individual. """ user = None user_created = False # First, try to match on username. user_username = generate_username(membersuite_entity) try: user = User.objects.get(username=user_username) except User.DoesNotExist: pass # Next, try to match on email address. if not user: try: user = User.objects.filter( email=membersuite_entity.email_address)[0] except IndexError: pass # No match? Create one. if not user: user = User.objects.create( username=user_username, email=membersuite_entity.email_address, first_name=membersuite_entity.first_name, last_name=membersuite_entity.last_name) user_created = True return user, user_created
AASHE/python-membersuite-api-client
membersuite_api_client/security/services.py
logout
python
def logout(client): if not client.session_id: client.request_session() concierge_request_header = client.construct_concierge_header( url=("http://membersuite.com/contracts/IConciergeAPIService/" "Logout")) logout_result = client.client.service.Logout( _soapheaders=[concierge_request_header]) result = logout_result["body"]["LogoutResult"] if result["SessionID"] is None: # Success! client.session_id = None else: # Failure . . . raise LogoutError(result=result)
Log out the currently logged-in user. There's a really crappy side-effect here - the session_id attribute of the `client` passed in will be reset to None if the logout succeeds, which is going to be almost always, let's hope.
train
https://github.com/AASHE/python-membersuite-api-client/blob/221f5ed8bc7d4424237a4669c5af9edc11819ee9/membersuite_api_client/security/services.py#L59-L82
null
import time from django.contrib.auth.models import User from .models import PortalUser, generate_username from ..exceptions import LoginToPortalError, LogoutError from ..utils import get_session_id def login_to_portal(username, password, client, retries=2, delay=0): """Log `username` into the MemberSuite Portal. Returns a PortalUser object if successful, raises LoginToPortalError if not. Will retry logging in if a GeneralException occurs, up to `retries`. Will pause `delay` seconds between retries. """ if not client.session_id: client.request_session() concierge_request_header = client.construct_concierge_header( url=("http://membersuite.com/contracts/IConciergeAPIService/" "LoginToPortal")) attempts = 0 while attempts < retries: if attempts: time.sleep(delay) result = client.client.service.LoginToPortal( _soapheaders=[concierge_request_header], portalUserName=username, portalPassword=password) login_to_portal_result = result["body"]["LoginToPortalResult"] if login_to_portal_result["Success"]: portal_user = login_to_portal_result["ResultValue"]["PortalUser"] session_id = get_session_id(result=result) return PortalUser(membersuite_object_data=portal_user, session_id=session_id) else: attempts += 1 try: error_code = login_to_portal_result[ "Errors"]["ConciergeError"][0]["Code"] except IndexError: # Not a ConciergeError continue else: if attempts < retries and error_code == "GeneralException": continue raise LoginToPortalError(result=result) # get_user_for_membersuite_entity introduces a dependency on # Django (django.contrib.auth.models, to be precise). That's # quite a drag. Goes someplace else. Need to drop dependency # on Django. def get_user_for_membersuite_entity(membersuite_entity): """Returns a User for `membersuite_entity`. membersuite_entity is any MemberSuite object that has the fields membersuite_id, email_address, first_name, and last_name, e.g., PortalUser or Individual. """ user = None user_created = False # First, try to match on username. user_username = generate_username(membersuite_entity) try: user = User.objects.get(username=user_username) except User.DoesNotExist: pass # Next, try to match on email address. if not user: try: user = User.objects.filter( email=membersuite_entity.email_address)[0] except IndexError: pass # No match? Create one. if not user: user = User.objects.create( username=user_username, email=membersuite_entity.email_address, first_name=membersuite_entity.first_name, last_name=membersuite_entity.last_name) user_created = True return user, user_created
AASHE/python-membersuite-api-client
membersuite_api_client/security/services.py
get_user_for_membersuite_entity
python
def get_user_for_membersuite_entity(membersuite_entity): user = None user_created = False # First, try to match on username. user_username = generate_username(membersuite_entity) try: user = User.objects.get(username=user_username) except User.DoesNotExist: pass # Next, try to match on email address. if not user: try: user = User.objects.filter( email=membersuite_entity.email_address)[0] except IndexError: pass # No match? Create one. if not user: user = User.objects.create( username=user_username, email=membersuite_entity.email_address, first_name=membersuite_entity.first_name, last_name=membersuite_entity.last_name) user_created = True return user, user_created
Returns a User for `membersuite_entity`. membersuite_entity is any MemberSuite object that has the fields membersuite_id, email_address, first_name, and last_name, e.g., PortalUser or Individual.
train
https://github.com/AASHE/python-membersuite-api-client/blob/221f5ed8bc7d4424237a4669c5af9edc11819ee9/membersuite_api_client/security/services.py#L89-L124
[ "def generate_username(membersuite_object):\n \"\"\"Return a username suitable for storing in auth.User.username.\n\n Has to be <= 30 characters long. (Until we drop support for\n Django 1.4, after which we can define a custom User model with\n a larger username field.)\n\n We want to incorporate th...
import time from django.contrib.auth.models import User from .models import PortalUser, generate_username from ..exceptions import LoginToPortalError, LogoutError from ..utils import get_session_id def login_to_portal(username, password, client, retries=2, delay=0): """Log `username` into the MemberSuite Portal. Returns a PortalUser object if successful, raises LoginToPortalError if not. Will retry logging in if a GeneralException occurs, up to `retries`. Will pause `delay` seconds between retries. """ if not client.session_id: client.request_session() concierge_request_header = client.construct_concierge_header( url=("http://membersuite.com/contracts/IConciergeAPIService/" "LoginToPortal")) attempts = 0 while attempts < retries: if attempts: time.sleep(delay) result = client.client.service.LoginToPortal( _soapheaders=[concierge_request_header], portalUserName=username, portalPassword=password) login_to_portal_result = result["body"]["LoginToPortalResult"] if login_to_portal_result["Success"]: portal_user = login_to_portal_result["ResultValue"]["PortalUser"] session_id = get_session_id(result=result) return PortalUser(membersuite_object_data=portal_user, session_id=session_id) else: attempts += 1 try: error_code = login_to_portal_result[ "Errors"]["ConciergeError"][0]["Code"] except IndexError: # Not a ConciergeError continue else: if attempts < retries and error_code == "GeneralException": continue raise LoginToPortalError(result=result) def logout(client): """Log out the currently logged-in user. There's a really crappy side-effect here - the session_id attribute of the `client` passed in will be reset to None if the logout succeeds, which is going to be almost always, let's hope. """ if not client.session_id: client.request_session() concierge_request_header = client.construct_concierge_header( url=("http://membersuite.com/contracts/IConciergeAPIService/" "Logout")) logout_result = client.client.service.Logout( _soapheaders=[concierge_request_header]) result = logout_result["body"]["LogoutResult"] if result["SessionID"] is None: # Success! client.session_id = None else: # Failure . . . raise LogoutError(result=result) # get_user_for_membersuite_entity introduces a dependency on # Django (django.contrib.auth.models, to be precise). That's # quite a drag. Goes someplace else. Need to drop dependency # on Django.
sublee/etc
etc/helpers.py
registry
python
def registry(attr, base=type): class Registry(base): def __init__(cls, name, bases, attrs): super(Registry, cls).__init__(name, bases, attrs) if not hasattr(cls, '__registry__'): cls.__registry__ = {} key = getattr(cls, attr) if key is not NotImplemented: assert key not in cls.__registry__ cls.__registry__[key] = cls def __dispatch__(cls, key): try: return cls.__registry__[key] except KeyError: raise ValueError('Unknown %s: %s' % (attr, key)) return Registry
Generates a meta class to index sub classes by their keys.
train
https://github.com/sublee/etc/blob/f2be64604da5af0d7739cfacf36f55712f0fc5cb/etc/helpers.py#L18-L34
null
# -*- coding: utf-8 -*- """ etc.helpers ~~~~~~~~~~~ """ from __future__ import absolute_import import io __all__ = ['gen_repr', 'Missing', 'registry'] #: The placeholder for missing parameters. Missing = object() def gen_repr(cls, template, *args, **kwargs): """Generates a string for :func:`repr`.""" buf = io.StringIO() buf.write(u'<') buf.write(cls.__module__.decode() if kwargs.pop('full', False) else u'etc') buf.write(u'.') buf.write(cls.__name__.decode()) if not kwargs.pop('dense', False): buf.write(u' ') buf.write(template.format(*args, **kwargs)) options = kwargs.pop('options', []) for attr, value in options: if value is not None: buf.write(u' %s=%s' % (attr, value)) buf.write(u'>') return buf.getvalue()
sublee/etc
etc/helpers.py
gen_repr
python
def gen_repr(cls, template, *args, **kwargs): buf = io.StringIO() buf.write(u'<') buf.write(cls.__module__.decode() if kwargs.pop('full', False) else u'etc') buf.write(u'.') buf.write(cls.__name__.decode()) if not kwargs.pop('dense', False): buf.write(u' ') buf.write(template.format(*args, **kwargs)) options = kwargs.pop('options', []) for attr, value in options: if value is not None: buf.write(u' %s=%s' % (attr, value)) buf.write(u'>') return buf.getvalue()
Generates a string for :func:`repr`.
train
https://github.com/sublee/etc/blob/f2be64604da5af0d7739cfacf36f55712f0fc5cb/etc/helpers.py#L37-L52
null
# -*- coding: utf-8 -*- """ etc.helpers ~~~~~~~~~~~ """ from __future__ import absolute_import import io __all__ = ['gen_repr', 'Missing', 'registry'] #: The placeholder for missing parameters. Missing = object() def registry(attr, base=type): """Generates a meta class to index sub classes by their keys.""" class Registry(base): def __init__(cls, name, bases, attrs): super(Registry, cls).__init__(name, bases, attrs) if not hasattr(cls, '__registry__'): cls.__registry__ = {} key = getattr(cls, attr) if key is not NotImplemented: assert key not in cls.__registry__ cls.__registry__[key] = cls def __dispatch__(cls, key): try: return cls.__registry__[key] except KeyError: raise ValueError('Unknown %s: %s' % (attr, key)) return Registry
sublee/etc
etc/__init__.py
etcd
python
def etcd(url=DEFAULT_URL, mock=False, **kwargs): if mock: from etc.adapters.mock import MockAdapter adapter_class = MockAdapter else: from etc.adapters.etcd import EtcdAdapter adapter_class = EtcdAdapter return Client(adapter_class(url, **kwargs))
Creates an etcd client.
train
https://github.com/sublee/etc/blob/f2be64604da5af0d7739cfacf36f55712f0fc5cb/etc/__init__.py#L60-L68
null
# -*- coding: utf-8 -*- """ etc ~~~ An etcd client library for humans. - Don't mix "camelCase" on your Python code. - Test without real etcd by mockup clients. - Proper options for actions. - Sugars for most cases. :copyright: (c) 2016-2017 by Heungsub Lee :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import from etc.__about__ import __version__ # noqa from etc.client import Client from etc.errors import ( ConnectionError, ConnectionRefused, DirNotEmpty, EtcdError, EtcException, EventIndexCleared, ExistingPeerAddr, HTTPError, IndexNaN, IndexOrValueRequired, IndexValueMutex, InvalidActiveSize, InvalidField, InvalidForm, InvalidRemoveDelay, KeyIsPreserved, KeyNotFound, LeaderElect, NameRequired, NodeExist, NoMorePeer, NotDir, NotFile, PrevValueRequired, RaftInternal, RefreshTTLRequired, RefreshValue, RootROnly, StandbyInternal, TestFailed, TimedOut, TimeoutNaN, TTLNaN, Unauthorized, ValueOrTTLRequired, ValueRequired, WatcherCleared) from etc.results import ( ComparedThenDeleted, ComparedThenSwapped, Created, Deleted, Directory, EtcdResult, Expired, Got, Node, Set, Updated, Value) __all__ = [ # etc 'etcd', # etc.client 'Client', # etc.errors 'ConnectionError', 'ConnectionRefused', 'DirNotEmpty', 'EtcdError', 'EtcException', 'EventIndexCleared', 'ExistingPeerAddr', 'IndexNaN', 'IndexOrValueRequired', 'IndexValueMutex', 'InvalidActiveSize', 'InvalidField', 'InvalidForm', 'InvalidRemoveDelay', 'KeyIsPreserved', 'KeyNotFound', 'LeaderElect', 'NameRequired', 'NodeExist', 'NoMorePeer', 'NotDir', 'NotFile', 'PrevValueRequired', 'RaftInternal', 'RefreshTTLRequired', 'RefreshValue', 'RootROnly', 'StandbyInternal', 'TestFailed', 'TimedOut', 'TimeoutNaN', 'TTLNaN', 'Unauthorized', 'ValueOrTTLRequired', 'ValueRequired', 'WatcherCleared', # etc.results 'ComparedThenDeleted', 'ComparedThenSwapped', 'Created', 'Deleted', 'Directory', 'EtcdResult', 'Expired', 'Got', 'Node', 'Set', 'Updated', 'Value', ] DEFAULT_URL = 'http://127.0.0.1:4001'
sublee/etc
etc/client.py
Client.get
python
def get(self, key, recursive=False, sorted=False, quorum=False, timeout=None): return self.adapter.get(key, recursive=recursive, sorted=sorted, quorum=quorum, timeout=timeout)
Gets a value of key.
train
https://github.com/sublee/etc/blob/f2be64604da5af0d7739cfacf36f55712f0fc5cb/etc/client.py#L29-L33
null
class Client(object): def __init__(self, adapter): self.adapter = adapter @property def url(self): return self.adapter.url def clear(self): return self.adapter.clear() def __repr__(self): return gen_repr(self.__class__, u"'{0}'", self.url, short=True) def wait(self, key, index=0, recursive=False, sorted=False, quorum=False, timeout=None): """Waits until a node changes.""" return self.adapter.get(key, recursive=recursive, sorted=sorted, quorum=quorum, wait=True, wait_index=index, timeout=timeout) def set(self, key, value=None, dir=False, ttl=None, refresh=False, prev_value=None, prev_index=None, timeout=None): """Sets a value to a key.""" return self.adapter.set(key, value, dir=dir, ttl=ttl, refresh=refresh, prev_value=prev_value, prev_index=prev_index, timeout=timeout) def refresh(self, key, ttl, prev_value=None, prev_index=None, timeout=None): """Sets only a TTL of a key. The waiters doesn't receive notification by this operation. """ return self.adapter.set(key, ttl=ttl, refresh=True, prev_value=prev_value, prev_index=prev_index, timeout=timeout) def create(self, key, value=None, dir=False, ttl=None, timeout=None): """Creates a new key.""" return self.adapter.set(key, value, dir=dir, ttl=ttl, prev_exist=False, timeout=timeout) def update(self, key, value=None, dir=False, ttl=None, refresh=False, prev_value=None, prev_index=None, timeout=None): """Updates an existing key.""" return self.adapter.set(key, value, dir=dir, ttl=ttl, refresh=refresh, prev_value=prev_value, prev_index=prev_index, prev_exist=True, timeout=timeout) def append(self, key, value=None, dir=False, ttl=None, timeout=None): """Creates a new automatically increasing key in the given directory key. """ return self.adapter.append(key, value, dir=dir, ttl=ttl, timeout=timeout) def delete(self, key, dir=False, recursive=False, prev_value=None, prev_index=None, timeout=None): """Deletes a key.""" return self.adapter.delete(key, dir=dir, recursive=recursive, prev_value=prev_value, prev_index=prev_index, timeout=timeout)
sublee/etc
etc/client.py
Client.wait
python
def wait(self, key, index=0, recursive=False, sorted=False, quorum=False, timeout=None): return self.adapter.get(key, recursive=recursive, sorted=sorted, quorum=quorum, wait=True, wait_index=index, timeout=timeout)
Waits until a node changes.
train
https://github.com/sublee/etc/blob/f2be64604da5af0d7739cfacf36f55712f0fc5cb/etc/client.py#L35-L40
null
class Client(object): def __init__(self, adapter): self.adapter = adapter @property def url(self): return self.adapter.url def clear(self): return self.adapter.clear() def __repr__(self): return gen_repr(self.__class__, u"'{0}'", self.url, short=True) def get(self, key, recursive=False, sorted=False, quorum=False, timeout=None): """Gets a value of key.""" return self.adapter.get(key, recursive=recursive, sorted=sorted, quorum=quorum, timeout=timeout) def set(self, key, value=None, dir=False, ttl=None, refresh=False, prev_value=None, prev_index=None, timeout=None): """Sets a value to a key.""" return self.adapter.set(key, value, dir=dir, ttl=ttl, refresh=refresh, prev_value=prev_value, prev_index=prev_index, timeout=timeout) def refresh(self, key, ttl, prev_value=None, prev_index=None, timeout=None): """Sets only a TTL of a key. The waiters doesn't receive notification by this operation. """ return self.adapter.set(key, ttl=ttl, refresh=True, prev_value=prev_value, prev_index=prev_index, timeout=timeout) def create(self, key, value=None, dir=False, ttl=None, timeout=None): """Creates a new key.""" return self.adapter.set(key, value, dir=dir, ttl=ttl, prev_exist=False, timeout=timeout) def update(self, key, value=None, dir=False, ttl=None, refresh=False, prev_value=None, prev_index=None, timeout=None): """Updates an existing key.""" return self.adapter.set(key, value, dir=dir, ttl=ttl, refresh=refresh, prev_value=prev_value, prev_index=prev_index, prev_exist=True, timeout=timeout) def append(self, key, value=None, dir=False, ttl=None, timeout=None): """Creates a new automatically increasing key in the given directory key. """ return self.adapter.append(key, value, dir=dir, ttl=ttl, timeout=timeout) def delete(self, key, dir=False, recursive=False, prev_value=None, prev_index=None, timeout=None): """Deletes a key.""" return self.adapter.delete(key, dir=dir, recursive=recursive, prev_value=prev_value, prev_index=prev_index, timeout=timeout)
sublee/etc
etc/client.py
Client.refresh
python
def refresh(self, key, ttl, prev_value=None, prev_index=None, timeout=None): return self.adapter.set(key, ttl=ttl, refresh=True, prev_value=prev_value, prev_index=prev_index, timeout=timeout)
Sets only a TTL of a key. The waiters doesn't receive notification by this operation.
train
https://github.com/sublee/etc/blob/f2be64604da5af0d7739cfacf36f55712f0fc5cb/etc/client.py#L49-L56
null
class Client(object): def __init__(self, adapter): self.adapter = adapter @property def url(self): return self.adapter.url def clear(self): return self.adapter.clear() def __repr__(self): return gen_repr(self.__class__, u"'{0}'", self.url, short=True) def get(self, key, recursive=False, sorted=False, quorum=False, timeout=None): """Gets a value of key.""" return self.adapter.get(key, recursive=recursive, sorted=sorted, quorum=quorum, timeout=timeout) def wait(self, key, index=0, recursive=False, sorted=False, quorum=False, timeout=None): """Waits until a node changes.""" return self.adapter.get(key, recursive=recursive, sorted=sorted, quorum=quorum, wait=True, wait_index=index, timeout=timeout) def set(self, key, value=None, dir=False, ttl=None, refresh=False, prev_value=None, prev_index=None, timeout=None): """Sets a value to a key.""" return self.adapter.set(key, value, dir=dir, ttl=ttl, refresh=refresh, prev_value=prev_value, prev_index=prev_index, timeout=timeout) def create(self, key, value=None, dir=False, ttl=None, timeout=None): """Creates a new key.""" return self.adapter.set(key, value, dir=dir, ttl=ttl, prev_exist=False, timeout=timeout) def update(self, key, value=None, dir=False, ttl=None, refresh=False, prev_value=None, prev_index=None, timeout=None): """Updates an existing key.""" return self.adapter.set(key, value, dir=dir, ttl=ttl, refresh=refresh, prev_value=prev_value, prev_index=prev_index, prev_exist=True, timeout=timeout) def append(self, key, value=None, dir=False, ttl=None, timeout=None): """Creates a new automatically increasing key in the given directory key. """ return self.adapter.append(key, value, dir=dir, ttl=ttl, timeout=timeout) def delete(self, key, dir=False, recursive=False, prev_value=None, prev_index=None, timeout=None): """Deletes a key.""" return self.adapter.delete(key, dir=dir, recursive=recursive, prev_value=prev_value, prev_index=prev_index, timeout=timeout)
sublee/etc
etc/client.py
Client.create
python
def create(self, key, value=None, dir=False, ttl=None, timeout=None): return self.adapter.set(key, value, dir=dir, ttl=ttl, prev_exist=False, timeout=timeout)
Creates a new key.
train
https://github.com/sublee/etc/blob/f2be64604da5af0d7739cfacf36f55712f0fc5cb/etc/client.py#L58-L61
null
class Client(object): def __init__(self, adapter): self.adapter = adapter @property def url(self): return self.adapter.url def clear(self): return self.adapter.clear() def __repr__(self): return gen_repr(self.__class__, u"'{0}'", self.url, short=True) def get(self, key, recursive=False, sorted=False, quorum=False, timeout=None): """Gets a value of key.""" return self.adapter.get(key, recursive=recursive, sorted=sorted, quorum=quorum, timeout=timeout) def wait(self, key, index=0, recursive=False, sorted=False, quorum=False, timeout=None): """Waits until a node changes.""" return self.adapter.get(key, recursive=recursive, sorted=sorted, quorum=quorum, wait=True, wait_index=index, timeout=timeout) def set(self, key, value=None, dir=False, ttl=None, refresh=False, prev_value=None, prev_index=None, timeout=None): """Sets a value to a key.""" return self.adapter.set(key, value, dir=dir, ttl=ttl, refresh=refresh, prev_value=prev_value, prev_index=prev_index, timeout=timeout) def refresh(self, key, ttl, prev_value=None, prev_index=None, timeout=None): """Sets only a TTL of a key. The waiters doesn't receive notification by this operation. """ return self.adapter.set(key, ttl=ttl, refresh=True, prev_value=prev_value, prev_index=prev_index, timeout=timeout) def update(self, key, value=None, dir=False, ttl=None, refresh=False, prev_value=None, prev_index=None, timeout=None): """Updates an existing key.""" return self.adapter.set(key, value, dir=dir, ttl=ttl, refresh=refresh, prev_value=prev_value, prev_index=prev_index, prev_exist=True, timeout=timeout) def append(self, key, value=None, dir=False, ttl=None, timeout=None): """Creates a new automatically increasing key in the given directory key. """ return self.adapter.append(key, value, dir=dir, ttl=ttl, timeout=timeout) def delete(self, key, dir=False, recursive=False, prev_value=None, prev_index=None, timeout=None): """Deletes a key.""" return self.adapter.delete(key, dir=dir, recursive=recursive, prev_value=prev_value, prev_index=prev_index, timeout=timeout)
sublee/etc
etc/client.py
Client.update
python
def update(self, key, value=None, dir=False, ttl=None, refresh=False, prev_value=None, prev_index=None, timeout=None): return self.adapter.set(key, value, dir=dir, ttl=ttl, refresh=refresh, prev_value=prev_value, prev_index=prev_index, prev_exist=True, timeout=timeout)
Updates an existing key.
train
https://github.com/sublee/etc/blob/f2be64604da5af0d7739cfacf36f55712f0fc5cb/etc/client.py#L63-L68
null
class Client(object): def __init__(self, adapter): self.adapter = adapter @property def url(self): return self.adapter.url def clear(self): return self.adapter.clear() def __repr__(self): return gen_repr(self.__class__, u"'{0}'", self.url, short=True) def get(self, key, recursive=False, sorted=False, quorum=False, timeout=None): """Gets a value of key.""" return self.adapter.get(key, recursive=recursive, sorted=sorted, quorum=quorum, timeout=timeout) def wait(self, key, index=0, recursive=False, sorted=False, quorum=False, timeout=None): """Waits until a node changes.""" return self.adapter.get(key, recursive=recursive, sorted=sorted, quorum=quorum, wait=True, wait_index=index, timeout=timeout) def set(self, key, value=None, dir=False, ttl=None, refresh=False, prev_value=None, prev_index=None, timeout=None): """Sets a value to a key.""" return self.adapter.set(key, value, dir=dir, ttl=ttl, refresh=refresh, prev_value=prev_value, prev_index=prev_index, timeout=timeout) def refresh(self, key, ttl, prev_value=None, prev_index=None, timeout=None): """Sets only a TTL of a key. The waiters doesn't receive notification by this operation. """ return self.adapter.set(key, ttl=ttl, refresh=True, prev_value=prev_value, prev_index=prev_index, timeout=timeout) def create(self, key, value=None, dir=False, ttl=None, timeout=None): """Creates a new key.""" return self.adapter.set(key, value, dir=dir, ttl=ttl, prev_exist=False, timeout=timeout) def append(self, key, value=None, dir=False, ttl=None, timeout=None): """Creates a new automatically increasing key in the given directory key. """ return self.adapter.append(key, value, dir=dir, ttl=ttl, timeout=timeout) def delete(self, key, dir=False, recursive=False, prev_value=None, prev_index=None, timeout=None): """Deletes a key.""" return self.adapter.delete(key, dir=dir, recursive=recursive, prev_value=prev_value, prev_index=prev_index, timeout=timeout)
sublee/etc
etc/client.py
Client.append
python
def append(self, key, value=None, dir=False, ttl=None, timeout=None): return self.adapter.append(key, value, dir=dir, ttl=ttl, timeout=timeout)
Creates a new automatically increasing key in the given directory key.
train
https://github.com/sublee/etc/blob/f2be64604da5af0d7739cfacf36f55712f0fc5cb/etc/client.py#L70-L75
null
class Client(object): def __init__(self, adapter): self.adapter = adapter @property def url(self): return self.adapter.url def clear(self): return self.adapter.clear() def __repr__(self): return gen_repr(self.__class__, u"'{0}'", self.url, short=True) def get(self, key, recursive=False, sorted=False, quorum=False, timeout=None): """Gets a value of key.""" return self.adapter.get(key, recursive=recursive, sorted=sorted, quorum=quorum, timeout=timeout) def wait(self, key, index=0, recursive=False, sorted=False, quorum=False, timeout=None): """Waits until a node changes.""" return self.adapter.get(key, recursive=recursive, sorted=sorted, quorum=quorum, wait=True, wait_index=index, timeout=timeout) def set(self, key, value=None, dir=False, ttl=None, refresh=False, prev_value=None, prev_index=None, timeout=None): """Sets a value to a key.""" return self.adapter.set(key, value, dir=dir, ttl=ttl, refresh=refresh, prev_value=prev_value, prev_index=prev_index, timeout=timeout) def refresh(self, key, ttl, prev_value=None, prev_index=None, timeout=None): """Sets only a TTL of a key. The waiters doesn't receive notification by this operation. """ return self.adapter.set(key, ttl=ttl, refresh=True, prev_value=prev_value, prev_index=prev_index, timeout=timeout) def create(self, key, value=None, dir=False, ttl=None, timeout=None): """Creates a new key.""" return self.adapter.set(key, value, dir=dir, ttl=ttl, prev_exist=False, timeout=timeout) def update(self, key, value=None, dir=False, ttl=None, refresh=False, prev_value=None, prev_index=None, timeout=None): """Updates an existing key.""" return self.adapter.set(key, value, dir=dir, ttl=ttl, refresh=refresh, prev_value=prev_value, prev_index=prev_index, prev_exist=True, timeout=timeout) def delete(self, key, dir=False, recursive=False, prev_value=None, prev_index=None, timeout=None): """Deletes a key.""" return self.adapter.delete(key, dir=dir, recursive=recursive, prev_value=prev_value, prev_index=prev_index, timeout=timeout)
sublee/etc
etc/client.py
Client.delete
python
def delete(self, key, dir=False, recursive=False, prev_value=None, prev_index=None, timeout=None): return self.adapter.delete(key, dir=dir, recursive=recursive, prev_value=prev_value, prev_index=prev_index, timeout=timeout)
Deletes a key.
train
https://github.com/sublee/etc/blob/f2be64604da5af0d7739cfacf36f55712f0fc5cb/etc/client.py#L77-L82
null
class Client(object): def __init__(self, adapter): self.adapter = adapter @property def url(self): return self.adapter.url def clear(self): return self.adapter.clear() def __repr__(self): return gen_repr(self.__class__, u"'{0}'", self.url, short=True) def get(self, key, recursive=False, sorted=False, quorum=False, timeout=None): """Gets a value of key.""" return self.adapter.get(key, recursive=recursive, sorted=sorted, quorum=quorum, timeout=timeout) def wait(self, key, index=0, recursive=False, sorted=False, quorum=False, timeout=None): """Waits until a node changes.""" return self.adapter.get(key, recursive=recursive, sorted=sorted, quorum=quorum, wait=True, wait_index=index, timeout=timeout) def set(self, key, value=None, dir=False, ttl=None, refresh=False, prev_value=None, prev_index=None, timeout=None): """Sets a value to a key.""" return self.adapter.set(key, value, dir=dir, ttl=ttl, refresh=refresh, prev_value=prev_value, prev_index=prev_index, timeout=timeout) def refresh(self, key, ttl, prev_value=None, prev_index=None, timeout=None): """Sets only a TTL of a key. The waiters doesn't receive notification by this operation. """ return self.adapter.set(key, ttl=ttl, refresh=True, prev_value=prev_value, prev_index=prev_index, timeout=timeout) def create(self, key, value=None, dir=False, ttl=None, timeout=None): """Creates a new key.""" return self.adapter.set(key, value, dir=dir, ttl=ttl, prev_exist=False, timeout=timeout) def update(self, key, value=None, dir=False, ttl=None, refresh=False, prev_value=None, prev_index=None, timeout=None): """Updates an existing key.""" return self.adapter.set(key, value, dir=dir, ttl=ttl, refresh=refresh, prev_value=prev_value, prev_index=prev_index, prev_exist=True, timeout=timeout) def append(self, key, value=None, dir=False, ttl=None, timeout=None): """Creates a new automatically increasing key in the given directory key. """ return self.adapter.append(key, value, dir=dir, ttl=ttl, timeout=timeout)
sublee/etc
etc/adapters/mock.py
split_key
python
def split_key(key): if key == KEY_SEP: return () key_chunks = tuple(key.strip(KEY_SEP).split(KEY_SEP)) if key_chunks[0].startswith(KEY_SEP): return (key_chunks[0][len(KEY_SEP):],) + key_chunks[1:] else: return key_chunks
Splits a node key.
train
https://github.com/sublee/etc/blob/f2be64604da5af0d7739cfacf36f55712f0fc5cb/etc/adapters/mock.py#L32-L40
null
# -*- coding: utf-8 -*- """ etc.mock ~~~~~~~~ """ from __future__ import absolute_import import bisect from datetime import datetime, timedelta import itertools import os import threading import six from six.moves import reduce, xrange from etc.adapter import Adapter from etc.errors import ( KeyNotFound, NodeExist, NotFile, RefreshTTLRequired, RefreshValue, TestFailed, TimedOut) from etc.results import ( ComparedThenSwapped, Created, Deleted, Directory, Got, Node, Set, Updated, Value) __all__ = ['MockAdapter'] KEY_SEP = '/' class MockNode(Node): __slots__ = Node.__slots__ + ('value', 'nodes', 'dir') def __init__(self, key, index, value=None, dir=False, ttl=None, expiration=None): self.key = key self.created_index = index self.dir = None self.set(index, value, dir, ttl, expiration) def set(self, index, value=None, dir=False, ttl=None, expiration=None): """Updates the node data.""" if bool(dir) is (value is not None): raise TypeError('Choose one of value or directory') if (ttl is not None) is (expiration is None): raise TypeError('Both of ttl and expiration required') self.value = value if self.dir != dir: self.dir = dir self.nodes = {} if dir else None self.ttl = ttl self.expiration = expiration self.modified_index = index def add_node(self, node): if not node.key.startswith(self.key): raise ValueError('Out of this key') sub_key = node.key[len(self.key):].strip(KEY_SEP) if sub_key in self.nodes: raise ValueError('Already exists') if KEY_SEP in sub_key: raise ValueError('Too deep key') self.nodes[sub_key] = node def has_node(self, sub_key): return sub_key in self.nodes def get_node(self, sub_key): return self.nodes[sub_key] def pop_node(self, sub_key): return self.nodes.pop(sub_key) def canonicalize(self, include_nodes=True, sorted=False): """Generates a canonical :class:`etc.Node` object from this mock node. """ node_class = Directory if self.dir else Value kwargs = {attr: getattr(self, attr) for attr in node_class.__slots__} if self.dir: if include_nodes: nodes = [node.canonicalize() for node in six.viewvalues(kwargs['nodes'])] if sorted: nodes.sort(key=lambda n: n.key) kwargs['nodes'] = nodes else: kwargs['nodes'] = [] return node_class(**kwargs) class MockAdapter(Adapter): def __init__(self, url): super(MockAdapter, self).__init__(url) self.index = 0 self.root = MockNode('', self.index, dir=True) self.history = {} self.indices = {} self.events = {} def clear(self): self.history.clear() self.indices.clear() self.events.clear() def next_index(self): """Gets the next etcd index.""" self.index += 1 return self.index def make_result(self, result_class, node=None, prev_node=None, remember=True, key_chunks=None, notify=True, **kwargs): """Makes an etcd result. If `remember` is ``True``, it keeps the result in the history and triggers events if waiting. `key_chunks` is the result of :func:`split_key` of the `node.key`. It is not required if `remember` is ``False``. Otherwise, it is optional but recommended to eliminate waste if the key chunks are already supplied. """ def canonicalize(node, **kwargs): return None if node is None else node.canonicalize(**kwargs) index = self.index result = result_class(canonicalize(node, **kwargs), canonicalize(prev_node, **kwargs), index) if not remember: return result self.history[index] = result_class( canonicalize(node, include_nodes=False), canonicalize(prev_node, include_nodes=False), index) key_chunks = key_chunks or split_key(node.key) asymptotic_key_chunks = (key_chunks[:x + 1] for x in xrange(len(key_chunks))) event_keys = [(False, key_chunks)] for _key_chunks in asymptotic_key_chunks: exact = _key_chunks == key_chunks self.indices.setdefault(_key_chunks, []).append((index, exact)) event_keys.append((True, _key_chunks)) if notify: for event_key in event_keys: try: event = self.events.pop(event_key) except KeyError: pass else: event.set() return result def compare(self, node, prev_value=None, prev_index=None): """Raises :exc:`TestFailed` if the node is not matched with `prev_value` or `prev_index`. """ if prev_value is not None and node.value != prev_value or \ prev_index is not None and node.index != prev_index: raise TestFailed(index=self.index) def get(self, key, recursive=False, sorted=False, quorum=False, wait=False, wait_index=None, timeout=None): key_chunks = split_key(key) if not wait: # Get immediately. try: node = reduce(MockNode.get_node, key_chunks, self.root) except KeyError: raise KeyNotFound(index=self.index) return self.make_result(Got, node, remember=False, sorted=sorted) # Wait... if wait_index is not None: indices = self.indices.get(key_chunks, ()) x = bisect.bisect_left(indices, (wait_index, False)) for index, exact in indices[x:]: if recursive or exact: # Matched past result found. return self.history[index] # Register an event and wait... event_key = (recursive, key_chunks) event = self.events.setdefault(event_key, threading.Event()) if not event.wait(timeout): raise TimedOut index, __ = self.indices[key_chunks][-1] return self.history[index] def set(self, key, value=None, dir=False, ttl=None, refresh=False, prev_value=None, prev_index=None, prev_exist=None, timeout=None): if refresh: prev_exist = True if value is not None: raise RefreshValue(index=self.index) elif ttl is None: raise RefreshTTLRequired(index=self.index) expiration = ttl and (datetime.utcnow() + timedelta(ttl)) key_chunks = split_key(key) index = self.next_index() should_test = prev_value is not None or prev_index is not None parent_node = reduce(MockNode.get_node, key_chunks[:-1], self.root) try: node = parent_node.get_node(key_chunks[-1]) except KeyError: if prev_exist or should_test: raise KeyNotFound(index=self.index) node = MockNode(key, index, value, dir, ttl, expiration) parent_node.add_node(node) else: if prev_exist is not None and not prev_exist: raise NodeExist(index=self.index) if refresh: if node.dir: raise NotFile(index=self.index) value = node.value self.compare(node, prev_value, prev_index) node.set(index, value, dir, ttl, expiration) if refresh: result_class = ComparedThenSwapped if should_test else Set notify = False else: result_class = Updated if prev_exist or should_test else Set notify = True return self.make_result(result_class, node, key_chunks=key_chunks, notify=notify) def append(self, key, value=None, dir=False, ttl=None, timeout=None): expiration = ttl and (datetime.utcnow() + timedelta(ttl)) key_chunks = split_key(key) parent_node = reduce(MockNode.get_node, key_chunks, self.root) for x in itertools.count(len(parent_node.nodes)): item_key = '%020d' % x if not parent_node.has_node(item_key): break key = os.path.join(key, item_key) index = self.next_index() node = MockNode(key, index, value, dir, ttl, expiration) parent_node.add_node(node) return self.make_result(Created, node, key_chunks=key_chunks) def delete(self, key, dir=False, recursive=False, prev_value=None, prev_index=None, timeout=None): key_chunks = split_key(key) parent_node = reduce(MockNode.get_node, key_chunks[:-1], self.root) try: node = parent_node.get_node(key_chunks[-1]) except KeyError: raise KeyNotFound(index=self.index) self.compare(node, prev_value, prev_index) parent_node.pop_node(key_chunks[-1]) return self.make_result(Deleted, prev_node=node, key_chunks=key_chunks)
sublee/etc
etc/adapters/mock.py
MockNode.set
python
def set(self, index, value=None, dir=False, ttl=None, expiration=None): if bool(dir) is (value is not None): raise TypeError('Choose one of value or directory') if (ttl is not None) is (expiration is None): raise TypeError('Both of ttl and expiration required') self.value = value if self.dir != dir: self.dir = dir self.nodes = {} if dir else None self.ttl = ttl self.expiration = expiration self.modified_index = index
Updates the node data.
train
https://github.com/sublee/etc/blob/f2be64604da5af0d7739cfacf36f55712f0fc5cb/etc/adapters/mock.py#L54-L66
null
class MockNode(Node): __slots__ = Node.__slots__ + ('value', 'nodes', 'dir') def __init__(self, key, index, value=None, dir=False, ttl=None, expiration=None): self.key = key self.created_index = index self.dir = None self.set(index, value, dir, ttl, expiration) def add_node(self, node): if not node.key.startswith(self.key): raise ValueError('Out of this key') sub_key = node.key[len(self.key):].strip(KEY_SEP) if sub_key in self.nodes: raise ValueError('Already exists') if KEY_SEP in sub_key: raise ValueError('Too deep key') self.nodes[sub_key] = node def has_node(self, sub_key): return sub_key in self.nodes def get_node(self, sub_key): return self.nodes[sub_key] def pop_node(self, sub_key): return self.nodes.pop(sub_key) def canonicalize(self, include_nodes=True, sorted=False): """Generates a canonical :class:`etc.Node` object from this mock node. """ node_class = Directory if self.dir else Value kwargs = {attr: getattr(self, attr) for attr in node_class.__slots__} if self.dir: if include_nodes: nodes = [node.canonicalize() for node in six.viewvalues(kwargs['nodes'])] if sorted: nodes.sort(key=lambda n: n.key) kwargs['nodes'] = nodes else: kwargs['nodes'] = [] return node_class(**kwargs)
sublee/etc
etc/adapters/mock.py
MockNode.canonicalize
python
def canonicalize(self, include_nodes=True, sorted=False): node_class = Directory if self.dir else Value kwargs = {attr: getattr(self, attr) for attr in node_class.__slots__} if self.dir: if include_nodes: nodes = [node.canonicalize() for node in six.viewvalues(kwargs['nodes'])] if sorted: nodes.sort(key=lambda n: n.key) kwargs['nodes'] = nodes else: kwargs['nodes'] = [] return node_class(**kwargs)
Generates a canonical :class:`etc.Node` object from this mock node.
train
https://github.com/sublee/etc/blob/f2be64604da5af0d7739cfacf36f55712f0fc5cb/etc/adapters/mock.py#L87-L101
null
class MockNode(Node): __slots__ = Node.__slots__ + ('value', 'nodes', 'dir') def __init__(self, key, index, value=None, dir=False, ttl=None, expiration=None): self.key = key self.created_index = index self.dir = None self.set(index, value, dir, ttl, expiration) def set(self, index, value=None, dir=False, ttl=None, expiration=None): """Updates the node data.""" if bool(dir) is (value is not None): raise TypeError('Choose one of value or directory') if (ttl is not None) is (expiration is None): raise TypeError('Both of ttl and expiration required') self.value = value if self.dir != dir: self.dir = dir self.nodes = {} if dir else None self.ttl = ttl self.expiration = expiration self.modified_index = index def add_node(self, node): if not node.key.startswith(self.key): raise ValueError('Out of this key') sub_key = node.key[len(self.key):].strip(KEY_SEP) if sub_key in self.nodes: raise ValueError('Already exists') if KEY_SEP in sub_key: raise ValueError('Too deep key') self.nodes[sub_key] = node def has_node(self, sub_key): return sub_key in self.nodes def get_node(self, sub_key): return self.nodes[sub_key] def pop_node(self, sub_key): return self.nodes.pop(sub_key)
sublee/etc
etc/adapters/mock.py
MockAdapter.make_result
python
def make_result(self, result_class, node=None, prev_node=None, remember=True, key_chunks=None, notify=True, **kwargs): def canonicalize(node, **kwargs): return None if node is None else node.canonicalize(**kwargs) index = self.index result = result_class(canonicalize(node, **kwargs), canonicalize(prev_node, **kwargs), index) if not remember: return result self.history[index] = result_class( canonicalize(node, include_nodes=False), canonicalize(prev_node, include_nodes=False), index) key_chunks = key_chunks or split_key(node.key) asymptotic_key_chunks = (key_chunks[:x + 1] for x in xrange(len(key_chunks))) event_keys = [(False, key_chunks)] for _key_chunks in asymptotic_key_chunks: exact = _key_chunks == key_chunks self.indices.setdefault(_key_chunks, []).append((index, exact)) event_keys.append((True, _key_chunks)) if notify: for event_key in event_keys: try: event = self.events.pop(event_key) except KeyError: pass else: event.set() return result
Makes an etcd result. If `remember` is ``True``, it keeps the result in the history and triggers events if waiting. `key_chunks` is the result of :func:`split_key` of the `node.key`. It is not required if `remember` is ``False``. Otherwise, it is optional but recommended to eliminate waste if the key chunks are already supplied.
train
https://github.com/sublee/etc/blob/f2be64604da5af0d7739cfacf36f55712f0fc5cb/etc/adapters/mock.py#L124-L161
[ "def split_key(key):\n \"\"\"Splits a node key.\"\"\"\n if key == KEY_SEP:\n return ()\n key_chunks = tuple(key.strip(KEY_SEP).split(KEY_SEP))\n if key_chunks[0].startswith(KEY_SEP):\n return (key_chunks[0][len(KEY_SEP):],) + key_chunks[1:]\n else:\n return key_chunks\n", "def ...
class MockAdapter(Adapter): def __init__(self, url): super(MockAdapter, self).__init__(url) self.index = 0 self.root = MockNode('', self.index, dir=True) self.history = {} self.indices = {} self.events = {} def clear(self): self.history.clear() self.indices.clear() self.events.clear() def next_index(self): """Gets the next etcd index.""" self.index += 1 return self.index def compare(self, node, prev_value=None, prev_index=None): """Raises :exc:`TestFailed` if the node is not matched with `prev_value` or `prev_index`. """ if prev_value is not None and node.value != prev_value or \ prev_index is not None and node.index != prev_index: raise TestFailed(index=self.index) def get(self, key, recursive=False, sorted=False, quorum=False, wait=False, wait_index=None, timeout=None): key_chunks = split_key(key) if not wait: # Get immediately. try: node = reduce(MockNode.get_node, key_chunks, self.root) except KeyError: raise KeyNotFound(index=self.index) return self.make_result(Got, node, remember=False, sorted=sorted) # Wait... if wait_index is not None: indices = self.indices.get(key_chunks, ()) x = bisect.bisect_left(indices, (wait_index, False)) for index, exact in indices[x:]: if recursive or exact: # Matched past result found. return self.history[index] # Register an event and wait... event_key = (recursive, key_chunks) event = self.events.setdefault(event_key, threading.Event()) if not event.wait(timeout): raise TimedOut index, __ = self.indices[key_chunks][-1] return self.history[index] def set(self, key, value=None, dir=False, ttl=None, refresh=False, prev_value=None, prev_index=None, prev_exist=None, timeout=None): if refresh: prev_exist = True if value is not None: raise RefreshValue(index=self.index) elif ttl is None: raise RefreshTTLRequired(index=self.index) expiration = ttl and (datetime.utcnow() + timedelta(ttl)) key_chunks = split_key(key) index = self.next_index() should_test = prev_value is not None or prev_index is not None parent_node = reduce(MockNode.get_node, key_chunks[:-1], self.root) try: node = parent_node.get_node(key_chunks[-1]) except KeyError: if prev_exist or should_test: raise KeyNotFound(index=self.index) node = MockNode(key, index, value, dir, ttl, expiration) parent_node.add_node(node) else: if prev_exist is not None and not prev_exist: raise NodeExist(index=self.index) if refresh: if node.dir: raise NotFile(index=self.index) value = node.value self.compare(node, prev_value, prev_index) node.set(index, value, dir, ttl, expiration) if refresh: result_class = ComparedThenSwapped if should_test else Set notify = False else: result_class = Updated if prev_exist or should_test else Set notify = True return self.make_result(result_class, node, key_chunks=key_chunks, notify=notify) def append(self, key, value=None, dir=False, ttl=None, timeout=None): expiration = ttl and (datetime.utcnow() + timedelta(ttl)) key_chunks = split_key(key) parent_node = reduce(MockNode.get_node, key_chunks, self.root) for x in itertools.count(len(parent_node.nodes)): item_key = '%020d' % x if not parent_node.has_node(item_key): break key = os.path.join(key, item_key) index = self.next_index() node = MockNode(key, index, value, dir, ttl, expiration) parent_node.add_node(node) return self.make_result(Created, node, key_chunks=key_chunks) def delete(self, key, dir=False, recursive=False, prev_value=None, prev_index=None, timeout=None): key_chunks = split_key(key) parent_node = reduce(MockNode.get_node, key_chunks[:-1], self.root) try: node = parent_node.get_node(key_chunks[-1]) except KeyError: raise KeyNotFound(index=self.index) self.compare(node, prev_value, prev_index) parent_node.pop_node(key_chunks[-1]) return self.make_result(Deleted, prev_node=node, key_chunks=key_chunks)
sublee/etc
etc/adapters/mock.py
MockAdapter.compare
python
def compare(self, node, prev_value=None, prev_index=None): if prev_value is not None and node.value != prev_value or \ prev_index is not None and node.index != prev_index: raise TestFailed(index=self.index)
Raises :exc:`TestFailed` if the node is not matched with `prev_value` or `prev_index`.
train
https://github.com/sublee/etc/blob/f2be64604da5af0d7739cfacf36f55712f0fc5cb/etc/adapters/mock.py#L163-L169
null
class MockAdapter(Adapter): def __init__(self, url): super(MockAdapter, self).__init__(url) self.index = 0 self.root = MockNode('', self.index, dir=True) self.history = {} self.indices = {} self.events = {} def clear(self): self.history.clear() self.indices.clear() self.events.clear() def next_index(self): """Gets the next etcd index.""" self.index += 1 return self.index def make_result(self, result_class, node=None, prev_node=None, remember=True, key_chunks=None, notify=True, **kwargs): """Makes an etcd result. If `remember` is ``True``, it keeps the result in the history and triggers events if waiting. `key_chunks` is the result of :func:`split_key` of the `node.key`. It is not required if `remember` is ``False``. Otherwise, it is optional but recommended to eliminate waste if the key chunks are already supplied. """ def canonicalize(node, **kwargs): return None if node is None else node.canonicalize(**kwargs) index = self.index result = result_class(canonicalize(node, **kwargs), canonicalize(prev_node, **kwargs), index) if not remember: return result self.history[index] = result_class( canonicalize(node, include_nodes=False), canonicalize(prev_node, include_nodes=False), index) key_chunks = key_chunks or split_key(node.key) asymptotic_key_chunks = (key_chunks[:x + 1] for x in xrange(len(key_chunks))) event_keys = [(False, key_chunks)] for _key_chunks in asymptotic_key_chunks: exact = _key_chunks == key_chunks self.indices.setdefault(_key_chunks, []).append((index, exact)) event_keys.append((True, _key_chunks)) if notify: for event_key in event_keys: try: event = self.events.pop(event_key) except KeyError: pass else: event.set() return result def get(self, key, recursive=False, sorted=False, quorum=False, wait=False, wait_index=None, timeout=None): key_chunks = split_key(key) if not wait: # Get immediately. try: node = reduce(MockNode.get_node, key_chunks, self.root) except KeyError: raise KeyNotFound(index=self.index) return self.make_result(Got, node, remember=False, sorted=sorted) # Wait... if wait_index is not None: indices = self.indices.get(key_chunks, ()) x = bisect.bisect_left(indices, (wait_index, False)) for index, exact in indices[x:]: if recursive or exact: # Matched past result found. return self.history[index] # Register an event and wait... event_key = (recursive, key_chunks) event = self.events.setdefault(event_key, threading.Event()) if not event.wait(timeout): raise TimedOut index, __ = self.indices[key_chunks][-1] return self.history[index] def set(self, key, value=None, dir=False, ttl=None, refresh=False, prev_value=None, prev_index=None, prev_exist=None, timeout=None): if refresh: prev_exist = True if value is not None: raise RefreshValue(index=self.index) elif ttl is None: raise RefreshTTLRequired(index=self.index) expiration = ttl and (datetime.utcnow() + timedelta(ttl)) key_chunks = split_key(key) index = self.next_index() should_test = prev_value is not None or prev_index is not None parent_node = reduce(MockNode.get_node, key_chunks[:-1], self.root) try: node = parent_node.get_node(key_chunks[-1]) except KeyError: if prev_exist or should_test: raise KeyNotFound(index=self.index) node = MockNode(key, index, value, dir, ttl, expiration) parent_node.add_node(node) else: if prev_exist is not None and not prev_exist: raise NodeExist(index=self.index) if refresh: if node.dir: raise NotFile(index=self.index) value = node.value self.compare(node, prev_value, prev_index) node.set(index, value, dir, ttl, expiration) if refresh: result_class = ComparedThenSwapped if should_test else Set notify = False else: result_class = Updated if prev_exist or should_test else Set notify = True return self.make_result(result_class, node, key_chunks=key_chunks, notify=notify) def append(self, key, value=None, dir=False, ttl=None, timeout=None): expiration = ttl and (datetime.utcnow() + timedelta(ttl)) key_chunks = split_key(key) parent_node = reduce(MockNode.get_node, key_chunks, self.root) for x in itertools.count(len(parent_node.nodes)): item_key = '%020d' % x if not parent_node.has_node(item_key): break key = os.path.join(key, item_key) index = self.next_index() node = MockNode(key, index, value, dir, ttl, expiration) parent_node.add_node(node) return self.make_result(Created, node, key_chunks=key_chunks) def delete(self, key, dir=False, recursive=False, prev_value=None, prev_index=None, timeout=None): key_chunks = split_key(key) parent_node = reduce(MockNode.get_node, key_chunks[:-1], self.root) try: node = parent_node.get_node(key_chunks[-1]) except KeyError: raise KeyNotFound(index=self.index) self.compare(node, prev_value, prev_index) parent_node.pop_node(key_chunks[-1]) return self.make_result(Deleted, prev_node=node, key_chunks=key_chunks)
sublee/etc
etc/adapters/etcd.py
EtcdAdapter.make_url
python
def make_url(self, path, api_root=u'/v2/'): return urljoin(urljoin(self.url, api_root), path)
Gets a full URL from just path.
train
https://github.com/sublee/etc/blob/f2be64604da5af0d7739cfacf36f55712f0fc5cb/etc/adapters/etcd.py#L40-L42
null
class EtcdAdapter(Adapter): """An adapter which communicates with an etcd v2 server.""" def __init__(self, url, default_timeout=60): super(EtcdAdapter, self).__init__(url) self.default_timeout = default_timeout self.session = requests.Session() def clear(self): self.session.close() def make_key_url(self, key): """Gets a URL for a key.""" if type(key) is bytes: key = key.decode('utf-8') buf = io.StringIO() buf.write(u'keys') if not key.startswith(u'/'): buf.write(u'/') buf.write(key) return self.make_url(buf.getvalue()) @classmethod def make_node(cls, data): try: key = data['key'] except KeyError: key, kwargs = u'/', {} else: kwargs = {'modified_index': int(data['modifiedIndex']), 'created_index': int(data['createdIndex'])} ttl = data.get('ttl') if ttl is not None: expiration = iso8601.parse_date(data['expiration']) kwargs.update(ttl=ttl, expiration=expiration) if 'value' in data: node_cls = Value args = (data['value'],) elif data.get('dir', False): node_cls = Directory args = ([cls.make_node(n) for n in data.get('nodes', ())],) else: node_cls, args = Node, () return node_cls(key, *args, **kwargs) @classmethod def make_result(cls, data, headers=None): action = data['action'] node = cls.make_node(data['node']) kwargs = {} try: prev_node_data = data['prevNode'] except KeyError: pass else: kwargs['prev_node'] = cls.make_node(prev_node_data) if headers: kwargs.update(etcd_index=int(headers['X-Etcd-Index']), raft_index=int(headers['X-Raft-Index']), raft_term=int(headers['X-Raft-Term'])) return EtcdResult.__dispatch__(action)(node, **kwargs) @classmethod def make_error(cls, data, headers=None): errno = data['errorCode'] message = data['message'] cause = data['cause'] index = data['index'] kwargs = {} if headers: kwargs.update(etcd_index=int(headers['X-Etcd-Index']), raft_index=int(headers['X-Raft-Index']), raft_term=int(headers['X-Raft-Term'])) return EtcdError.__dispatch__(errno)(message, cause, index, **kwargs) @classmethod def wrap_response(cls, res): if res.ok: return cls.make_result(res.json(), res.headers) try: json = res.json() except ValueError: raise HTTPError(res.status_code) else: raise cls.make_error(json, res.headers) @staticmethod def build_args(typed_args): args = {} for key, (type_, value) in typed_args.items(): if value is None: continue if type_ is bool: args[key] = u'true' if value else u'false' else: args[key] = value return args @staticmethod def erred(): """Wraps errors. Call it in `except` clause:: try: do_something() except: self.erred() """ exc_type, exc, tb = sys.exc_info() if issubclass(exc_type, socket.timeout): raise TimedOut elif issubclass(exc_type, requests.ConnectionError): internal_exc = exc.args[0] if isinstance(internal_exc, ReadTimeoutError): raise TimedOut else: raise ConnectionError(exc) elif issubclass(exc_type, requests.RequestException): raise EtcException(exc) reraise(exc_type, exc, tb) def get(self, key, recursive=False, sorted=False, quorum=False, wait=False, wait_index=None, timeout=None): """Requests to get a node by the given key.""" url = self.make_key_url(key) params = self.build_args({ 'recursive': (bool, recursive or None), 'sorted': (bool, sorted or None), 'quorum': (bool, quorum or None), 'wait': (bool, wait or None), 'waitIndex': (int, wait_index), }) if timeout is None: # Try again when :exc:`TimedOut` thrown. while True: try: try: res = self.session.get(url, params=params) except: self.erred() except (TimedOut, ChunkedEncodingError): continue else: break else: try: res = self.session.get(url, params=params, timeout=timeout) except ChunkedEncodingError: raise TimedOut except: self.erred() return self.wrap_response(res) def set(self, key, value=None, dir=False, refresh=False, ttl=None, prev_value=None, prev_index=None, prev_exist=None, timeout=None): """Requests to create an ordered node into a node by the given key.""" url = self.make_key_url(key) data = self.build_args({ 'value': (six.text_type, value), 'dir': (bool, dir or None), 'refresh': (bool, refresh or None), 'ttl': (int, ttl), 'prevValue': (six.text_type, prev_value), 'prevIndex': (int, prev_index), 'prevExist': (bool, prev_exist), }) try: res = self.session.put(url, data=data, timeout=timeout) except: self.erred() return self.wrap_response(res) def append(self, key, value=None, dir=False, ttl=None, timeout=None): """Requests to create an ordered node into a node by the given key.""" url = self.make_key_url(key) data = self.build_args({ 'value': (six.text_type, value), 'dir': (bool, dir or None), 'ttl': (int, ttl), }) try: res = self.session.post(url, data=data, timeout=timeout) except: self.erred() return self.wrap_response(res) def delete(self, key, dir=False, recursive=False, prev_value=None, prev_index=None, timeout=None): """Requests to delete a node by the given key.""" url = self.make_key_url(key) params = self.build_args({ 'dir': (bool, dir or None), 'recursive': (bool, recursive or None), 'prevValue': (six.text_type, prev_value), 'prevIndex': (int, prev_index), }) try: res = self.session.delete(url, params=params, timeout=timeout) except: self.erred() return self.wrap_response(res)
sublee/etc
etc/adapters/etcd.py
EtcdAdapter.make_key_url
python
def make_key_url(self, key): if type(key) is bytes: key = key.decode('utf-8') buf = io.StringIO() buf.write(u'keys') if not key.startswith(u'/'): buf.write(u'/') buf.write(key) return self.make_url(buf.getvalue())
Gets a URL for a key.
train
https://github.com/sublee/etc/blob/f2be64604da5af0d7739cfacf36f55712f0fc5cb/etc/adapters/etcd.py#L44-L53
null
class EtcdAdapter(Adapter): """An adapter which communicates with an etcd v2 server.""" def __init__(self, url, default_timeout=60): super(EtcdAdapter, self).__init__(url) self.default_timeout = default_timeout self.session = requests.Session() def clear(self): self.session.close() def make_url(self, path, api_root=u'/v2/'): """Gets a full URL from just path.""" return urljoin(urljoin(self.url, api_root), path) @classmethod def make_node(cls, data): try: key = data['key'] except KeyError: key, kwargs = u'/', {} else: kwargs = {'modified_index': int(data['modifiedIndex']), 'created_index': int(data['createdIndex'])} ttl = data.get('ttl') if ttl is not None: expiration = iso8601.parse_date(data['expiration']) kwargs.update(ttl=ttl, expiration=expiration) if 'value' in data: node_cls = Value args = (data['value'],) elif data.get('dir', False): node_cls = Directory args = ([cls.make_node(n) for n in data.get('nodes', ())],) else: node_cls, args = Node, () return node_cls(key, *args, **kwargs) @classmethod def make_result(cls, data, headers=None): action = data['action'] node = cls.make_node(data['node']) kwargs = {} try: prev_node_data = data['prevNode'] except KeyError: pass else: kwargs['prev_node'] = cls.make_node(prev_node_data) if headers: kwargs.update(etcd_index=int(headers['X-Etcd-Index']), raft_index=int(headers['X-Raft-Index']), raft_term=int(headers['X-Raft-Term'])) return EtcdResult.__dispatch__(action)(node, **kwargs) @classmethod def make_error(cls, data, headers=None): errno = data['errorCode'] message = data['message'] cause = data['cause'] index = data['index'] kwargs = {} if headers: kwargs.update(etcd_index=int(headers['X-Etcd-Index']), raft_index=int(headers['X-Raft-Index']), raft_term=int(headers['X-Raft-Term'])) return EtcdError.__dispatch__(errno)(message, cause, index, **kwargs) @classmethod def wrap_response(cls, res): if res.ok: return cls.make_result(res.json(), res.headers) try: json = res.json() except ValueError: raise HTTPError(res.status_code) else: raise cls.make_error(json, res.headers) @staticmethod def build_args(typed_args): args = {} for key, (type_, value) in typed_args.items(): if value is None: continue if type_ is bool: args[key] = u'true' if value else u'false' else: args[key] = value return args @staticmethod def erred(): """Wraps errors. Call it in `except` clause:: try: do_something() except: self.erred() """ exc_type, exc, tb = sys.exc_info() if issubclass(exc_type, socket.timeout): raise TimedOut elif issubclass(exc_type, requests.ConnectionError): internal_exc = exc.args[0] if isinstance(internal_exc, ReadTimeoutError): raise TimedOut else: raise ConnectionError(exc) elif issubclass(exc_type, requests.RequestException): raise EtcException(exc) reraise(exc_type, exc, tb) def get(self, key, recursive=False, sorted=False, quorum=False, wait=False, wait_index=None, timeout=None): """Requests to get a node by the given key.""" url = self.make_key_url(key) params = self.build_args({ 'recursive': (bool, recursive or None), 'sorted': (bool, sorted or None), 'quorum': (bool, quorum or None), 'wait': (bool, wait or None), 'waitIndex': (int, wait_index), }) if timeout is None: # Try again when :exc:`TimedOut` thrown. while True: try: try: res = self.session.get(url, params=params) except: self.erred() except (TimedOut, ChunkedEncodingError): continue else: break else: try: res = self.session.get(url, params=params, timeout=timeout) except ChunkedEncodingError: raise TimedOut except: self.erred() return self.wrap_response(res) def set(self, key, value=None, dir=False, refresh=False, ttl=None, prev_value=None, prev_index=None, prev_exist=None, timeout=None): """Requests to create an ordered node into a node by the given key.""" url = self.make_key_url(key) data = self.build_args({ 'value': (six.text_type, value), 'dir': (bool, dir or None), 'refresh': (bool, refresh or None), 'ttl': (int, ttl), 'prevValue': (six.text_type, prev_value), 'prevIndex': (int, prev_index), 'prevExist': (bool, prev_exist), }) try: res = self.session.put(url, data=data, timeout=timeout) except: self.erred() return self.wrap_response(res) def append(self, key, value=None, dir=False, ttl=None, timeout=None): """Requests to create an ordered node into a node by the given key.""" url = self.make_key_url(key) data = self.build_args({ 'value': (six.text_type, value), 'dir': (bool, dir or None), 'ttl': (int, ttl), }) try: res = self.session.post(url, data=data, timeout=timeout) except: self.erred() return self.wrap_response(res) def delete(self, key, dir=False, recursive=False, prev_value=None, prev_index=None, timeout=None): """Requests to delete a node by the given key.""" url = self.make_key_url(key) params = self.build_args({ 'dir': (bool, dir or None), 'recursive': (bool, recursive or None), 'prevValue': (six.text_type, prev_value), 'prevIndex': (int, prev_index), }) try: res = self.session.delete(url, params=params, timeout=timeout) except: self.erred() return self.wrap_response(res)
sublee/etc
etc/adapters/etcd.py
EtcdAdapter.erred
python
def erred(): exc_type, exc, tb = sys.exc_info() if issubclass(exc_type, socket.timeout): raise TimedOut elif issubclass(exc_type, requests.ConnectionError): internal_exc = exc.args[0] if isinstance(internal_exc, ReadTimeoutError): raise TimedOut else: raise ConnectionError(exc) elif issubclass(exc_type, requests.RequestException): raise EtcException(exc) reraise(exc_type, exc, tb)
Wraps errors. Call it in `except` clause:: try: do_something() except: self.erred()
train
https://github.com/sublee/etc/blob/f2be64604da5af0d7739cfacf36f55712f0fc5cb/etc/adapters/etcd.py#L133-L153
null
class EtcdAdapter(Adapter): """An adapter which communicates with an etcd v2 server.""" def __init__(self, url, default_timeout=60): super(EtcdAdapter, self).__init__(url) self.default_timeout = default_timeout self.session = requests.Session() def clear(self): self.session.close() def make_url(self, path, api_root=u'/v2/'): """Gets a full URL from just path.""" return urljoin(urljoin(self.url, api_root), path) def make_key_url(self, key): """Gets a URL for a key.""" if type(key) is bytes: key = key.decode('utf-8') buf = io.StringIO() buf.write(u'keys') if not key.startswith(u'/'): buf.write(u'/') buf.write(key) return self.make_url(buf.getvalue()) @classmethod def make_node(cls, data): try: key = data['key'] except KeyError: key, kwargs = u'/', {} else: kwargs = {'modified_index': int(data['modifiedIndex']), 'created_index': int(data['createdIndex'])} ttl = data.get('ttl') if ttl is not None: expiration = iso8601.parse_date(data['expiration']) kwargs.update(ttl=ttl, expiration=expiration) if 'value' in data: node_cls = Value args = (data['value'],) elif data.get('dir', False): node_cls = Directory args = ([cls.make_node(n) for n in data.get('nodes', ())],) else: node_cls, args = Node, () return node_cls(key, *args, **kwargs) @classmethod def make_result(cls, data, headers=None): action = data['action'] node = cls.make_node(data['node']) kwargs = {} try: prev_node_data = data['prevNode'] except KeyError: pass else: kwargs['prev_node'] = cls.make_node(prev_node_data) if headers: kwargs.update(etcd_index=int(headers['X-Etcd-Index']), raft_index=int(headers['X-Raft-Index']), raft_term=int(headers['X-Raft-Term'])) return EtcdResult.__dispatch__(action)(node, **kwargs) @classmethod def make_error(cls, data, headers=None): errno = data['errorCode'] message = data['message'] cause = data['cause'] index = data['index'] kwargs = {} if headers: kwargs.update(etcd_index=int(headers['X-Etcd-Index']), raft_index=int(headers['X-Raft-Index']), raft_term=int(headers['X-Raft-Term'])) return EtcdError.__dispatch__(errno)(message, cause, index, **kwargs) @classmethod def wrap_response(cls, res): if res.ok: return cls.make_result(res.json(), res.headers) try: json = res.json() except ValueError: raise HTTPError(res.status_code) else: raise cls.make_error(json, res.headers) @staticmethod def build_args(typed_args): args = {} for key, (type_, value) in typed_args.items(): if value is None: continue if type_ is bool: args[key] = u'true' if value else u'false' else: args[key] = value return args @staticmethod def get(self, key, recursive=False, sorted=False, quorum=False, wait=False, wait_index=None, timeout=None): """Requests to get a node by the given key.""" url = self.make_key_url(key) params = self.build_args({ 'recursive': (bool, recursive or None), 'sorted': (bool, sorted or None), 'quorum': (bool, quorum or None), 'wait': (bool, wait or None), 'waitIndex': (int, wait_index), }) if timeout is None: # Try again when :exc:`TimedOut` thrown. while True: try: try: res = self.session.get(url, params=params) except: self.erred() except (TimedOut, ChunkedEncodingError): continue else: break else: try: res = self.session.get(url, params=params, timeout=timeout) except ChunkedEncodingError: raise TimedOut except: self.erred() return self.wrap_response(res) def set(self, key, value=None, dir=False, refresh=False, ttl=None, prev_value=None, prev_index=None, prev_exist=None, timeout=None): """Requests to create an ordered node into a node by the given key.""" url = self.make_key_url(key) data = self.build_args({ 'value': (six.text_type, value), 'dir': (bool, dir or None), 'refresh': (bool, refresh or None), 'ttl': (int, ttl), 'prevValue': (six.text_type, prev_value), 'prevIndex': (int, prev_index), 'prevExist': (bool, prev_exist), }) try: res = self.session.put(url, data=data, timeout=timeout) except: self.erred() return self.wrap_response(res) def append(self, key, value=None, dir=False, ttl=None, timeout=None): """Requests to create an ordered node into a node by the given key.""" url = self.make_key_url(key) data = self.build_args({ 'value': (six.text_type, value), 'dir': (bool, dir or None), 'ttl': (int, ttl), }) try: res = self.session.post(url, data=data, timeout=timeout) except: self.erred() return self.wrap_response(res) def delete(self, key, dir=False, recursive=False, prev_value=None, prev_index=None, timeout=None): """Requests to delete a node by the given key.""" url = self.make_key_url(key) params = self.build_args({ 'dir': (bool, dir or None), 'recursive': (bool, recursive or None), 'prevValue': (six.text_type, prev_value), 'prevIndex': (int, prev_index), }) try: res = self.session.delete(url, params=params, timeout=timeout) except: self.erred() return self.wrap_response(res)
sublee/etc
etc/adapters/etcd.py
EtcdAdapter.get
python
def get(self, key, recursive=False, sorted=False, quorum=False, wait=False, wait_index=None, timeout=None): url = self.make_key_url(key) params = self.build_args({ 'recursive': (bool, recursive or None), 'sorted': (bool, sorted or None), 'quorum': (bool, quorum or None), 'wait': (bool, wait or None), 'waitIndex': (int, wait_index), }) if timeout is None: # Try again when :exc:`TimedOut` thrown. while True: try: try: res = self.session.get(url, params=params) except: self.erred() except (TimedOut, ChunkedEncodingError): continue else: break else: try: res = self.session.get(url, params=params, timeout=timeout) except ChunkedEncodingError: raise TimedOut except: self.erred() return self.wrap_response(res)
Requests to get a node by the given key.
train
https://github.com/sublee/etc/blob/f2be64604da5af0d7739cfacf36f55712f0fc5cb/etc/adapters/etcd.py#L155-L185
null
class EtcdAdapter(Adapter): """An adapter which communicates with an etcd v2 server.""" def __init__(self, url, default_timeout=60): super(EtcdAdapter, self).__init__(url) self.default_timeout = default_timeout self.session = requests.Session() def clear(self): self.session.close() def make_url(self, path, api_root=u'/v2/'): """Gets a full URL from just path.""" return urljoin(urljoin(self.url, api_root), path) def make_key_url(self, key): """Gets a URL for a key.""" if type(key) is bytes: key = key.decode('utf-8') buf = io.StringIO() buf.write(u'keys') if not key.startswith(u'/'): buf.write(u'/') buf.write(key) return self.make_url(buf.getvalue()) @classmethod def make_node(cls, data): try: key = data['key'] except KeyError: key, kwargs = u'/', {} else: kwargs = {'modified_index': int(data['modifiedIndex']), 'created_index': int(data['createdIndex'])} ttl = data.get('ttl') if ttl is not None: expiration = iso8601.parse_date(data['expiration']) kwargs.update(ttl=ttl, expiration=expiration) if 'value' in data: node_cls = Value args = (data['value'],) elif data.get('dir', False): node_cls = Directory args = ([cls.make_node(n) for n in data.get('nodes', ())],) else: node_cls, args = Node, () return node_cls(key, *args, **kwargs) @classmethod def make_result(cls, data, headers=None): action = data['action'] node = cls.make_node(data['node']) kwargs = {} try: prev_node_data = data['prevNode'] except KeyError: pass else: kwargs['prev_node'] = cls.make_node(prev_node_data) if headers: kwargs.update(etcd_index=int(headers['X-Etcd-Index']), raft_index=int(headers['X-Raft-Index']), raft_term=int(headers['X-Raft-Term'])) return EtcdResult.__dispatch__(action)(node, **kwargs) @classmethod def make_error(cls, data, headers=None): errno = data['errorCode'] message = data['message'] cause = data['cause'] index = data['index'] kwargs = {} if headers: kwargs.update(etcd_index=int(headers['X-Etcd-Index']), raft_index=int(headers['X-Raft-Index']), raft_term=int(headers['X-Raft-Term'])) return EtcdError.__dispatch__(errno)(message, cause, index, **kwargs) @classmethod def wrap_response(cls, res): if res.ok: return cls.make_result(res.json(), res.headers) try: json = res.json() except ValueError: raise HTTPError(res.status_code) else: raise cls.make_error(json, res.headers) @staticmethod def build_args(typed_args): args = {} for key, (type_, value) in typed_args.items(): if value is None: continue if type_ is bool: args[key] = u'true' if value else u'false' else: args[key] = value return args @staticmethod def erred(): """Wraps errors. Call it in `except` clause:: try: do_something() except: self.erred() """ exc_type, exc, tb = sys.exc_info() if issubclass(exc_type, socket.timeout): raise TimedOut elif issubclass(exc_type, requests.ConnectionError): internal_exc = exc.args[0] if isinstance(internal_exc, ReadTimeoutError): raise TimedOut else: raise ConnectionError(exc) elif issubclass(exc_type, requests.RequestException): raise EtcException(exc) reraise(exc_type, exc, tb) def set(self, key, value=None, dir=False, refresh=False, ttl=None, prev_value=None, prev_index=None, prev_exist=None, timeout=None): """Requests to create an ordered node into a node by the given key.""" url = self.make_key_url(key) data = self.build_args({ 'value': (six.text_type, value), 'dir': (bool, dir or None), 'refresh': (bool, refresh or None), 'ttl': (int, ttl), 'prevValue': (six.text_type, prev_value), 'prevIndex': (int, prev_index), 'prevExist': (bool, prev_exist), }) try: res = self.session.put(url, data=data, timeout=timeout) except: self.erred() return self.wrap_response(res) def append(self, key, value=None, dir=False, ttl=None, timeout=None): """Requests to create an ordered node into a node by the given key.""" url = self.make_key_url(key) data = self.build_args({ 'value': (six.text_type, value), 'dir': (bool, dir or None), 'ttl': (int, ttl), }) try: res = self.session.post(url, data=data, timeout=timeout) except: self.erred() return self.wrap_response(res) def delete(self, key, dir=False, recursive=False, prev_value=None, prev_index=None, timeout=None): """Requests to delete a node by the given key.""" url = self.make_key_url(key) params = self.build_args({ 'dir': (bool, dir or None), 'recursive': (bool, recursive or None), 'prevValue': (six.text_type, prev_value), 'prevIndex': (int, prev_index), }) try: res = self.session.delete(url, params=params, timeout=timeout) except: self.erred() return self.wrap_response(res)
sublee/etc
etc/adapters/etcd.py
EtcdAdapter.set
python
def set(self, key, value=None, dir=False, refresh=False, ttl=None, prev_value=None, prev_index=None, prev_exist=None, timeout=None): url = self.make_key_url(key) data = self.build_args({ 'value': (six.text_type, value), 'dir': (bool, dir or None), 'refresh': (bool, refresh or None), 'ttl': (int, ttl), 'prevValue': (six.text_type, prev_value), 'prevIndex': (int, prev_index), 'prevExist': (bool, prev_exist), }) try: res = self.session.put(url, data=data, timeout=timeout) except: self.erred() return self.wrap_response(res)
Requests to create an ordered node into a node by the given key.
train
https://github.com/sublee/etc/blob/f2be64604da5af0d7739cfacf36f55712f0fc5cb/etc/adapters/etcd.py#L187-L204
null
class EtcdAdapter(Adapter): """An adapter which communicates with an etcd v2 server.""" def __init__(self, url, default_timeout=60): super(EtcdAdapter, self).__init__(url) self.default_timeout = default_timeout self.session = requests.Session() def clear(self): self.session.close() def make_url(self, path, api_root=u'/v2/'): """Gets a full URL from just path.""" return urljoin(urljoin(self.url, api_root), path) def make_key_url(self, key): """Gets a URL for a key.""" if type(key) is bytes: key = key.decode('utf-8') buf = io.StringIO() buf.write(u'keys') if not key.startswith(u'/'): buf.write(u'/') buf.write(key) return self.make_url(buf.getvalue()) @classmethod def make_node(cls, data): try: key = data['key'] except KeyError: key, kwargs = u'/', {} else: kwargs = {'modified_index': int(data['modifiedIndex']), 'created_index': int(data['createdIndex'])} ttl = data.get('ttl') if ttl is not None: expiration = iso8601.parse_date(data['expiration']) kwargs.update(ttl=ttl, expiration=expiration) if 'value' in data: node_cls = Value args = (data['value'],) elif data.get('dir', False): node_cls = Directory args = ([cls.make_node(n) for n in data.get('nodes', ())],) else: node_cls, args = Node, () return node_cls(key, *args, **kwargs) @classmethod def make_result(cls, data, headers=None): action = data['action'] node = cls.make_node(data['node']) kwargs = {} try: prev_node_data = data['prevNode'] except KeyError: pass else: kwargs['prev_node'] = cls.make_node(prev_node_data) if headers: kwargs.update(etcd_index=int(headers['X-Etcd-Index']), raft_index=int(headers['X-Raft-Index']), raft_term=int(headers['X-Raft-Term'])) return EtcdResult.__dispatch__(action)(node, **kwargs) @classmethod def make_error(cls, data, headers=None): errno = data['errorCode'] message = data['message'] cause = data['cause'] index = data['index'] kwargs = {} if headers: kwargs.update(etcd_index=int(headers['X-Etcd-Index']), raft_index=int(headers['X-Raft-Index']), raft_term=int(headers['X-Raft-Term'])) return EtcdError.__dispatch__(errno)(message, cause, index, **kwargs) @classmethod def wrap_response(cls, res): if res.ok: return cls.make_result(res.json(), res.headers) try: json = res.json() except ValueError: raise HTTPError(res.status_code) else: raise cls.make_error(json, res.headers) @staticmethod def build_args(typed_args): args = {} for key, (type_, value) in typed_args.items(): if value is None: continue if type_ is bool: args[key] = u'true' if value else u'false' else: args[key] = value return args @staticmethod def erred(): """Wraps errors. Call it in `except` clause:: try: do_something() except: self.erred() """ exc_type, exc, tb = sys.exc_info() if issubclass(exc_type, socket.timeout): raise TimedOut elif issubclass(exc_type, requests.ConnectionError): internal_exc = exc.args[0] if isinstance(internal_exc, ReadTimeoutError): raise TimedOut else: raise ConnectionError(exc) elif issubclass(exc_type, requests.RequestException): raise EtcException(exc) reraise(exc_type, exc, tb) def get(self, key, recursive=False, sorted=False, quorum=False, wait=False, wait_index=None, timeout=None): """Requests to get a node by the given key.""" url = self.make_key_url(key) params = self.build_args({ 'recursive': (bool, recursive or None), 'sorted': (bool, sorted or None), 'quorum': (bool, quorum or None), 'wait': (bool, wait or None), 'waitIndex': (int, wait_index), }) if timeout is None: # Try again when :exc:`TimedOut` thrown. while True: try: try: res = self.session.get(url, params=params) except: self.erred() except (TimedOut, ChunkedEncodingError): continue else: break else: try: res = self.session.get(url, params=params, timeout=timeout) except ChunkedEncodingError: raise TimedOut except: self.erred() return self.wrap_response(res) def append(self, key, value=None, dir=False, ttl=None, timeout=None): """Requests to create an ordered node into a node by the given key.""" url = self.make_key_url(key) data = self.build_args({ 'value': (six.text_type, value), 'dir': (bool, dir or None), 'ttl': (int, ttl), }) try: res = self.session.post(url, data=data, timeout=timeout) except: self.erred() return self.wrap_response(res) def delete(self, key, dir=False, recursive=False, prev_value=None, prev_index=None, timeout=None): """Requests to delete a node by the given key.""" url = self.make_key_url(key) params = self.build_args({ 'dir': (bool, dir or None), 'recursive': (bool, recursive or None), 'prevValue': (six.text_type, prev_value), 'prevIndex': (int, prev_index), }) try: res = self.session.delete(url, params=params, timeout=timeout) except: self.erred() return self.wrap_response(res)
sublee/etc
etc/adapters/etcd.py
EtcdAdapter.append
python
def append(self, key, value=None, dir=False, ttl=None, timeout=None): url = self.make_key_url(key) data = self.build_args({ 'value': (six.text_type, value), 'dir': (bool, dir or None), 'ttl': (int, ttl), }) try: res = self.session.post(url, data=data, timeout=timeout) except: self.erred() return self.wrap_response(res)
Requests to create an ordered node into a node by the given key.
train
https://github.com/sublee/etc/blob/f2be64604da5af0d7739cfacf36f55712f0fc5cb/etc/adapters/etcd.py#L206-L218
null
class EtcdAdapter(Adapter): """An adapter which communicates with an etcd v2 server.""" def __init__(self, url, default_timeout=60): super(EtcdAdapter, self).__init__(url) self.default_timeout = default_timeout self.session = requests.Session() def clear(self): self.session.close() def make_url(self, path, api_root=u'/v2/'): """Gets a full URL from just path.""" return urljoin(urljoin(self.url, api_root), path) def make_key_url(self, key): """Gets a URL for a key.""" if type(key) is bytes: key = key.decode('utf-8') buf = io.StringIO() buf.write(u'keys') if not key.startswith(u'/'): buf.write(u'/') buf.write(key) return self.make_url(buf.getvalue()) @classmethod def make_node(cls, data): try: key = data['key'] except KeyError: key, kwargs = u'/', {} else: kwargs = {'modified_index': int(data['modifiedIndex']), 'created_index': int(data['createdIndex'])} ttl = data.get('ttl') if ttl is not None: expiration = iso8601.parse_date(data['expiration']) kwargs.update(ttl=ttl, expiration=expiration) if 'value' in data: node_cls = Value args = (data['value'],) elif data.get('dir', False): node_cls = Directory args = ([cls.make_node(n) for n in data.get('nodes', ())],) else: node_cls, args = Node, () return node_cls(key, *args, **kwargs) @classmethod def make_result(cls, data, headers=None): action = data['action'] node = cls.make_node(data['node']) kwargs = {} try: prev_node_data = data['prevNode'] except KeyError: pass else: kwargs['prev_node'] = cls.make_node(prev_node_data) if headers: kwargs.update(etcd_index=int(headers['X-Etcd-Index']), raft_index=int(headers['X-Raft-Index']), raft_term=int(headers['X-Raft-Term'])) return EtcdResult.__dispatch__(action)(node, **kwargs) @classmethod def make_error(cls, data, headers=None): errno = data['errorCode'] message = data['message'] cause = data['cause'] index = data['index'] kwargs = {} if headers: kwargs.update(etcd_index=int(headers['X-Etcd-Index']), raft_index=int(headers['X-Raft-Index']), raft_term=int(headers['X-Raft-Term'])) return EtcdError.__dispatch__(errno)(message, cause, index, **kwargs) @classmethod def wrap_response(cls, res): if res.ok: return cls.make_result(res.json(), res.headers) try: json = res.json() except ValueError: raise HTTPError(res.status_code) else: raise cls.make_error(json, res.headers) @staticmethod def build_args(typed_args): args = {} for key, (type_, value) in typed_args.items(): if value is None: continue if type_ is bool: args[key] = u'true' if value else u'false' else: args[key] = value return args @staticmethod def erred(): """Wraps errors. Call it in `except` clause:: try: do_something() except: self.erred() """ exc_type, exc, tb = sys.exc_info() if issubclass(exc_type, socket.timeout): raise TimedOut elif issubclass(exc_type, requests.ConnectionError): internal_exc = exc.args[0] if isinstance(internal_exc, ReadTimeoutError): raise TimedOut else: raise ConnectionError(exc) elif issubclass(exc_type, requests.RequestException): raise EtcException(exc) reraise(exc_type, exc, tb) def get(self, key, recursive=False, sorted=False, quorum=False, wait=False, wait_index=None, timeout=None): """Requests to get a node by the given key.""" url = self.make_key_url(key) params = self.build_args({ 'recursive': (bool, recursive or None), 'sorted': (bool, sorted or None), 'quorum': (bool, quorum or None), 'wait': (bool, wait or None), 'waitIndex': (int, wait_index), }) if timeout is None: # Try again when :exc:`TimedOut` thrown. while True: try: try: res = self.session.get(url, params=params) except: self.erred() except (TimedOut, ChunkedEncodingError): continue else: break else: try: res = self.session.get(url, params=params, timeout=timeout) except ChunkedEncodingError: raise TimedOut except: self.erred() return self.wrap_response(res) def set(self, key, value=None, dir=False, refresh=False, ttl=None, prev_value=None, prev_index=None, prev_exist=None, timeout=None): """Requests to create an ordered node into a node by the given key.""" url = self.make_key_url(key) data = self.build_args({ 'value': (six.text_type, value), 'dir': (bool, dir or None), 'refresh': (bool, refresh or None), 'ttl': (int, ttl), 'prevValue': (six.text_type, prev_value), 'prevIndex': (int, prev_index), 'prevExist': (bool, prev_exist), }) try: res = self.session.put(url, data=data, timeout=timeout) except: self.erred() return self.wrap_response(res) def delete(self, key, dir=False, recursive=False, prev_value=None, prev_index=None, timeout=None): """Requests to delete a node by the given key.""" url = self.make_key_url(key) params = self.build_args({ 'dir': (bool, dir or None), 'recursive': (bool, recursive or None), 'prevValue': (six.text_type, prev_value), 'prevIndex': (int, prev_index), }) try: res = self.session.delete(url, params=params, timeout=timeout) except: self.erred() return self.wrap_response(res)
sublee/etc
etc/adapters/etcd.py
EtcdAdapter.delete
python
def delete(self, key, dir=False, recursive=False, prev_value=None, prev_index=None, timeout=None): url = self.make_key_url(key) params = self.build_args({ 'dir': (bool, dir or None), 'recursive': (bool, recursive or None), 'prevValue': (six.text_type, prev_value), 'prevIndex': (int, prev_index), }) try: res = self.session.delete(url, params=params, timeout=timeout) except: self.erred() return self.wrap_response(res)
Requests to delete a node by the given key.
train
https://github.com/sublee/etc/blob/f2be64604da5af0d7739cfacf36f55712f0fc5cb/etc/adapters/etcd.py#L220-L234
null
class EtcdAdapter(Adapter): """An adapter which communicates with an etcd v2 server.""" def __init__(self, url, default_timeout=60): super(EtcdAdapter, self).__init__(url) self.default_timeout = default_timeout self.session = requests.Session() def clear(self): self.session.close() def make_url(self, path, api_root=u'/v2/'): """Gets a full URL from just path.""" return urljoin(urljoin(self.url, api_root), path) def make_key_url(self, key): """Gets a URL for a key.""" if type(key) is bytes: key = key.decode('utf-8') buf = io.StringIO() buf.write(u'keys') if not key.startswith(u'/'): buf.write(u'/') buf.write(key) return self.make_url(buf.getvalue()) @classmethod def make_node(cls, data): try: key = data['key'] except KeyError: key, kwargs = u'/', {} else: kwargs = {'modified_index': int(data['modifiedIndex']), 'created_index': int(data['createdIndex'])} ttl = data.get('ttl') if ttl is not None: expiration = iso8601.parse_date(data['expiration']) kwargs.update(ttl=ttl, expiration=expiration) if 'value' in data: node_cls = Value args = (data['value'],) elif data.get('dir', False): node_cls = Directory args = ([cls.make_node(n) for n in data.get('nodes', ())],) else: node_cls, args = Node, () return node_cls(key, *args, **kwargs) @classmethod def make_result(cls, data, headers=None): action = data['action'] node = cls.make_node(data['node']) kwargs = {} try: prev_node_data = data['prevNode'] except KeyError: pass else: kwargs['prev_node'] = cls.make_node(prev_node_data) if headers: kwargs.update(etcd_index=int(headers['X-Etcd-Index']), raft_index=int(headers['X-Raft-Index']), raft_term=int(headers['X-Raft-Term'])) return EtcdResult.__dispatch__(action)(node, **kwargs) @classmethod def make_error(cls, data, headers=None): errno = data['errorCode'] message = data['message'] cause = data['cause'] index = data['index'] kwargs = {} if headers: kwargs.update(etcd_index=int(headers['X-Etcd-Index']), raft_index=int(headers['X-Raft-Index']), raft_term=int(headers['X-Raft-Term'])) return EtcdError.__dispatch__(errno)(message, cause, index, **kwargs) @classmethod def wrap_response(cls, res): if res.ok: return cls.make_result(res.json(), res.headers) try: json = res.json() except ValueError: raise HTTPError(res.status_code) else: raise cls.make_error(json, res.headers) @staticmethod def build_args(typed_args): args = {} for key, (type_, value) in typed_args.items(): if value is None: continue if type_ is bool: args[key] = u'true' if value else u'false' else: args[key] = value return args @staticmethod def erred(): """Wraps errors. Call it in `except` clause:: try: do_something() except: self.erred() """ exc_type, exc, tb = sys.exc_info() if issubclass(exc_type, socket.timeout): raise TimedOut elif issubclass(exc_type, requests.ConnectionError): internal_exc = exc.args[0] if isinstance(internal_exc, ReadTimeoutError): raise TimedOut else: raise ConnectionError(exc) elif issubclass(exc_type, requests.RequestException): raise EtcException(exc) reraise(exc_type, exc, tb) def get(self, key, recursive=False, sorted=False, quorum=False, wait=False, wait_index=None, timeout=None): """Requests to get a node by the given key.""" url = self.make_key_url(key) params = self.build_args({ 'recursive': (bool, recursive or None), 'sorted': (bool, sorted or None), 'quorum': (bool, quorum or None), 'wait': (bool, wait or None), 'waitIndex': (int, wait_index), }) if timeout is None: # Try again when :exc:`TimedOut` thrown. while True: try: try: res = self.session.get(url, params=params) except: self.erred() except (TimedOut, ChunkedEncodingError): continue else: break else: try: res = self.session.get(url, params=params, timeout=timeout) except ChunkedEncodingError: raise TimedOut except: self.erred() return self.wrap_response(res) def set(self, key, value=None, dir=False, refresh=False, ttl=None, prev_value=None, prev_index=None, prev_exist=None, timeout=None): """Requests to create an ordered node into a node by the given key.""" url = self.make_key_url(key) data = self.build_args({ 'value': (six.text_type, value), 'dir': (bool, dir or None), 'refresh': (bool, refresh or None), 'ttl': (int, ttl), 'prevValue': (six.text_type, prev_value), 'prevIndex': (int, prev_index), 'prevExist': (bool, prev_exist), }) try: res = self.session.put(url, data=data, timeout=timeout) except: self.erred() return self.wrap_response(res) def append(self, key, value=None, dir=False, ttl=None, timeout=None): """Requests to create an ordered node into a node by the given key.""" url = self.make_key_url(key) data = self.build_args({ 'value': (six.text_type, value), 'dir': (bool, dir or None), 'ttl': (int, ttl), }) try: res = self.session.post(url, data=data, timeout=timeout) except: self.erred() return self.wrap_response(res)
nhfruchter/pgh-bustime
pghbustime/datatypes.py
Bus.get
python
def get(_class, api, vid): busses = api.vehicles(vid=vid)['vehicle'] return _class.fromapi(api, api.vehicles(vid=vid)['vehicle'])
Return a Bus object for a certain vehicle ID `vid` using API instance `api`.
train
https://github.com/nhfruchter/pgh-bustime/blob/b915e8fea28541612f0e79783c2cf12fd3daaac0/pghbustime/datatypes.py#L13-L19
null
class Bus(object): """Represents an individual vehicle on a route with a location.""" @classmethod @classmethod def fromapi(_class, api, apiresponse): """ Return a Bus object from an API response dict. """ bus = apiresponse return _class( api = api, vid = bus['vid'], timeupdated = datetime.strptime(bus['tmstmp'], api.STRPTIME), lat = float(bus['lat']), lng = float(bus['lon']), heading = bus['hdg'], pid = bus['pid'], intotrip = bus['pdist'], route = bus['rt'], destination = bus['des'], speed = bus['spd'], delay = bus.get('dly') or False ) def __init__(self, api, vid, timeupdated, lat, lng, heading, pid, intotrip, route, destination, speed, delay=False): self.api = api self.vid = vid self.timeupdated = timezone("US/Eastern").localize(timeupdated) self.location = (lat, lng) self.heading = int(heading) self.patternid = pid self.dist_in_trip = intotrip self.route = route self.destination = destination self.speed = speed self.delayed = delay def __str__(self): return "<Bus #{} on {} {}> - at {} as of {}".format(self.vid, self.route, self.destination, self.location, self.timeupdated) def __repr__(self): return self.__str__() def update(self): """Update this bus by creating a new one and transplanting dictionaries.""" vehicle = self.api.vehicles(vid=self.vid)['vehicle'] newbus = self.fromapi(self.api, vehicle) self.__dict__ = newbus.__dict__ del newbus @property def pattern(self): return self.api.geopatterns(pid=self.patternid) @property def predictions(self): """Generator that yields prediction objects from an API response.""" for prediction in self.api.predictions(vid=self.vid)['prd']: pobj = Prediction.fromapi(self.api, prediction) pobj._busobj = self yield pobj @property def next_stop(self): """Return the next stop for this bus.""" p = self.api.predictions(vid=self.vid)['prd'] pobj = Prediction.fromapi(self.api, p[0]) pobj._busobj = self return pobj
nhfruchter/pgh-bustime
pghbustime/datatypes.py
Bus.fromapi
python
def fromapi(_class, api, apiresponse): bus = apiresponse return _class( api = api, vid = bus['vid'], timeupdated = datetime.strptime(bus['tmstmp'], api.STRPTIME), lat = float(bus['lat']), lng = float(bus['lon']), heading = bus['hdg'], pid = bus['pid'], intotrip = bus['pdist'], route = bus['rt'], destination = bus['des'], speed = bus['spd'], delay = bus.get('dly') or False )
Return a Bus object from an API response dict.
train
https://github.com/nhfruchter/pgh-bustime/blob/b915e8fea28541612f0e79783c2cf12fd3daaac0/pghbustime/datatypes.py#L22-L40
null
class Bus(object): """Represents an individual vehicle on a route with a location.""" @classmethod def get(_class, api, vid): """ Return a Bus object for a certain vehicle ID `vid` using API instance `api`. """ busses = api.vehicles(vid=vid)['vehicle'] return _class.fromapi(api, api.vehicles(vid=vid)['vehicle']) @classmethod def __init__(self, api, vid, timeupdated, lat, lng, heading, pid, intotrip, route, destination, speed, delay=False): self.api = api self.vid = vid self.timeupdated = timezone("US/Eastern").localize(timeupdated) self.location = (lat, lng) self.heading = int(heading) self.patternid = pid self.dist_in_trip = intotrip self.route = route self.destination = destination self.speed = speed self.delayed = delay def __str__(self): return "<Bus #{} on {} {}> - at {} as of {}".format(self.vid, self.route, self.destination, self.location, self.timeupdated) def __repr__(self): return self.__str__() def update(self): """Update this bus by creating a new one and transplanting dictionaries.""" vehicle = self.api.vehicles(vid=self.vid)['vehicle'] newbus = self.fromapi(self.api, vehicle) self.__dict__ = newbus.__dict__ del newbus @property def pattern(self): return self.api.geopatterns(pid=self.patternid) @property def predictions(self): """Generator that yields prediction objects from an API response.""" for prediction in self.api.predictions(vid=self.vid)['prd']: pobj = Prediction.fromapi(self.api, prediction) pobj._busobj = self yield pobj @property def next_stop(self): """Return the next stop for this bus.""" p = self.api.predictions(vid=self.vid)['prd'] pobj = Prediction.fromapi(self.api, p[0]) pobj._busobj = self return pobj
nhfruchter/pgh-bustime
pghbustime/datatypes.py
Bus.update
python
def update(self): vehicle = self.api.vehicles(vid=self.vid)['vehicle'] newbus = self.fromapi(self.api, vehicle) self.__dict__ = newbus.__dict__ del newbus
Update this bus by creating a new one and transplanting dictionaries.
train
https://github.com/nhfruchter/pgh-bustime/blob/b915e8fea28541612f0e79783c2cf12fd3daaac0/pghbustime/datatypes.py#L61-L66
[ "def fromapi(_class, api, apiresponse):\n \"\"\"\n Return a Bus object from an API response dict.\n \"\"\"\n bus = apiresponse\n return _class(\n api = api,\n vid = bus['vid'],\n timeupdated = datetime.strptime(bus['tmstmp'], api.STRPTIME),\n lat = float(bus['lat']),\n ...
class Bus(object): """Represents an individual vehicle on a route with a location.""" @classmethod def get(_class, api, vid): """ Return a Bus object for a certain vehicle ID `vid` using API instance `api`. """ busses = api.vehicles(vid=vid)['vehicle'] return _class.fromapi(api, api.vehicles(vid=vid)['vehicle']) @classmethod def fromapi(_class, api, apiresponse): """ Return a Bus object from an API response dict. """ bus = apiresponse return _class( api = api, vid = bus['vid'], timeupdated = datetime.strptime(bus['tmstmp'], api.STRPTIME), lat = float(bus['lat']), lng = float(bus['lon']), heading = bus['hdg'], pid = bus['pid'], intotrip = bus['pdist'], route = bus['rt'], destination = bus['des'], speed = bus['spd'], delay = bus.get('dly') or False ) def __init__(self, api, vid, timeupdated, lat, lng, heading, pid, intotrip, route, destination, speed, delay=False): self.api = api self.vid = vid self.timeupdated = timezone("US/Eastern").localize(timeupdated) self.location = (lat, lng) self.heading = int(heading) self.patternid = pid self.dist_in_trip = intotrip self.route = route self.destination = destination self.speed = speed self.delayed = delay def __str__(self): return "<Bus #{} on {} {}> - at {} as of {}".format(self.vid, self.route, self.destination, self.location, self.timeupdated) def __repr__(self): return self.__str__() @property def pattern(self): return self.api.geopatterns(pid=self.patternid) @property def predictions(self): """Generator that yields prediction objects from an API response.""" for prediction in self.api.predictions(vid=self.vid)['prd']: pobj = Prediction.fromapi(self.api, prediction) pobj._busobj = self yield pobj @property def next_stop(self): """Return the next stop for this bus.""" p = self.api.predictions(vid=self.vid)['prd'] pobj = Prediction.fromapi(self.api, p[0]) pobj._busobj = self return pobj
nhfruchter/pgh-bustime
pghbustime/datatypes.py
Bus.predictions
python
def predictions(self): for prediction in self.api.predictions(vid=self.vid)['prd']: pobj = Prediction.fromapi(self.api, prediction) pobj._busobj = self yield pobj
Generator that yields prediction objects from an API response.
train
https://github.com/nhfruchter/pgh-bustime/blob/b915e8fea28541612f0e79783c2cf12fd3daaac0/pghbustime/datatypes.py#L73-L78
[ "def fromapi(_class, api, apiresponse):\n generated_time = datetime.strptime(apiresponse['tmstmp'], api.STRPTIME)\n arrival = True if apiresponse['typ'] == 'A' else False\n bus = apiresponse['vid']\n stop = _class.pstop(apiresponse['stpid'], apiresponse['stpnm'], int(apiresponse['dstp']))\n route = a...
class Bus(object): """Represents an individual vehicle on a route with a location.""" @classmethod def get(_class, api, vid): """ Return a Bus object for a certain vehicle ID `vid` using API instance `api`. """ busses = api.vehicles(vid=vid)['vehicle'] return _class.fromapi(api, api.vehicles(vid=vid)['vehicle']) @classmethod def fromapi(_class, api, apiresponse): """ Return a Bus object from an API response dict. """ bus = apiresponse return _class( api = api, vid = bus['vid'], timeupdated = datetime.strptime(bus['tmstmp'], api.STRPTIME), lat = float(bus['lat']), lng = float(bus['lon']), heading = bus['hdg'], pid = bus['pid'], intotrip = bus['pdist'], route = bus['rt'], destination = bus['des'], speed = bus['spd'], delay = bus.get('dly') or False ) def __init__(self, api, vid, timeupdated, lat, lng, heading, pid, intotrip, route, destination, speed, delay=False): self.api = api self.vid = vid self.timeupdated = timezone("US/Eastern").localize(timeupdated) self.location = (lat, lng) self.heading = int(heading) self.patternid = pid self.dist_in_trip = intotrip self.route = route self.destination = destination self.speed = speed self.delayed = delay def __str__(self): return "<Bus #{} on {} {}> - at {} as of {}".format(self.vid, self.route, self.destination, self.location, self.timeupdated) def __repr__(self): return self.__str__() def update(self): """Update this bus by creating a new one and transplanting dictionaries.""" vehicle = self.api.vehicles(vid=self.vid)['vehicle'] newbus = self.fromapi(self.api, vehicle) self.__dict__ = newbus.__dict__ del newbus @property def pattern(self): return self.api.geopatterns(pid=self.patternid) @property @property def next_stop(self): """Return the next stop for this bus.""" p = self.api.predictions(vid=self.vid)['prd'] pobj = Prediction.fromapi(self.api, p[0]) pobj._busobj = self return pobj
nhfruchter/pgh-bustime
pghbustime/datatypes.py
Bus.next_stop
python
def next_stop(self): p = self.api.predictions(vid=self.vid)['prd'] pobj = Prediction.fromapi(self.api, p[0]) pobj._busobj = self return pobj
Return the next stop for this bus.
train
https://github.com/nhfruchter/pgh-bustime/blob/b915e8fea28541612f0e79783c2cf12fd3daaac0/pghbustime/datatypes.py#L81-L86
[ "def fromapi(_class, api, apiresponse):\n generated_time = datetime.strptime(apiresponse['tmstmp'], api.STRPTIME)\n arrival = True if apiresponse['typ'] == 'A' else False\n bus = apiresponse['vid']\n stop = _class.pstop(apiresponse['stpid'], apiresponse['stpnm'], int(apiresponse['dstp']))\n route = a...
class Bus(object): """Represents an individual vehicle on a route with a location.""" @classmethod def get(_class, api, vid): """ Return a Bus object for a certain vehicle ID `vid` using API instance `api`. """ busses = api.vehicles(vid=vid)['vehicle'] return _class.fromapi(api, api.vehicles(vid=vid)['vehicle']) @classmethod def fromapi(_class, api, apiresponse): """ Return a Bus object from an API response dict. """ bus = apiresponse return _class( api = api, vid = bus['vid'], timeupdated = datetime.strptime(bus['tmstmp'], api.STRPTIME), lat = float(bus['lat']), lng = float(bus['lon']), heading = bus['hdg'], pid = bus['pid'], intotrip = bus['pdist'], route = bus['rt'], destination = bus['des'], speed = bus['spd'], delay = bus.get('dly') or False ) def __init__(self, api, vid, timeupdated, lat, lng, heading, pid, intotrip, route, destination, speed, delay=False): self.api = api self.vid = vid self.timeupdated = timezone("US/Eastern").localize(timeupdated) self.location = (lat, lng) self.heading = int(heading) self.patternid = pid self.dist_in_trip = intotrip self.route = route self.destination = destination self.speed = speed self.delayed = delay def __str__(self): return "<Bus #{} on {} {}> - at {} as of {}".format(self.vid, self.route, self.destination, self.location, self.timeupdated) def __repr__(self): return self.__str__() def update(self): """Update this bus by creating a new one and transplanting dictionaries.""" vehicle = self.api.vehicles(vid=self.vid)['vehicle'] newbus = self.fromapi(self.api, vehicle) self.__dict__ = newbus.__dict__ del newbus @property def pattern(self): return self.api.geopatterns(pid=self.patternid) @property def predictions(self): """Generator that yields prediction objects from an API response.""" for prediction in self.api.predictions(vid=self.vid)['prd']: pobj = Prediction.fromapi(self.api, prediction) pobj._busobj = self yield pobj @property
nhfruchter/pgh-bustime
pghbustime/datatypes.py
Route.get
python
def get(_class, api, rt): if not _class.all_routes: _class.all_routes = _class.update_list(api, api.routes()['route']) return _class.all_routes[str(rt)]
Return a Route object for route `rt` using API instance `api`.
train
https://github.com/nhfruchter/pgh-bustime/blob/b915e8fea28541612f0e79783c2cf12fd3daaac0/pghbustime/datatypes.py#L114-L122
null
class Route(object): """Represents a certain bus route (e.g. P1). Also contains a list of all the valid routes.""" all_routes = {} # store list of all routes currently @classmethod def update_list(_class, api, rtdicts): allroutes = {} for rtdict in rtdicts: rtobject = Route.fromapi(api, rtdict) allroutes[str(rtobject.number)] = rtobject return allroutes @classmethod def get(_class, api, rt): """ Return a Route object for route `rt` using API instance `api`. """ if not _class.all_routes: _class.all_routes = _class.update_list(api, api.routes()['route']) return _class.all_routes[str(rt)] @classmethod def fromapi(_class, api, apiresponse): return _class(api, apiresponse['rt'], apiresponse['rtnm'], apiresponse['rtclr']) def __init__(self, api, number, name, color): self.api = api self.number = number self.name = name self.color = color self.stops = {} def __str__(self): return "{} {}".format(self.number, self.name) def __repr__(self): classname = self.__class__.__name__ return "{}({}, {})".format(classname, self.name, self.number) def __hash__(self): return hash(str(self)) @property def bulletins(self): apiresponse = self.api.bulletins(rt=self.number) if apiresponse: for b in apiresponse['sb']: yield Bulletin.fromapi(b) @property def detours(self): self._detours = self.api.detournotices(self.number) return self._detours @property def patterns(self): return self.api.geopatterns(rt=self.number) @property def busses(self): apiresp = self.api.vehicles(rt=self.number)['vehicle'] if type(apiresp) is list: for busdict in apiresp: busobj = Bus.fromapi(self.api, busdict) busobj.route = self yield busobj else: busobj = Bus.fromapi(self.api, apiresp) busobj.route = self yield busobj @property def directions(self): if not hasattr(self, "_directions"): self._directions = self.api.route_directions(self.number)['dir'] return self._directions @property def inbound_stops(self): try: return self.stops['inbound'] except: inboundstops = self.api.stops(self.number, "INBOUND")['stop'] self.stops['inbound'] = [StopWithLocation.fromapi(self.api, stop) for stop in inboundstops] return self.stops['inbound'] @property def outbound_stops(self): try: return self.stops['outbound'] except: outboundstops = self.api.stops(self.number, "OUTBOUND")['stop'] self.stops['outbound'] = [StopWithLocation.fromapi(self.api, stop) for stop in outboundstops] return self.stops['outbound'] def find_stop(self, query, direction=""): """ Search the list of stops, optionally in a direction (inbound or outbound), for the term passed to the function. Case insensitive, searches both the stop name and ID. Yields a generator. Defaults to both directions. """ _directions = ["inbound", "outbound", ""] direction = direction.lower() if direction == "inbound": stops = self.inbound_stops elif direction == "outbound": stops = self.outbound_stops else: stops = self.inbound_stops + self.outbound_stops found = [] for stop in stops: q = str(query).lower() if q in stop.name.lower() or q in str(stop.id).lower(): found.append(stop) return found
nhfruchter/pgh-bustime
pghbustime/datatypes.py
Route.find_stop
python
def find_stop(self, query, direction=""): _directions = ["inbound", "outbound", ""] direction = direction.lower() if direction == "inbound": stops = self.inbound_stops elif direction == "outbound": stops = self.outbound_stops else: stops = self.inbound_stops + self.outbound_stops found = [] for stop in stops: q = str(query).lower() if q in stop.name.lower() or q in str(stop.id).lower(): found.append(stop) return found
Search the list of stops, optionally in a direction (inbound or outbound), for the term passed to the function. Case insensitive, searches both the stop name and ID. Yields a generator. Defaults to both directions.
train
https://github.com/nhfruchter/pgh-bustime/blob/b915e8fea28541612f0e79783c2cf12fd3daaac0/pghbustime/datatypes.py#L198-L220
null
class Route(object): """Represents a certain bus route (e.g. P1). Also contains a list of all the valid routes.""" all_routes = {} # store list of all routes currently @classmethod def update_list(_class, api, rtdicts): allroutes = {} for rtdict in rtdicts: rtobject = Route.fromapi(api, rtdict) allroutes[str(rtobject.number)] = rtobject return allroutes @classmethod def get(_class, api, rt): """ Return a Route object for route `rt` using API instance `api`. """ if not _class.all_routes: _class.all_routes = _class.update_list(api, api.routes()['route']) return _class.all_routes[str(rt)] @classmethod def fromapi(_class, api, apiresponse): return _class(api, apiresponse['rt'], apiresponse['rtnm'], apiresponse['rtclr']) def __init__(self, api, number, name, color): self.api = api self.number = number self.name = name self.color = color self.stops = {} def __str__(self): return "{} {}".format(self.number, self.name) def __repr__(self): classname = self.__class__.__name__ return "{}({}, {})".format(classname, self.name, self.number) def __hash__(self): return hash(str(self)) @property def bulletins(self): apiresponse = self.api.bulletins(rt=self.number) if apiresponse: for b in apiresponse['sb']: yield Bulletin.fromapi(b) @property def detours(self): self._detours = self.api.detournotices(self.number) return self._detours @property def patterns(self): return self.api.geopatterns(rt=self.number) @property def busses(self): apiresp = self.api.vehicles(rt=self.number)['vehicle'] if type(apiresp) is list: for busdict in apiresp: busobj = Bus.fromapi(self.api, busdict) busobj.route = self yield busobj else: busobj = Bus.fromapi(self.api, apiresp) busobj.route = self yield busobj @property def directions(self): if not hasattr(self, "_directions"): self._directions = self.api.route_directions(self.number)['dir'] return self._directions @property def inbound_stops(self): try: return self.stops['inbound'] except: inboundstops = self.api.stops(self.number, "INBOUND")['stop'] self.stops['inbound'] = [StopWithLocation.fromapi(self.api, stop) for stop in inboundstops] return self.stops['inbound'] @property def outbound_stops(self): try: return self.stops['outbound'] except: outboundstops = self.api.stops(self.number, "OUTBOUND")['stop'] self.stops['outbound'] = [StopWithLocation.fromapi(self.api, stop) for stop in outboundstops] return self.stops['outbound'] def find_stop(self, query, direction=""): """ Search the list of stops, optionally in a direction (inbound or outbound), for the term passed to the function. Case insensitive, searches both the stop name and ID. Yields a generator. Defaults to both directions. """ _directions = ["inbound", "outbound", ""] direction = direction.lower() if direction == "inbound": stops = self.inbound_stops elif direction == "outbound": stops = self.outbound_stops else: stops = self.inbound_stops + self.outbound_stops found = [] for stop in stops: q = str(query).lower() if q in stop.name.lower() or q in str(stop.id).lower(): found.append(stop) return found
nhfruchter/pgh-bustime
pghbustime/datatypes.py
Stop.predictions
python
def predictions(self, route=''): """ Yields predicted bus ETAs for this stop. You can specify a route identifier for ETAs specific to one route, or leave `route` blank (done by default) to get information on all arriving busses. """ apiresponse = self.api.predictions(stpid=self.id, rt=route)['prd'] if type(apiresponse) is list: for prediction in apiresponse: try: pobj = Prediction.fromapi(self.api, prediction) pobj._stopobj = self yield pobj except: continue else: pobj = Prediction.fromapi(self.api, apiresponse) pobj._stopobj = self yield pobj
Yields predicted bus ETAs for this stop. You can specify a route identifier for ETAs specific to one route, or leave `route` blank (done by default) to get information on all arriving busses.
train
https://github.com/nhfruchter/pgh-bustime/blob/b915e8fea28541612f0e79783c2cf12fd3daaac0/pghbustime/datatypes.py#L252-L270
[ "def fromapi(_class, api, apiresponse):\n generated_time = datetime.strptime(apiresponse['tmstmp'], api.STRPTIME)\n arrival = True if apiresponse['typ'] == 'A' else False\n bus = apiresponse['vid']\n stop = _class.pstop(apiresponse['stpid'], apiresponse['stpnm'], int(apiresponse['dstp']))\n route = a...
class Stop(object): """Represents a single stop.""" @classmethod def get(_class, api, stpid): """ Returns a Stop object for stop # `stpid` using API instance `api`. The API doesn't support looking up information for an individual stop, so all stops generated using Stop.get only have stop ID # info attached. Getting a stop from a Route is the recommended method of finding a specific stop (using `find_stop`/`inbound_stop`/`outbound_stop` functions). >>> Stop.get(1605) Stop(1605, "(Unnamed)") """ return _class(api, stpid, "(Unnamed)") def __init__(self, api, _id, name): self.api = api self.id = _id self.name = name def __repr__(self): classname = self.__class__.__name__ return "{}({}, {})".format(classname, self.id, self.name) def __hash__(self): return hash(str(self)) @property def bulletins(self): apiresponse = self.api.bulletins(stpid=self.id) if apiresponse: for b in apiresponse['sb']: yield Bulletin.fromapi(b)
nhfruchter/pgh-bustime
pghbustime/datatypes.py
Bulletin.fromapi
python
def fromapi(_class, apiresponse): for resp in apiresponse['sb']: # Extract details from dict _id = "n/a" or resp.get("nm") subject = resp.get("sbj") text = resp.get('dtl') + "\n" + resp.get('brf') priority = "n/a" or resp.get('prty') for_stops, for_routes = [], [] svc = resp.get('srvc') # Create list of affected routes/stops, if there are any if svc: has_stop = 'stpid' in svc or 'stpnm' in svc has_rt = 'rt' in svc or 'rtdir' in svc if has_stop: aff = _class.affected_service('stop', svc.get('stpid'), svc.get('stpnm')) for_stops.append(aff) if has_rt: aff = _class.affected_service('route', svc.get('rt'), svc.get('rtdir')) for_routes.append(aff) yield _class(_id, subject, text, priority, for_stops, for_routes)
Create a bulletin object from an API response (dict), containing `sbj`, etc.
train
https://github.com/nhfruchter/pgh-bustime/blob/b915e8fea28541612f0e79783c2cf12fd3daaac0/pghbustime/datatypes.py#L391-L414
null
class Bulletin(object): """ A service bulletin, usually representing a detour or other type of route change. """ affected_service = namedtuple('affected_service', ['type', 'id', 'name']) @classmethod def get(_class, api, rt=None, rtdir=None, stpid=None): if not (rt or stpid) or (rtdir and not (rt or stpid)): raise ValueError("You must specify a parameter.") if listlike(stpid): stpid = ",".join(stpid) if listlike(rt): rt = ",".join(rt) bulletins = api.bulletins(rt=rt, rtdir=rtdir, stpid=stpid) if bulletins: bulletins = bulletins['sb'] if type(bulletins) is list: return [_class.fromapi(b) for b in bulletins] else: return _class.fromapi(bulletins) @classmethod def fromapi(_class, apiresponse): """Create a bulletin object from an API response (dict), containing `sbj`, etc.""" for resp in apiresponse['sb']: # Extract details from dict _id = "n/a" or resp.get("nm") subject = resp.get("sbj") text = resp.get('dtl') + "\n" + resp.get('brf') priority = "n/a" or resp.get('prty') for_stops, for_routes = [], [] svc = resp.get('srvc') # Create list of affected routes/stops, if there are any if svc: has_stop = 'stpid' in svc or 'stpnm' in svc has_rt = 'rt' in svc or 'rtdir' in svc if has_stop: aff = _class.affected_service('stop', svc.get('stpid'), svc.get('stpnm')) for_stops.append(aff) if has_rt: aff = _class.affected_service('route', svc.get('rt'), svc.get('rtdir')) for_routes.append(aff) yield _class(_id, subject, text, priority, for_stops, for_routes) def __init__(self, _id, subject, text, priority, for_stops=None, for_routes=None): self.id = _id self.subject = subject self.body = text self.priority = priority self._stops = for_stops or [] self._routes = for_routes or [] def __str__(self): formatted = "Bulletin #{}\n\nSubject: {}\nPriority: {}\n\n{}\n\nValid for stops: {}\nValid for routes: {}" return formatted.format(self.id, self.subject, self.priority, self.body, self._stops, self._routes) @property def valid_for(self): return dict( stops=self._stops, routes=self._routes )
nhfruchter/pgh-bustime
pghbustime/utils.py
queryjoin
python
def queryjoin(argdict=dict(), **kwargs): if kwargs: argdict.update(kwargs) if issubclass(type(argdict), dict): args = ["{}={}".format(k, v) for k, v in argdict.items() if v != None] return "&".join(args)
Turn a dictionary into a querystring for a URL. >>> args = dict(a=1, b=2, c="foo") >>> queryjoin(args) "a=1&b=2&c=foo"
train
https://github.com/nhfruchter/pgh-bustime/blob/b915e8fea28541612f0e79783c2cf12fd3daaac0/pghbustime/utils.py#L3-L14
null
"""Some utility functions and other stuff.""" def queryjoin(argdict=dict(), **kwargs): """Turn a dictionary into a querystring for a URL. >>> args = dict(a=1, b=2, c="foo") >>> queryjoin(args) "a=1&b=2&c=foo" """ if kwargs: argdict.update(kwargs) if issubclass(type(argdict), dict): args = ["{}={}".format(k, v) for k, v in argdict.items() if v != None] return "&".join(args) def listlike(obj): """Is an object iterable like a list (and not a string)?""" return hasattr(obj, "__iter__") \ and not issubclass(type(obj), str)\ and not issubclass(type(obj), unicode) def patterntogeojson(pattern, color=False): import geojson """ Turns an an API response of a pattern into a GeoJSON FeatureCollection. Takes a dict that contains at least `pid`, `ln`, `rtdir`, and `pt`. >>> api_response = {'ln': '123.45', 'pid': '1', 'pt': [], 'rtdir': 'OUTBOUND'} >>> pt1 = {'lat': '40.449', 'lon': '-79.983', 'seq': '1', 'typ': 'W'} >>> pt2 = {'stpid': '1', 'seq': '2', 'stpnm': '3142 Test Ave FS', 'lon': '-79.984', 'pdist': '42.4', 'lat': '40.450', 'typ': 'S'} >>> api_response['pt'] = [pt1, pt2] >>> patterntogeojson(api_response) # doctest: +ELLIPSIS {"features": [{"geometry": {"coordinates": ... "name": "3142 Test Ave FS", "type": "stop"}, "type": "Feature"}], "type": "FeatureCollection"} """ # Base properties for the pattern properties = dict( pid = pattern['pid'], length = pattern['ln'], direction = pattern['rtdir'], color = color or "" ) points = [(float(point.get('lon')), float(point.get('lat'))) for point in pattern['pt']] return geojson.LineString(coordinates=points, properties=properties)
nhfruchter/pgh-bustime
pghbustime/utils.py
listlike
python
def listlike(obj): return hasattr(obj, "__iter__") \ and not issubclass(type(obj), str)\ and not issubclass(type(obj), unicode)
Is an object iterable like a list (and not a string)?
train
https://github.com/nhfruchter/pgh-bustime/blob/b915e8fea28541612f0e79783c2cf12fd3daaac0/pghbustime/utils.py#L16-L21
null
"""Some utility functions and other stuff.""" def queryjoin(argdict=dict(), **kwargs): """Turn a dictionary into a querystring for a URL. >>> args = dict(a=1, b=2, c="foo") >>> queryjoin(args) "a=1&b=2&c=foo" """ if kwargs: argdict.update(kwargs) if issubclass(type(argdict), dict): args = ["{}={}".format(k, v) for k, v in argdict.items() if v != None] return "&".join(args) def listlike(obj): """Is an object iterable like a list (and not a string)?""" return hasattr(obj, "__iter__") \ and not issubclass(type(obj), str)\ and not issubclass(type(obj), unicode) def patterntogeojson(pattern, color=False): import geojson """ Turns an an API response of a pattern into a GeoJSON FeatureCollection. Takes a dict that contains at least `pid`, `ln`, `rtdir`, and `pt`. >>> api_response = {'ln': '123.45', 'pid': '1', 'pt': [], 'rtdir': 'OUTBOUND'} >>> pt1 = {'lat': '40.449', 'lon': '-79.983', 'seq': '1', 'typ': 'W'} >>> pt2 = {'stpid': '1', 'seq': '2', 'stpnm': '3142 Test Ave FS', 'lon': '-79.984', 'pdist': '42.4', 'lat': '40.450', 'typ': 'S'} >>> api_response['pt'] = [pt1, pt2] >>> patterntogeojson(api_response) # doctest: +ELLIPSIS {"features": [{"geometry": {"coordinates": ... "name": "3142 Test Ave FS", "type": "stop"}, "type": "Feature"}], "type": "FeatureCollection"} """ # Base properties for the pattern properties = dict( pid = pattern['pid'], length = pattern['ln'], direction = pattern['rtdir'], color = color or "" ) points = [(float(point.get('lon')), float(point.get('lat'))) for point in pattern['pt']] return geojson.LineString(coordinates=points, properties=properties)
nhfruchter/pgh-bustime
pghbustime/utils.py
patterntogeojson
python
def patterntogeojson(pattern, color=False): import geojson """ Turns an an API response of a pattern into a GeoJSON FeatureCollection. Takes a dict that contains at least `pid`, `ln`, `rtdir`, and `pt`. >>> api_response = {'ln': '123.45', 'pid': '1', 'pt': [], 'rtdir': 'OUTBOUND'} >>> pt1 = {'lat': '40.449', 'lon': '-79.983', 'seq': '1', 'typ': 'W'} >>> pt2 = {'stpid': '1', 'seq': '2', 'stpnm': '3142 Test Ave FS', 'lon': '-79.984', 'pdist': '42.4', 'lat': '40.450', 'typ': 'S'} >>> api_response['pt'] = [pt1, pt2] >>> patterntogeojson(api_response) # doctest: +ELLIPSIS {"features": [{"geometry": {"coordinates": ... "name": "3142 Test Ave FS", "type": "stop"}, "type": "Feature"}], "type": "FeatureCollection"} """ # Base properties for the pattern properties = dict( pid = pattern['pid'], length = pattern['ln'], direction = pattern['rtdir'], color = color or "" ) points = [(float(point.get('lon')), float(point.get('lat'))) for point in pattern['pt']] return geojson.LineString(coordinates=points, properties=properties)
Turns an an API response of a pattern into a GeoJSON FeatureCollection. Takes a dict that contains at least `pid`, `ln`, `rtdir`, and `pt`. >>> api_response = {'ln': '123.45', 'pid': '1', 'pt': [], 'rtdir': 'OUTBOUND'} >>> pt1 = {'lat': '40.449', 'lon': '-79.983', 'seq': '1', 'typ': 'W'} >>> pt2 = {'stpid': '1', 'seq': '2', 'stpnm': '3142 Test Ave FS', 'lon': '-79.984', 'pdist': '42.4', 'lat': '40.450', 'typ': 'S'} >>> api_response['pt'] = [pt1, pt2] >>> patterntogeojson(api_response) # doctest: +ELLIPSIS {"features": [{"geometry": {"coordinates": ... "name": "3142 Test Ave FS", "type": "stop"}, "type": "Feature"}], "type": "FeatureCollection"}
train
https://github.com/nhfruchter/pgh-bustime/blob/b915e8fea28541612f0e79783c2cf12fd3daaac0/pghbustime/utils.py#L23-L47
null
"""Some utility functions and other stuff.""" def queryjoin(argdict=dict(), **kwargs): """Turn a dictionary into a querystring for a URL. >>> args = dict(a=1, b=2, c="foo") >>> queryjoin(args) "a=1&b=2&c=foo" """ if kwargs: argdict.update(kwargs) if issubclass(type(argdict), dict): args = ["{}={}".format(k, v) for k, v in argdict.items() if v != None] return "&".join(args) def listlike(obj): """Is an object iterable like a list (and not a string)?""" return hasattr(obj, "__iter__") \ and not issubclass(type(obj), str)\ and not issubclass(type(obj), unicode) def patterntogeojson(pattern, color=False): import geojson """ Turns an an API response of a pattern into a GeoJSON FeatureCollection. Takes a dict that contains at least `pid`, `ln`, `rtdir`, and `pt`. >>> api_response = {'ln': '123.45', 'pid': '1', 'pt': [], 'rtdir': 'OUTBOUND'} >>> pt1 = {'lat': '40.449', 'lon': '-79.983', 'seq': '1', 'typ': 'W'} >>> pt2 = {'stpid': '1', 'seq': '2', 'stpnm': '3142 Test Ave FS', 'lon': '-79.984', 'pdist': '42.4', 'lat': '40.450', 'typ': 'S'} >>> api_response['pt'] = [pt1, pt2] >>> patterntogeojson(api_response) # doctest: +ELLIPSIS {"features": [{"geometry": {"coordinates": ... "name": "3142 Test Ave FS", "type": "stop"}, "type": "Feature"}], "type": "FeatureCollection"} """ # Base properties for the pattern properties = dict( pid = pattern['pid'], length = pattern['ln'], direction = pattern['rtdir'], color = color or "" ) points = [(float(point.get('lon')), float(point.get('lat'))) for point in pattern['pt']] return geojson.LineString(coordinates=points, properties=properties)
nhfruchter/pgh-bustime
pghbustime/interface.py
BustimeAPI.endpoint
python
def endpoint(self, endpt, argdict=None): instanceargs = "{}&{}".format(queryjoin(key=self.key), queryjoin(self.args)) if argdict: localargs = queryjoin(argdict) querystring = "{}&{}".format(instanceargs, localargs) else: querystring = instanceargs return "{}?{}".format(self.ENDPOINTS[endpt], querystring)
Construct API endpoint URLs using instance options in `self.args` and local arguments passed to the function as a dictionary `argdict`. >>> api = BustimeAPI("BOGUSAPIKEY") >>> api.endpoint('VEHICLES') 'http://realtime.portauthority.org/bustime/api/v1/getvehicles?key=BOGUSAPIKEY&tmres=s&localestring=en_US' >>> api.endpoint('PREDICTION', dict(stpid=4123, rt="61C")) 'http://realtime.portauthority.org/bustime/api/v1/getpredictions?key=BOGUSAPIKEY&tmres=s&localestring=en_US&format=json&rt=61C&stpid=4123'
train
https://github.com/nhfruchter/pgh-bustime/blob/b915e8fea28541612f0e79783c2cf12fd3daaac0/pghbustime/interface.py#L64-L82
null
class BustimeAPI(object): """ A `requests` wrapper around the Port Authority's bustime API with some basic error handling and some useful conversions (like an option to convert all responses from JSON to XML.) This attempts to stay relatively close to the actual API's format with a few post-processing liberties taken to make things more Python friendly. Requires: `api_key` Optional: `locale` (defaults to en_US) `_format` (defaults to `json`, can be `xml`), `tmres` (time resolution, defaults to `s`) `cache` (cache non-dynamic information, defaults to False; currently caches stops, routes) Implements: `bulletins`, `geopatterns`, `predictions`, `route_directions`, `routes`, `stops`, `systemtime`, `vehicles If you have an API key: >>> bus = PAACBustime(my_api_key) Official API documentation can be found at the Port Authority site: http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=documentation.jsp """ __api_version__ = 'v1' ENDPOINTS = dict( SYSTIME = "http://realtime.portauthority.org/bustime/api/v1/gettime", VEHICLES = "http://realtime.portauthority.org/bustime/api/v1/getvehicles", ROUTES = "http://realtime.portauthority.org/bustime/api/v1/getroutes", R_DIRECTIONS = "http://realtime.portauthority.org/bustime/api/v1/getdirections", STOPS = "http://realtime.portauthority.org/bustime/api/v1/getstops", R_GEO = "http://realtime.portauthority.org/bustime/api/v1/getpatterns", PREDICTION = "http://realtime.portauthority.org/bustime/api/v1/getpredictions", BULLETINS = "http://realtime.portauthority.org/bustime/api/v1/getservicebulletins" ) RESPONSE_TOKEN = "bustime-response" ERROR_TOKEN = "error" STRPTIME = "%Y%m%d %H:%M:%S" def __init__(self, apikey, locale="en_US", _format="json", tmres="s"): self.key = apikey self.format = _format self.args = dict( localestring = locale, tmres = tmres ) def endpoint(self, endpt, argdict=None): """ Construct API endpoint URLs using instance options in `self.args` and local arguments passed to the function as a dictionary `argdict`. >>> api = BustimeAPI("BOGUSAPIKEY") >>> api.endpoint('VEHICLES') 'http://realtime.portauthority.org/bustime/api/v1/getvehicles?key=BOGUSAPIKEY&tmres=s&localestring=en_US' >>> api.endpoint('PREDICTION', dict(stpid=4123, rt="61C")) 'http://realtime.portauthority.org/bustime/api/v1/getpredictions?key=BOGUSAPIKEY&tmres=s&localestring=en_US&format=json&rt=61C&stpid=4123' """ instanceargs = "{}&{}".format(queryjoin(key=self.key), queryjoin(self.args)) if argdict: localargs = queryjoin(argdict) querystring = "{}&{}".format(instanceargs, localargs) else: querystring = instanceargs return "{}?{}".format(self.ENDPOINTS[endpt], querystring) def response(self, url): """Grab an API response.""" resp = requests.get(url).content return self.parseresponse(resp) def errorhandle(self, resp): """Parse API error responses and raise appropriate exceptions.""" if self.format == 'json': parsed = xmltodict.parse(resp) errors = parsed[self.RESPONSE_TOKEN][self.ERROR_TOKEN] # Create list of errors if more than one error response is given if type(errors) is list and len(errors) > 1: messages = ", ".join([" ".join(["{}: {}".format(k,v) for k, v in e.items()]) for e in errors]) else: overlimit = any('transaction limit' in msg.lower() for msg in errors.values()) if overlimit: raise APILimitExceeded("This API key has used up its daily quota of calls.") else: messages = " ".join(["{}: {}".format(k,v) for k, v in errors.items()]) elif self.format == 'xml': import xml.etree.ElementTree as ET errors = ET.fromstring(resp).findall(self.ERROR_TOKEN) messages = ", ".join(err.find('msg').text for err in errors) else: raise ValueError("Invalid API response format specified: {}." % self.format) raise BustimeError("API returned: {}".format(messages)) def parseresponse(self, resp): """Parse an API response.""" # Support Python 3's bytes type from socket repsonses if sys.version_info.major > 2: resp = resp.decode('utf-8') if self.RESPONSE_TOKEN not in resp: raise BustimeError("The Bustime API returned an invalid response: {}".format(resp)) elif self.ERROR_TOKEN in resp: return self.errorhandle(resp) else: if self.format == 'json': return xmltodict.parse(resp)[self.RESPONSE_TOKEN] elif self.format == 'xml': return resp def systemtime(self): """ Get the API's official time (local, eastern). Arguments: none. Response: `tm`: "Date and time is represented in the following format: YYYYMMDD HH:MM:SS." http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=time.jsp """ return self.response(self.endpoint('SYSTIME')) def vehicles(self, vid=None, rt=None): """ Get busses by route or by vehicle ID. Arguments: either `vid`: "Set of one or more vehicle IDs whose location should be returned." Maximum of 10 `vid`s, either in a comma-separated list or an iterable. `rt`: "Set of one or more route designators for which matching vehicles should be returned." Maximum of 10 routes, either in a comma-separated list or an iterable. Response: `vehicle`: (vehicle container) contains list of `vid`: bus # `tmstmp`: local date/time of vehicle update `lat`, `lon`: position `hdg`: vehicle heading (e.g., 0: north, 180: south) `pid`: pattern ID of current trip (see `self.geopatterns`) `pdist`: distance into trip `rt`: route (e.g, 88) `des`: bus destinations (e.g., "Penn to Bakery Square") `dly` (optional): True if bus is delayed `spd`: speed in mph `zone`: current zone (usually `None` here) `tablockid`, `tatripid`: unsure, seems internal? http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=vehicles.jsp """ if vid and rt: raise ValueError("The `vid` and `route` parameters cannot be specified simultaneously.") if not (vid or rt): raise ValueError("You must specify either the `vid` or `rt` parameter.") # Turn list into comma separated string if listlike(rt): rt = ",".join( map(str, rt) ) if listlike(vid): vid = ",".join( map(str, vid) ) url = self.endpoint('VEHICLES', dict(vid=vid, rt=rt)) return self.response(url) def routes(self): """ Return a list of routes currently tracked by the API. Arguments: none Response: `route`: (route container) contains list of `rt`: route designator (e.g, P1, 88) `rtnm`: route name (e.g. EAST BUSWAY-ALL STOPS, PENN) `rtclr`: color of route used in map display (e.g. #9900ff), usually unimportant http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=routes.jsp """ return self.response(self.endpoint('ROUTES')) def route_directions(self, rt): """ Return a list of directions for a route. The directions seem to always be INBOUND and OUTBOUND for the busses currently, where INBOUND is towards downtown and OUTBOUND is away from downtown. (No idea if this is going to change.) Arguments: `rt`: route designator Response: list of `dir`: directions served (e.g., INBOUND, OUTBOUND) http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=routeDirections.jsp """ url = self.endpoint('R_DIRECTIONS', dict(rt=rt)) return self.response(url) def stops(self, rt, direction): """ Return a list of stops for a particular route. Arguments: `rt`: route designator `dir`: route direction (INBOUND, OUTBOUND) Response: `stop`: (stop container) contains list of `stpid`: unique ID number for bus stop `stpnm`: stop name (what shows up on the display in the bus, e.g., "Forbes and Murray") `lat`, `lng`: location of stop http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=stops.jsp """ url = self.endpoint('STOPS', dict(rt=rt, dir=direction)) return self.response(url) def geopatterns(self, rt=None, pid=None): """ Returns a set of geographic points that make up a particular routing ('pattern', in API terminology) for a bus route. A bus route can have more than one routing. Arguments: either `rt`: route designator or `pid`: comma-separated list or an iterable of pattern IDs (max 10) Response: `ptr`: (pattern container) contains list of `pid`: pattern ID `ln`: length of pattern in feet `rtdir`: route direction (see `self.route_directions`) `pt`: geo points, contains list of `seq`: position of point in pattern `typ`: 'S' = stop, 'W' = waypoint -> if `typ` is a stop, will contain: `stpid`, `stpnm`, `pdist` (see `self.stops`) `lat`, `lon`: position of point http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=patterns.jsp """ if rt and pid: raise ValueError("The `rt` and `pid` parameters cannot be specified simultaneously.") if not (rt or pid): ValueError("You must specify either the `rt` or `pid` parameter.") if listlike(pid): pid = ",".join(pid) url = self.endpoint("R_GEO", dict(rt=rt, pid=pid)) return self._lru_geopatterns(url) def _lru_geopatterns(self, url): # @lru_cache doesn't support kwargs so this is a bit of a workaround... return self.response(url) def predictions(self, stpid="", rt="", vid="", maxpredictions=""): """ Retrieve predictions for 1+ stops or 1+ vehicles. Arguments: `stpid`: unique ID number for bus stop (single or comma-seperated list or iterable) or `vid`: vehicle ID number (single or comma-seperated list or iterable) or `stpid` and `rt` `maxpredictions` (optional): limit number of predictions returned Response: `prd`: (prediction container) contains list of `tmstp`: when prediction was generated `typ`: prediction type ('A' = arrival, 'D' = departure) `stpid`: stop ID for prediction `stpnm`: stop name for prediction `vid`: vehicle ID for prediction `dstp`: vehicle distance to stop (feet) `rt`: bus route `des`: bus destination `prdtm`: ETA/ETD `dly`: True if bus delayed `tablockid`, `tatripid`, `zone`: internal, see `self.vehicles` http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=predictions.jsp """ if (stpid and vid) or (rt and vid): raise ValueError("These parameters cannot be specified simultaneously.") elif not (stpid or rt or vid): raise ValueError("You must specify a parameter.") if listlike(stpid): stpid = ",".join(stpid) if listlike(rt): rt = ",".join(rt) if listlike(vid): vid = ",".join(vid) if stpid or (rt and stpid) or vid: url = self.endpoint('PREDICTION', dict(rt=rt, stpid=stpid, vid=vid, top=maxpredictions)) return self.response(url) def bulletins(self, rt="", rtdir="", stpid=""): """ Return list of service alerts ('bulletins') for a route or stop. Arguments: `rt`: route designator or `stpid`: bus stop number or (`rt` and `rtdir`) or (`rt` and `rtdir` and `stpid`) Response: `sb`: (bulletin container) contains list of `nm`: bulletin name/ID `sbj`: bulletin subject `dtl`: full text and/or `brf`: short text `prty`: priority (high, medium, low) `srvc`: (routes bulletin applies to) contains list of `rt`: route designator `rtdir`: route direction `stpid`: bus stop ID number `stpnm`: bus stop name http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=serviceBulletins.jsp """ if not (rt or stpid) or (rtdir and not (rt or stpid)): raise ValueError("You must specify a parameter.") if listlike(stpid): stpid = ",".join(stpid) if listlike(rt): rt = ",".join(rt) url = self.endpoint('BULLETINS', dict(rt=rt, rtdir=rtdir, stpid=stpid)) return self.response(url) def detournotices(self, rt): from BeautifulSoup import BeautifulSoup from datetime import datetime URL = "http://www.portauthority.org/paac/apps/detoursdnn/pgDetours.asp?mode=results&s=Route&Type=Detour" _strptime = "%m/%d/%Y" rt = str(rt) formdata = { "txtRoute": "0"*(4-len(rt)) + rt, "submit1": "Search" } data = requests.post(URL, data=formdata) if "No Detours are running" in data.content: return False else: detours = [] parser = BeautifulSoup(data.content) titles = parser.findAll('td', attrs={'colspan': '2'})[0:-1] dates = parser.findAll('td', attrs={'colspan': '1', 'class': 'RegularFormText'}) notices = zip(titles, dates) for rawTitle, rawDates in notices: title = rawTitle.p.a.text memoID = dict(rawTitle.p.a.attrs)['href'].split("MemoID=")[-1] fromDate, toDate = rawDates.p.text.replace('&nbsp;', ' ').replace('\r', '').replace('\n', '').replace('\t', '').split(' to ') try: fromDate = datetime.strptime(fromDate, _strptime) except: None try: toDate = datetime.strptime(toDate, _strptime) except: None detour = DetourNotice(memoID, title, fromDate, toDate) detours.append(detour) return detours
nhfruchter/pgh-bustime
pghbustime/interface.py
BustimeAPI.response
python
def response(self, url): resp = requests.get(url).content return self.parseresponse(resp)
Grab an API response.
train
https://github.com/nhfruchter/pgh-bustime/blob/b915e8fea28541612f0e79783c2cf12fd3daaac0/pghbustime/interface.py#L84-L88
null
class BustimeAPI(object): """ A `requests` wrapper around the Port Authority's bustime API with some basic error handling and some useful conversions (like an option to convert all responses from JSON to XML.) This attempts to stay relatively close to the actual API's format with a few post-processing liberties taken to make things more Python friendly. Requires: `api_key` Optional: `locale` (defaults to en_US) `_format` (defaults to `json`, can be `xml`), `tmres` (time resolution, defaults to `s`) `cache` (cache non-dynamic information, defaults to False; currently caches stops, routes) Implements: `bulletins`, `geopatterns`, `predictions`, `route_directions`, `routes`, `stops`, `systemtime`, `vehicles If you have an API key: >>> bus = PAACBustime(my_api_key) Official API documentation can be found at the Port Authority site: http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=documentation.jsp """ __api_version__ = 'v1' ENDPOINTS = dict( SYSTIME = "http://realtime.portauthority.org/bustime/api/v1/gettime", VEHICLES = "http://realtime.portauthority.org/bustime/api/v1/getvehicles", ROUTES = "http://realtime.portauthority.org/bustime/api/v1/getroutes", R_DIRECTIONS = "http://realtime.portauthority.org/bustime/api/v1/getdirections", STOPS = "http://realtime.portauthority.org/bustime/api/v1/getstops", R_GEO = "http://realtime.portauthority.org/bustime/api/v1/getpatterns", PREDICTION = "http://realtime.portauthority.org/bustime/api/v1/getpredictions", BULLETINS = "http://realtime.portauthority.org/bustime/api/v1/getservicebulletins" ) RESPONSE_TOKEN = "bustime-response" ERROR_TOKEN = "error" STRPTIME = "%Y%m%d %H:%M:%S" def __init__(self, apikey, locale="en_US", _format="json", tmres="s"): self.key = apikey self.format = _format self.args = dict( localestring = locale, tmres = tmres ) def endpoint(self, endpt, argdict=None): """ Construct API endpoint URLs using instance options in `self.args` and local arguments passed to the function as a dictionary `argdict`. >>> api = BustimeAPI("BOGUSAPIKEY") >>> api.endpoint('VEHICLES') 'http://realtime.portauthority.org/bustime/api/v1/getvehicles?key=BOGUSAPIKEY&tmres=s&localestring=en_US' >>> api.endpoint('PREDICTION', dict(stpid=4123, rt="61C")) 'http://realtime.portauthority.org/bustime/api/v1/getpredictions?key=BOGUSAPIKEY&tmres=s&localestring=en_US&format=json&rt=61C&stpid=4123' """ instanceargs = "{}&{}".format(queryjoin(key=self.key), queryjoin(self.args)) if argdict: localargs = queryjoin(argdict) querystring = "{}&{}".format(instanceargs, localargs) else: querystring = instanceargs return "{}?{}".format(self.ENDPOINTS[endpt], querystring) def response(self, url): """Grab an API response.""" resp = requests.get(url).content return self.parseresponse(resp) def errorhandle(self, resp): """Parse API error responses and raise appropriate exceptions.""" if self.format == 'json': parsed = xmltodict.parse(resp) errors = parsed[self.RESPONSE_TOKEN][self.ERROR_TOKEN] # Create list of errors if more than one error response is given if type(errors) is list and len(errors) > 1: messages = ", ".join([" ".join(["{}: {}".format(k,v) for k, v in e.items()]) for e in errors]) else: overlimit = any('transaction limit' in msg.lower() for msg in errors.values()) if overlimit: raise APILimitExceeded("This API key has used up its daily quota of calls.") else: messages = " ".join(["{}: {}".format(k,v) for k, v in errors.items()]) elif self.format == 'xml': import xml.etree.ElementTree as ET errors = ET.fromstring(resp).findall(self.ERROR_TOKEN) messages = ", ".join(err.find('msg').text for err in errors) else: raise ValueError("Invalid API response format specified: {}." % self.format) raise BustimeError("API returned: {}".format(messages)) def parseresponse(self, resp): """Parse an API response.""" # Support Python 3's bytes type from socket repsonses if sys.version_info.major > 2: resp = resp.decode('utf-8') if self.RESPONSE_TOKEN not in resp: raise BustimeError("The Bustime API returned an invalid response: {}".format(resp)) elif self.ERROR_TOKEN in resp: return self.errorhandle(resp) else: if self.format == 'json': return xmltodict.parse(resp)[self.RESPONSE_TOKEN] elif self.format == 'xml': return resp def systemtime(self): """ Get the API's official time (local, eastern). Arguments: none. Response: `tm`: "Date and time is represented in the following format: YYYYMMDD HH:MM:SS." http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=time.jsp """ return self.response(self.endpoint('SYSTIME')) def vehicles(self, vid=None, rt=None): """ Get busses by route or by vehicle ID. Arguments: either `vid`: "Set of one or more vehicle IDs whose location should be returned." Maximum of 10 `vid`s, either in a comma-separated list or an iterable. `rt`: "Set of one or more route designators for which matching vehicles should be returned." Maximum of 10 routes, either in a comma-separated list or an iterable. Response: `vehicle`: (vehicle container) contains list of `vid`: bus # `tmstmp`: local date/time of vehicle update `lat`, `lon`: position `hdg`: vehicle heading (e.g., 0: north, 180: south) `pid`: pattern ID of current trip (see `self.geopatterns`) `pdist`: distance into trip `rt`: route (e.g, 88) `des`: bus destinations (e.g., "Penn to Bakery Square") `dly` (optional): True if bus is delayed `spd`: speed in mph `zone`: current zone (usually `None` here) `tablockid`, `tatripid`: unsure, seems internal? http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=vehicles.jsp """ if vid and rt: raise ValueError("The `vid` and `route` parameters cannot be specified simultaneously.") if not (vid or rt): raise ValueError("You must specify either the `vid` or `rt` parameter.") # Turn list into comma separated string if listlike(rt): rt = ",".join( map(str, rt) ) if listlike(vid): vid = ",".join( map(str, vid) ) url = self.endpoint('VEHICLES', dict(vid=vid, rt=rt)) return self.response(url) def routes(self): """ Return a list of routes currently tracked by the API. Arguments: none Response: `route`: (route container) contains list of `rt`: route designator (e.g, P1, 88) `rtnm`: route name (e.g. EAST BUSWAY-ALL STOPS, PENN) `rtclr`: color of route used in map display (e.g. #9900ff), usually unimportant http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=routes.jsp """ return self.response(self.endpoint('ROUTES')) def route_directions(self, rt): """ Return a list of directions for a route. The directions seem to always be INBOUND and OUTBOUND for the busses currently, where INBOUND is towards downtown and OUTBOUND is away from downtown. (No idea if this is going to change.) Arguments: `rt`: route designator Response: list of `dir`: directions served (e.g., INBOUND, OUTBOUND) http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=routeDirections.jsp """ url = self.endpoint('R_DIRECTIONS', dict(rt=rt)) return self.response(url) def stops(self, rt, direction): """ Return a list of stops for a particular route. Arguments: `rt`: route designator `dir`: route direction (INBOUND, OUTBOUND) Response: `stop`: (stop container) contains list of `stpid`: unique ID number for bus stop `stpnm`: stop name (what shows up on the display in the bus, e.g., "Forbes and Murray") `lat`, `lng`: location of stop http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=stops.jsp """ url = self.endpoint('STOPS', dict(rt=rt, dir=direction)) return self.response(url) def geopatterns(self, rt=None, pid=None): """ Returns a set of geographic points that make up a particular routing ('pattern', in API terminology) for a bus route. A bus route can have more than one routing. Arguments: either `rt`: route designator or `pid`: comma-separated list or an iterable of pattern IDs (max 10) Response: `ptr`: (pattern container) contains list of `pid`: pattern ID `ln`: length of pattern in feet `rtdir`: route direction (see `self.route_directions`) `pt`: geo points, contains list of `seq`: position of point in pattern `typ`: 'S' = stop, 'W' = waypoint -> if `typ` is a stop, will contain: `stpid`, `stpnm`, `pdist` (see `self.stops`) `lat`, `lon`: position of point http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=patterns.jsp """ if rt and pid: raise ValueError("The `rt` and `pid` parameters cannot be specified simultaneously.") if not (rt or pid): ValueError("You must specify either the `rt` or `pid` parameter.") if listlike(pid): pid = ",".join(pid) url = self.endpoint("R_GEO", dict(rt=rt, pid=pid)) return self._lru_geopatterns(url) def _lru_geopatterns(self, url): # @lru_cache doesn't support kwargs so this is a bit of a workaround... return self.response(url) def predictions(self, stpid="", rt="", vid="", maxpredictions=""): """ Retrieve predictions for 1+ stops or 1+ vehicles. Arguments: `stpid`: unique ID number for bus stop (single or comma-seperated list or iterable) or `vid`: vehicle ID number (single or comma-seperated list or iterable) or `stpid` and `rt` `maxpredictions` (optional): limit number of predictions returned Response: `prd`: (prediction container) contains list of `tmstp`: when prediction was generated `typ`: prediction type ('A' = arrival, 'D' = departure) `stpid`: stop ID for prediction `stpnm`: stop name for prediction `vid`: vehicle ID for prediction `dstp`: vehicle distance to stop (feet) `rt`: bus route `des`: bus destination `prdtm`: ETA/ETD `dly`: True if bus delayed `tablockid`, `tatripid`, `zone`: internal, see `self.vehicles` http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=predictions.jsp """ if (stpid and vid) or (rt and vid): raise ValueError("These parameters cannot be specified simultaneously.") elif not (stpid or rt or vid): raise ValueError("You must specify a parameter.") if listlike(stpid): stpid = ",".join(stpid) if listlike(rt): rt = ",".join(rt) if listlike(vid): vid = ",".join(vid) if stpid or (rt and stpid) or vid: url = self.endpoint('PREDICTION', dict(rt=rt, stpid=stpid, vid=vid, top=maxpredictions)) return self.response(url) def bulletins(self, rt="", rtdir="", stpid=""): """ Return list of service alerts ('bulletins') for a route or stop. Arguments: `rt`: route designator or `stpid`: bus stop number or (`rt` and `rtdir`) or (`rt` and `rtdir` and `stpid`) Response: `sb`: (bulletin container) contains list of `nm`: bulletin name/ID `sbj`: bulletin subject `dtl`: full text and/or `brf`: short text `prty`: priority (high, medium, low) `srvc`: (routes bulletin applies to) contains list of `rt`: route designator `rtdir`: route direction `stpid`: bus stop ID number `stpnm`: bus stop name http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=serviceBulletins.jsp """ if not (rt or stpid) or (rtdir and not (rt or stpid)): raise ValueError("You must specify a parameter.") if listlike(stpid): stpid = ",".join(stpid) if listlike(rt): rt = ",".join(rt) url = self.endpoint('BULLETINS', dict(rt=rt, rtdir=rtdir, stpid=stpid)) return self.response(url) def detournotices(self, rt): from BeautifulSoup import BeautifulSoup from datetime import datetime URL = "http://www.portauthority.org/paac/apps/detoursdnn/pgDetours.asp?mode=results&s=Route&Type=Detour" _strptime = "%m/%d/%Y" rt = str(rt) formdata = { "txtRoute": "0"*(4-len(rt)) + rt, "submit1": "Search" } data = requests.post(URL, data=formdata) if "No Detours are running" in data.content: return False else: detours = [] parser = BeautifulSoup(data.content) titles = parser.findAll('td', attrs={'colspan': '2'})[0:-1] dates = parser.findAll('td', attrs={'colspan': '1', 'class': 'RegularFormText'}) notices = zip(titles, dates) for rawTitle, rawDates in notices: title = rawTitle.p.a.text memoID = dict(rawTitle.p.a.attrs)['href'].split("MemoID=")[-1] fromDate, toDate = rawDates.p.text.replace('&nbsp;', ' ').replace('\r', '').replace('\n', '').replace('\t', '').split(' to ') try: fromDate = datetime.strptime(fromDate, _strptime) except: None try: toDate = datetime.strptime(toDate, _strptime) except: None detour = DetourNotice(memoID, title, fromDate, toDate) detours.append(detour) return detours
nhfruchter/pgh-bustime
pghbustime/interface.py
BustimeAPI.errorhandle
python
def errorhandle(self, resp): if self.format == 'json': parsed = xmltodict.parse(resp) errors = parsed[self.RESPONSE_TOKEN][self.ERROR_TOKEN] # Create list of errors if more than one error response is given if type(errors) is list and len(errors) > 1: messages = ", ".join([" ".join(["{}: {}".format(k,v) for k, v in e.items()]) for e in errors]) else: overlimit = any('transaction limit' in msg.lower() for msg in errors.values()) if overlimit: raise APILimitExceeded("This API key has used up its daily quota of calls.") else: messages = " ".join(["{}: {}".format(k,v) for k, v in errors.items()]) elif self.format == 'xml': import xml.etree.ElementTree as ET errors = ET.fromstring(resp).findall(self.ERROR_TOKEN) messages = ", ".join(err.find('msg').text for err in errors) else: raise ValueError("Invalid API response format specified: {}." % self.format) raise BustimeError("API returned: {}".format(messages))
Parse API error responses and raise appropriate exceptions.
train
https://github.com/nhfruchter/pgh-bustime/blob/b915e8fea28541612f0e79783c2cf12fd3daaac0/pghbustime/interface.py#L90-L111
null
class BustimeAPI(object): """ A `requests` wrapper around the Port Authority's bustime API with some basic error handling and some useful conversions (like an option to convert all responses from JSON to XML.) This attempts to stay relatively close to the actual API's format with a few post-processing liberties taken to make things more Python friendly. Requires: `api_key` Optional: `locale` (defaults to en_US) `_format` (defaults to `json`, can be `xml`), `tmres` (time resolution, defaults to `s`) `cache` (cache non-dynamic information, defaults to False; currently caches stops, routes) Implements: `bulletins`, `geopatterns`, `predictions`, `route_directions`, `routes`, `stops`, `systemtime`, `vehicles If you have an API key: >>> bus = PAACBustime(my_api_key) Official API documentation can be found at the Port Authority site: http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=documentation.jsp """ __api_version__ = 'v1' ENDPOINTS = dict( SYSTIME = "http://realtime.portauthority.org/bustime/api/v1/gettime", VEHICLES = "http://realtime.portauthority.org/bustime/api/v1/getvehicles", ROUTES = "http://realtime.portauthority.org/bustime/api/v1/getroutes", R_DIRECTIONS = "http://realtime.portauthority.org/bustime/api/v1/getdirections", STOPS = "http://realtime.portauthority.org/bustime/api/v1/getstops", R_GEO = "http://realtime.portauthority.org/bustime/api/v1/getpatterns", PREDICTION = "http://realtime.portauthority.org/bustime/api/v1/getpredictions", BULLETINS = "http://realtime.portauthority.org/bustime/api/v1/getservicebulletins" ) RESPONSE_TOKEN = "bustime-response" ERROR_TOKEN = "error" STRPTIME = "%Y%m%d %H:%M:%S" def __init__(self, apikey, locale="en_US", _format="json", tmres="s"): self.key = apikey self.format = _format self.args = dict( localestring = locale, tmres = tmres ) def endpoint(self, endpt, argdict=None): """ Construct API endpoint URLs using instance options in `self.args` and local arguments passed to the function as a dictionary `argdict`. >>> api = BustimeAPI("BOGUSAPIKEY") >>> api.endpoint('VEHICLES') 'http://realtime.portauthority.org/bustime/api/v1/getvehicles?key=BOGUSAPIKEY&tmres=s&localestring=en_US' >>> api.endpoint('PREDICTION', dict(stpid=4123, rt="61C")) 'http://realtime.portauthority.org/bustime/api/v1/getpredictions?key=BOGUSAPIKEY&tmres=s&localestring=en_US&format=json&rt=61C&stpid=4123' """ instanceargs = "{}&{}".format(queryjoin(key=self.key), queryjoin(self.args)) if argdict: localargs = queryjoin(argdict) querystring = "{}&{}".format(instanceargs, localargs) else: querystring = instanceargs return "{}?{}".format(self.ENDPOINTS[endpt], querystring) def response(self, url): """Grab an API response.""" resp = requests.get(url).content return self.parseresponse(resp) def errorhandle(self, resp): """Parse API error responses and raise appropriate exceptions.""" if self.format == 'json': parsed = xmltodict.parse(resp) errors = parsed[self.RESPONSE_TOKEN][self.ERROR_TOKEN] # Create list of errors if more than one error response is given if type(errors) is list and len(errors) > 1: messages = ", ".join([" ".join(["{}: {}".format(k,v) for k, v in e.items()]) for e in errors]) else: overlimit = any('transaction limit' in msg.lower() for msg in errors.values()) if overlimit: raise APILimitExceeded("This API key has used up its daily quota of calls.") else: messages = " ".join(["{}: {}".format(k,v) for k, v in errors.items()]) elif self.format == 'xml': import xml.etree.ElementTree as ET errors = ET.fromstring(resp).findall(self.ERROR_TOKEN) messages = ", ".join(err.find('msg').text for err in errors) else: raise ValueError("Invalid API response format specified: {}." % self.format) raise BustimeError("API returned: {}".format(messages)) def parseresponse(self, resp): """Parse an API response.""" # Support Python 3's bytes type from socket repsonses if sys.version_info.major > 2: resp = resp.decode('utf-8') if self.RESPONSE_TOKEN not in resp: raise BustimeError("The Bustime API returned an invalid response: {}".format(resp)) elif self.ERROR_TOKEN in resp: return self.errorhandle(resp) else: if self.format == 'json': return xmltodict.parse(resp)[self.RESPONSE_TOKEN] elif self.format == 'xml': return resp def systemtime(self): """ Get the API's official time (local, eastern). Arguments: none. Response: `tm`: "Date and time is represented in the following format: YYYYMMDD HH:MM:SS." http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=time.jsp """ return self.response(self.endpoint('SYSTIME')) def vehicles(self, vid=None, rt=None): """ Get busses by route or by vehicle ID. Arguments: either `vid`: "Set of one or more vehicle IDs whose location should be returned." Maximum of 10 `vid`s, either in a comma-separated list or an iterable. `rt`: "Set of one or more route designators for which matching vehicles should be returned." Maximum of 10 routes, either in a comma-separated list or an iterable. Response: `vehicle`: (vehicle container) contains list of `vid`: bus # `tmstmp`: local date/time of vehicle update `lat`, `lon`: position `hdg`: vehicle heading (e.g., 0: north, 180: south) `pid`: pattern ID of current trip (see `self.geopatterns`) `pdist`: distance into trip `rt`: route (e.g, 88) `des`: bus destinations (e.g., "Penn to Bakery Square") `dly` (optional): True if bus is delayed `spd`: speed in mph `zone`: current zone (usually `None` here) `tablockid`, `tatripid`: unsure, seems internal? http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=vehicles.jsp """ if vid and rt: raise ValueError("The `vid` and `route` parameters cannot be specified simultaneously.") if not (vid or rt): raise ValueError("You must specify either the `vid` or `rt` parameter.") # Turn list into comma separated string if listlike(rt): rt = ",".join( map(str, rt) ) if listlike(vid): vid = ",".join( map(str, vid) ) url = self.endpoint('VEHICLES', dict(vid=vid, rt=rt)) return self.response(url) def routes(self): """ Return a list of routes currently tracked by the API. Arguments: none Response: `route`: (route container) contains list of `rt`: route designator (e.g, P1, 88) `rtnm`: route name (e.g. EAST BUSWAY-ALL STOPS, PENN) `rtclr`: color of route used in map display (e.g. #9900ff), usually unimportant http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=routes.jsp """ return self.response(self.endpoint('ROUTES')) def route_directions(self, rt): """ Return a list of directions for a route. The directions seem to always be INBOUND and OUTBOUND for the busses currently, where INBOUND is towards downtown and OUTBOUND is away from downtown. (No idea if this is going to change.) Arguments: `rt`: route designator Response: list of `dir`: directions served (e.g., INBOUND, OUTBOUND) http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=routeDirections.jsp """ url = self.endpoint('R_DIRECTIONS', dict(rt=rt)) return self.response(url) def stops(self, rt, direction): """ Return a list of stops for a particular route. Arguments: `rt`: route designator `dir`: route direction (INBOUND, OUTBOUND) Response: `stop`: (stop container) contains list of `stpid`: unique ID number for bus stop `stpnm`: stop name (what shows up on the display in the bus, e.g., "Forbes and Murray") `lat`, `lng`: location of stop http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=stops.jsp """ url = self.endpoint('STOPS', dict(rt=rt, dir=direction)) return self.response(url) def geopatterns(self, rt=None, pid=None): """ Returns a set of geographic points that make up a particular routing ('pattern', in API terminology) for a bus route. A bus route can have more than one routing. Arguments: either `rt`: route designator or `pid`: comma-separated list or an iterable of pattern IDs (max 10) Response: `ptr`: (pattern container) contains list of `pid`: pattern ID `ln`: length of pattern in feet `rtdir`: route direction (see `self.route_directions`) `pt`: geo points, contains list of `seq`: position of point in pattern `typ`: 'S' = stop, 'W' = waypoint -> if `typ` is a stop, will contain: `stpid`, `stpnm`, `pdist` (see `self.stops`) `lat`, `lon`: position of point http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=patterns.jsp """ if rt and pid: raise ValueError("The `rt` and `pid` parameters cannot be specified simultaneously.") if not (rt or pid): ValueError("You must specify either the `rt` or `pid` parameter.") if listlike(pid): pid = ",".join(pid) url = self.endpoint("R_GEO", dict(rt=rt, pid=pid)) return self._lru_geopatterns(url) def _lru_geopatterns(self, url): # @lru_cache doesn't support kwargs so this is a bit of a workaround... return self.response(url) def predictions(self, stpid="", rt="", vid="", maxpredictions=""): """ Retrieve predictions for 1+ stops or 1+ vehicles. Arguments: `stpid`: unique ID number for bus stop (single or comma-seperated list or iterable) or `vid`: vehicle ID number (single or comma-seperated list or iterable) or `stpid` and `rt` `maxpredictions` (optional): limit number of predictions returned Response: `prd`: (prediction container) contains list of `tmstp`: when prediction was generated `typ`: prediction type ('A' = arrival, 'D' = departure) `stpid`: stop ID for prediction `stpnm`: stop name for prediction `vid`: vehicle ID for prediction `dstp`: vehicle distance to stop (feet) `rt`: bus route `des`: bus destination `prdtm`: ETA/ETD `dly`: True if bus delayed `tablockid`, `tatripid`, `zone`: internal, see `self.vehicles` http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=predictions.jsp """ if (stpid and vid) or (rt and vid): raise ValueError("These parameters cannot be specified simultaneously.") elif not (stpid or rt or vid): raise ValueError("You must specify a parameter.") if listlike(stpid): stpid = ",".join(stpid) if listlike(rt): rt = ",".join(rt) if listlike(vid): vid = ",".join(vid) if stpid or (rt and stpid) or vid: url = self.endpoint('PREDICTION', dict(rt=rt, stpid=stpid, vid=vid, top=maxpredictions)) return self.response(url) def bulletins(self, rt="", rtdir="", stpid=""): """ Return list of service alerts ('bulletins') for a route or stop. Arguments: `rt`: route designator or `stpid`: bus stop number or (`rt` and `rtdir`) or (`rt` and `rtdir` and `stpid`) Response: `sb`: (bulletin container) contains list of `nm`: bulletin name/ID `sbj`: bulletin subject `dtl`: full text and/or `brf`: short text `prty`: priority (high, medium, low) `srvc`: (routes bulletin applies to) contains list of `rt`: route designator `rtdir`: route direction `stpid`: bus stop ID number `stpnm`: bus stop name http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=serviceBulletins.jsp """ if not (rt or stpid) or (rtdir and not (rt or stpid)): raise ValueError("You must specify a parameter.") if listlike(stpid): stpid = ",".join(stpid) if listlike(rt): rt = ",".join(rt) url = self.endpoint('BULLETINS', dict(rt=rt, rtdir=rtdir, stpid=stpid)) return self.response(url) def detournotices(self, rt): from BeautifulSoup import BeautifulSoup from datetime import datetime URL = "http://www.portauthority.org/paac/apps/detoursdnn/pgDetours.asp?mode=results&s=Route&Type=Detour" _strptime = "%m/%d/%Y" rt = str(rt) formdata = { "txtRoute": "0"*(4-len(rt)) + rt, "submit1": "Search" } data = requests.post(URL, data=formdata) if "No Detours are running" in data.content: return False else: detours = [] parser = BeautifulSoup(data.content) titles = parser.findAll('td', attrs={'colspan': '2'})[0:-1] dates = parser.findAll('td', attrs={'colspan': '1', 'class': 'RegularFormText'}) notices = zip(titles, dates) for rawTitle, rawDates in notices: title = rawTitle.p.a.text memoID = dict(rawTitle.p.a.attrs)['href'].split("MemoID=")[-1] fromDate, toDate = rawDates.p.text.replace('&nbsp;', ' ').replace('\r', '').replace('\n', '').replace('\t', '').split(' to ') try: fromDate = datetime.strptime(fromDate, _strptime) except: None try: toDate = datetime.strptime(toDate, _strptime) except: None detour = DetourNotice(memoID, title, fromDate, toDate) detours.append(detour) return detours
nhfruchter/pgh-bustime
pghbustime/interface.py
BustimeAPI.parseresponse
python
def parseresponse(self, resp): # Support Python 3's bytes type from socket repsonses if sys.version_info.major > 2: resp = resp.decode('utf-8') if self.RESPONSE_TOKEN not in resp: raise BustimeError("The Bustime API returned an invalid response: {}".format(resp)) elif self.ERROR_TOKEN in resp: return self.errorhandle(resp) else: if self.format == 'json': return xmltodict.parse(resp)[self.RESPONSE_TOKEN] elif self.format == 'xml': return resp
Parse an API response.
train
https://github.com/nhfruchter/pgh-bustime/blob/b915e8fea28541612f0e79783c2cf12fd3daaac0/pghbustime/interface.py#L113-L127
null
class BustimeAPI(object): """ A `requests` wrapper around the Port Authority's bustime API with some basic error handling and some useful conversions (like an option to convert all responses from JSON to XML.) This attempts to stay relatively close to the actual API's format with a few post-processing liberties taken to make things more Python friendly. Requires: `api_key` Optional: `locale` (defaults to en_US) `_format` (defaults to `json`, can be `xml`), `tmres` (time resolution, defaults to `s`) `cache` (cache non-dynamic information, defaults to False; currently caches stops, routes) Implements: `bulletins`, `geopatterns`, `predictions`, `route_directions`, `routes`, `stops`, `systemtime`, `vehicles If you have an API key: >>> bus = PAACBustime(my_api_key) Official API documentation can be found at the Port Authority site: http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=documentation.jsp """ __api_version__ = 'v1' ENDPOINTS = dict( SYSTIME = "http://realtime.portauthority.org/bustime/api/v1/gettime", VEHICLES = "http://realtime.portauthority.org/bustime/api/v1/getvehicles", ROUTES = "http://realtime.portauthority.org/bustime/api/v1/getroutes", R_DIRECTIONS = "http://realtime.portauthority.org/bustime/api/v1/getdirections", STOPS = "http://realtime.portauthority.org/bustime/api/v1/getstops", R_GEO = "http://realtime.portauthority.org/bustime/api/v1/getpatterns", PREDICTION = "http://realtime.portauthority.org/bustime/api/v1/getpredictions", BULLETINS = "http://realtime.portauthority.org/bustime/api/v1/getservicebulletins" ) RESPONSE_TOKEN = "bustime-response" ERROR_TOKEN = "error" STRPTIME = "%Y%m%d %H:%M:%S" def __init__(self, apikey, locale="en_US", _format="json", tmres="s"): self.key = apikey self.format = _format self.args = dict( localestring = locale, tmres = tmres ) def endpoint(self, endpt, argdict=None): """ Construct API endpoint URLs using instance options in `self.args` and local arguments passed to the function as a dictionary `argdict`. >>> api = BustimeAPI("BOGUSAPIKEY") >>> api.endpoint('VEHICLES') 'http://realtime.portauthority.org/bustime/api/v1/getvehicles?key=BOGUSAPIKEY&tmres=s&localestring=en_US' >>> api.endpoint('PREDICTION', dict(stpid=4123, rt="61C")) 'http://realtime.portauthority.org/bustime/api/v1/getpredictions?key=BOGUSAPIKEY&tmres=s&localestring=en_US&format=json&rt=61C&stpid=4123' """ instanceargs = "{}&{}".format(queryjoin(key=self.key), queryjoin(self.args)) if argdict: localargs = queryjoin(argdict) querystring = "{}&{}".format(instanceargs, localargs) else: querystring = instanceargs return "{}?{}".format(self.ENDPOINTS[endpt], querystring) def response(self, url): """Grab an API response.""" resp = requests.get(url).content return self.parseresponse(resp) def errorhandle(self, resp): """Parse API error responses and raise appropriate exceptions.""" if self.format == 'json': parsed = xmltodict.parse(resp) errors = parsed[self.RESPONSE_TOKEN][self.ERROR_TOKEN] # Create list of errors if more than one error response is given if type(errors) is list and len(errors) > 1: messages = ", ".join([" ".join(["{}: {}".format(k,v) for k, v in e.items()]) for e in errors]) else: overlimit = any('transaction limit' in msg.lower() for msg in errors.values()) if overlimit: raise APILimitExceeded("This API key has used up its daily quota of calls.") else: messages = " ".join(["{}: {}".format(k,v) for k, v in errors.items()]) elif self.format == 'xml': import xml.etree.ElementTree as ET errors = ET.fromstring(resp).findall(self.ERROR_TOKEN) messages = ", ".join(err.find('msg').text for err in errors) else: raise ValueError("Invalid API response format specified: {}." % self.format) raise BustimeError("API returned: {}".format(messages)) def parseresponse(self, resp): """Parse an API response.""" # Support Python 3's bytes type from socket repsonses if sys.version_info.major > 2: resp = resp.decode('utf-8') if self.RESPONSE_TOKEN not in resp: raise BustimeError("The Bustime API returned an invalid response: {}".format(resp)) elif self.ERROR_TOKEN in resp: return self.errorhandle(resp) else: if self.format == 'json': return xmltodict.parse(resp)[self.RESPONSE_TOKEN] elif self.format == 'xml': return resp def systemtime(self): """ Get the API's official time (local, eastern). Arguments: none. Response: `tm`: "Date and time is represented in the following format: YYYYMMDD HH:MM:SS." http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=time.jsp """ return self.response(self.endpoint('SYSTIME')) def vehicles(self, vid=None, rt=None): """ Get busses by route or by vehicle ID. Arguments: either `vid`: "Set of one or more vehicle IDs whose location should be returned." Maximum of 10 `vid`s, either in a comma-separated list or an iterable. `rt`: "Set of one or more route designators for which matching vehicles should be returned." Maximum of 10 routes, either in a comma-separated list or an iterable. Response: `vehicle`: (vehicle container) contains list of `vid`: bus # `tmstmp`: local date/time of vehicle update `lat`, `lon`: position `hdg`: vehicle heading (e.g., 0: north, 180: south) `pid`: pattern ID of current trip (see `self.geopatterns`) `pdist`: distance into trip `rt`: route (e.g, 88) `des`: bus destinations (e.g., "Penn to Bakery Square") `dly` (optional): True if bus is delayed `spd`: speed in mph `zone`: current zone (usually `None` here) `tablockid`, `tatripid`: unsure, seems internal? http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=vehicles.jsp """ if vid and rt: raise ValueError("The `vid` and `route` parameters cannot be specified simultaneously.") if not (vid or rt): raise ValueError("You must specify either the `vid` or `rt` parameter.") # Turn list into comma separated string if listlike(rt): rt = ",".join( map(str, rt) ) if listlike(vid): vid = ",".join( map(str, vid) ) url = self.endpoint('VEHICLES', dict(vid=vid, rt=rt)) return self.response(url) def routes(self): """ Return a list of routes currently tracked by the API. Arguments: none Response: `route`: (route container) contains list of `rt`: route designator (e.g, P1, 88) `rtnm`: route name (e.g. EAST BUSWAY-ALL STOPS, PENN) `rtclr`: color of route used in map display (e.g. #9900ff), usually unimportant http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=routes.jsp """ return self.response(self.endpoint('ROUTES')) def route_directions(self, rt): """ Return a list of directions for a route. The directions seem to always be INBOUND and OUTBOUND for the busses currently, where INBOUND is towards downtown and OUTBOUND is away from downtown. (No idea if this is going to change.) Arguments: `rt`: route designator Response: list of `dir`: directions served (e.g., INBOUND, OUTBOUND) http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=routeDirections.jsp """ url = self.endpoint('R_DIRECTIONS', dict(rt=rt)) return self.response(url) def stops(self, rt, direction): """ Return a list of stops for a particular route. Arguments: `rt`: route designator `dir`: route direction (INBOUND, OUTBOUND) Response: `stop`: (stop container) contains list of `stpid`: unique ID number for bus stop `stpnm`: stop name (what shows up on the display in the bus, e.g., "Forbes and Murray") `lat`, `lng`: location of stop http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=stops.jsp """ url = self.endpoint('STOPS', dict(rt=rt, dir=direction)) return self.response(url) def geopatterns(self, rt=None, pid=None): """ Returns a set of geographic points that make up a particular routing ('pattern', in API terminology) for a bus route. A bus route can have more than one routing. Arguments: either `rt`: route designator or `pid`: comma-separated list or an iterable of pattern IDs (max 10) Response: `ptr`: (pattern container) contains list of `pid`: pattern ID `ln`: length of pattern in feet `rtdir`: route direction (see `self.route_directions`) `pt`: geo points, contains list of `seq`: position of point in pattern `typ`: 'S' = stop, 'W' = waypoint -> if `typ` is a stop, will contain: `stpid`, `stpnm`, `pdist` (see `self.stops`) `lat`, `lon`: position of point http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=patterns.jsp """ if rt and pid: raise ValueError("The `rt` and `pid` parameters cannot be specified simultaneously.") if not (rt or pid): ValueError("You must specify either the `rt` or `pid` parameter.") if listlike(pid): pid = ",".join(pid) url = self.endpoint("R_GEO", dict(rt=rt, pid=pid)) return self._lru_geopatterns(url) def _lru_geopatterns(self, url): # @lru_cache doesn't support kwargs so this is a bit of a workaround... return self.response(url) def predictions(self, stpid="", rt="", vid="", maxpredictions=""): """ Retrieve predictions for 1+ stops or 1+ vehicles. Arguments: `stpid`: unique ID number for bus stop (single or comma-seperated list or iterable) or `vid`: vehicle ID number (single or comma-seperated list or iterable) or `stpid` and `rt` `maxpredictions` (optional): limit number of predictions returned Response: `prd`: (prediction container) contains list of `tmstp`: when prediction was generated `typ`: prediction type ('A' = arrival, 'D' = departure) `stpid`: stop ID for prediction `stpnm`: stop name for prediction `vid`: vehicle ID for prediction `dstp`: vehicle distance to stop (feet) `rt`: bus route `des`: bus destination `prdtm`: ETA/ETD `dly`: True if bus delayed `tablockid`, `tatripid`, `zone`: internal, see `self.vehicles` http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=predictions.jsp """ if (stpid and vid) or (rt and vid): raise ValueError("These parameters cannot be specified simultaneously.") elif not (stpid or rt or vid): raise ValueError("You must specify a parameter.") if listlike(stpid): stpid = ",".join(stpid) if listlike(rt): rt = ",".join(rt) if listlike(vid): vid = ",".join(vid) if stpid or (rt and stpid) or vid: url = self.endpoint('PREDICTION', dict(rt=rt, stpid=stpid, vid=vid, top=maxpredictions)) return self.response(url) def bulletins(self, rt="", rtdir="", stpid=""): """ Return list of service alerts ('bulletins') for a route or stop. Arguments: `rt`: route designator or `stpid`: bus stop number or (`rt` and `rtdir`) or (`rt` and `rtdir` and `stpid`) Response: `sb`: (bulletin container) contains list of `nm`: bulletin name/ID `sbj`: bulletin subject `dtl`: full text and/or `brf`: short text `prty`: priority (high, medium, low) `srvc`: (routes bulletin applies to) contains list of `rt`: route designator `rtdir`: route direction `stpid`: bus stop ID number `stpnm`: bus stop name http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=serviceBulletins.jsp """ if not (rt or stpid) or (rtdir and not (rt or stpid)): raise ValueError("You must specify a parameter.") if listlike(stpid): stpid = ",".join(stpid) if listlike(rt): rt = ",".join(rt) url = self.endpoint('BULLETINS', dict(rt=rt, rtdir=rtdir, stpid=stpid)) return self.response(url) def detournotices(self, rt): from BeautifulSoup import BeautifulSoup from datetime import datetime URL = "http://www.portauthority.org/paac/apps/detoursdnn/pgDetours.asp?mode=results&s=Route&Type=Detour" _strptime = "%m/%d/%Y" rt = str(rt) formdata = { "txtRoute": "0"*(4-len(rt)) + rt, "submit1": "Search" } data = requests.post(URL, data=formdata) if "No Detours are running" in data.content: return False else: detours = [] parser = BeautifulSoup(data.content) titles = parser.findAll('td', attrs={'colspan': '2'})[0:-1] dates = parser.findAll('td', attrs={'colspan': '1', 'class': 'RegularFormText'}) notices = zip(titles, dates) for rawTitle, rawDates in notices: title = rawTitle.p.a.text memoID = dict(rawTitle.p.a.attrs)['href'].split("MemoID=")[-1] fromDate, toDate = rawDates.p.text.replace('&nbsp;', ' ').replace('\r', '').replace('\n', '').replace('\t', '').split(' to ') try: fromDate = datetime.strptime(fromDate, _strptime) except: None try: toDate = datetime.strptime(toDate, _strptime) except: None detour = DetourNotice(memoID, title, fromDate, toDate) detours.append(detour) return detours
nhfruchter/pgh-bustime
pghbustime/interface.py
BustimeAPI.vehicles
python
def vehicles(self, vid=None, rt=None): if vid and rt: raise ValueError("The `vid` and `route` parameters cannot be specified simultaneously.") if not (vid or rt): raise ValueError("You must specify either the `vid` or `rt` parameter.") # Turn list into comma separated string if listlike(rt): rt = ",".join( map(str, rt) ) if listlike(vid): vid = ",".join( map(str, vid) ) url = self.endpoint('VEHICLES', dict(vid=vid, rt=rt)) return self.response(url)
Get busses by route or by vehicle ID. Arguments: either `vid`: "Set of one or more vehicle IDs whose location should be returned." Maximum of 10 `vid`s, either in a comma-separated list or an iterable. `rt`: "Set of one or more route designators for which matching vehicles should be returned." Maximum of 10 routes, either in a comma-separated list or an iterable. Response: `vehicle`: (vehicle container) contains list of `vid`: bus # `tmstmp`: local date/time of vehicle update `lat`, `lon`: position `hdg`: vehicle heading (e.g., 0: north, 180: south) `pid`: pattern ID of current trip (see `self.geopatterns`) `pdist`: distance into trip `rt`: route (e.g, 88) `des`: bus destinations (e.g., "Penn to Bakery Square") `dly` (optional): True if bus is delayed `spd`: speed in mph `zone`: current zone (usually `None` here) `tablockid`, `tatripid`: unsure, seems internal? http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=vehicles.jsp
train
https://github.com/nhfruchter/pgh-bustime/blob/b915e8fea28541612f0e79783c2cf12fd3daaac0/pghbustime/interface.py#L144-L183
null
class BustimeAPI(object): """ A `requests` wrapper around the Port Authority's bustime API with some basic error handling and some useful conversions (like an option to convert all responses from JSON to XML.) This attempts to stay relatively close to the actual API's format with a few post-processing liberties taken to make things more Python friendly. Requires: `api_key` Optional: `locale` (defaults to en_US) `_format` (defaults to `json`, can be `xml`), `tmres` (time resolution, defaults to `s`) `cache` (cache non-dynamic information, defaults to False; currently caches stops, routes) Implements: `bulletins`, `geopatterns`, `predictions`, `route_directions`, `routes`, `stops`, `systemtime`, `vehicles If you have an API key: >>> bus = PAACBustime(my_api_key) Official API documentation can be found at the Port Authority site: http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=documentation.jsp """ __api_version__ = 'v1' ENDPOINTS = dict( SYSTIME = "http://realtime.portauthority.org/bustime/api/v1/gettime", VEHICLES = "http://realtime.portauthority.org/bustime/api/v1/getvehicles", ROUTES = "http://realtime.portauthority.org/bustime/api/v1/getroutes", R_DIRECTIONS = "http://realtime.portauthority.org/bustime/api/v1/getdirections", STOPS = "http://realtime.portauthority.org/bustime/api/v1/getstops", R_GEO = "http://realtime.portauthority.org/bustime/api/v1/getpatterns", PREDICTION = "http://realtime.portauthority.org/bustime/api/v1/getpredictions", BULLETINS = "http://realtime.portauthority.org/bustime/api/v1/getservicebulletins" ) RESPONSE_TOKEN = "bustime-response" ERROR_TOKEN = "error" STRPTIME = "%Y%m%d %H:%M:%S" def __init__(self, apikey, locale="en_US", _format="json", tmres="s"): self.key = apikey self.format = _format self.args = dict( localestring = locale, tmres = tmres ) def endpoint(self, endpt, argdict=None): """ Construct API endpoint URLs using instance options in `self.args` and local arguments passed to the function as a dictionary `argdict`. >>> api = BustimeAPI("BOGUSAPIKEY") >>> api.endpoint('VEHICLES') 'http://realtime.portauthority.org/bustime/api/v1/getvehicles?key=BOGUSAPIKEY&tmres=s&localestring=en_US' >>> api.endpoint('PREDICTION', dict(stpid=4123, rt="61C")) 'http://realtime.portauthority.org/bustime/api/v1/getpredictions?key=BOGUSAPIKEY&tmres=s&localestring=en_US&format=json&rt=61C&stpid=4123' """ instanceargs = "{}&{}".format(queryjoin(key=self.key), queryjoin(self.args)) if argdict: localargs = queryjoin(argdict) querystring = "{}&{}".format(instanceargs, localargs) else: querystring = instanceargs return "{}?{}".format(self.ENDPOINTS[endpt], querystring) def response(self, url): """Grab an API response.""" resp = requests.get(url).content return self.parseresponse(resp) def errorhandle(self, resp): """Parse API error responses and raise appropriate exceptions.""" if self.format == 'json': parsed = xmltodict.parse(resp) errors = parsed[self.RESPONSE_TOKEN][self.ERROR_TOKEN] # Create list of errors if more than one error response is given if type(errors) is list and len(errors) > 1: messages = ", ".join([" ".join(["{}: {}".format(k,v) for k, v in e.items()]) for e in errors]) else: overlimit = any('transaction limit' in msg.lower() for msg in errors.values()) if overlimit: raise APILimitExceeded("This API key has used up its daily quota of calls.") else: messages = " ".join(["{}: {}".format(k,v) for k, v in errors.items()]) elif self.format == 'xml': import xml.etree.ElementTree as ET errors = ET.fromstring(resp).findall(self.ERROR_TOKEN) messages = ", ".join(err.find('msg').text for err in errors) else: raise ValueError("Invalid API response format specified: {}." % self.format) raise BustimeError("API returned: {}".format(messages)) def parseresponse(self, resp): """Parse an API response.""" # Support Python 3's bytes type from socket repsonses if sys.version_info.major > 2: resp = resp.decode('utf-8') if self.RESPONSE_TOKEN not in resp: raise BustimeError("The Bustime API returned an invalid response: {}".format(resp)) elif self.ERROR_TOKEN in resp: return self.errorhandle(resp) else: if self.format == 'json': return xmltodict.parse(resp)[self.RESPONSE_TOKEN] elif self.format == 'xml': return resp def systemtime(self): """ Get the API's official time (local, eastern). Arguments: none. Response: `tm`: "Date and time is represented in the following format: YYYYMMDD HH:MM:SS." http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=time.jsp """ return self.response(self.endpoint('SYSTIME')) def vehicles(self, vid=None, rt=None): """ Get busses by route or by vehicle ID. Arguments: either `vid`: "Set of one or more vehicle IDs whose location should be returned." Maximum of 10 `vid`s, either in a comma-separated list or an iterable. `rt`: "Set of one or more route designators for which matching vehicles should be returned." Maximum of 10 routes, either in a comma-separated list or an iterable. Response: `vehicle`: (vehicle container) contains list of `vid`: bus # `tmstmp`: local date/time of vehicle update `lat`, `lon`: position `hdg`: vehicle heading (e.g., 0: north, 180: south) `pid`: pattern ID of current trip (see `self.geopatterns`) `pdist`: distance into trip `rt`: route (e.g, 88) `des`: bus destinations (e.g., "Penn to Bakery Square") `dly` (optional): True if bus is delayed `spd`: speed in mph `zone`: current zone (usually `None` here) `tablockid`, `tatripid`: unsure, seems internal? http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=vehicles.jsp """ if vid and rt: raise ValueError("The `vid` and `route` parameters cannot be specified simultaneously.") if not (vid or rt): raise ValueError("You must specify either the `vid` or `rt` parameter.") # Turn list into comma separated string if listlike(rt): rt = ",".join( map(str, rt) ) if listlike(vid): vid = ",".join( map(str, vid) ) url = self.endpoint('VEHICLES', dict(vid=vid, rt=rt)) return self.response(url) def routes(self): """ Return a list of routes currently tracked by the API. Arguments: none Response: `route`: (route container) contains list of `rt`: route designator (e.g, P1, 88) `rtnm`: route name (e.g. EAST BUSWAY-ALL STOPS, PENN) `rtclr`: color of route used in map display (e.g. #9900ff), usually unimportant http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=routes.jsp """ return self.response(self.endpoint('ROUTES')) def route_directions(self, rt): """ Return a list of directions for a route. The directions seem to always be INBOUND and OUTBOUND for the busses currently, where INBOUND is towards downtown and OUTBOUND is away from downtown. (No idea if this is going to change.) Arguments: `rt`: route designator Response: list of `dir`: directions served (e.g., INBOUND, OUTBOUND) http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=routeDirections.jsp """ url = self.endpoint('R_DIRECTIONS', dict(rt=rt)) return self.response(url) def stops(self, rt, direction): """ Return a list of stops for a particular route. Arguments: `rt`: route designator `dir`: route direction (INBOUND, OUTBOUND) Response: `stop`: (stop container) contains list of `stpid`: unique ID number for bus stop `stpnm`: stop name (what shows up on the display in the bus, e.g., "Forbes and Murray") `lat`, `lng`: location of stop http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=stops.jsp """ url = self.endpoint('STOPS', dict(rt=rt, dir=direction)) return self.response(url) def geopatterns(self, rt=None, pid=None): """ Returns a set of geographic points that make up a particular routing ('pattern', in API terminology) for a bus route. A bus route can have more than one routing. Arguments: either `rt`: route designator or `pid`: comma-separated list or an iterable of pattern IDs (max 10) Response: `ptr`: (pattern container) contains list of `pid`: pattern ID `ln`: length of pattern in feet `rtdir`: route direction (see `self.route_directions`) `pt`: geo points, contains list of `seq`: position of point in pattern `typ`: 'S' = stop, 'W' = waypoint -> if `typ` is a stop, will contain: `stpid`, `stpnm`, `pdist` (see `self.stops`) `lat`, `lon`: position of point http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=patterns.jsp """ if rt and pid: raise ValueError("The `rt` and `pid` parameters cannot be specified simultaneously.") if not (rt or pid): ValueError("You must specify either the `rt` or `pid` parameter.") if listlike(pid): pid = ",".join(pid) url = self.endpoint("R_GEO", dict(rt=rt, pid=pid)) return self._lru_geopatterns(url) def _lru_geopatterns(self, url): # @lru_cache doesn't support kwargs so this is a bit of a workaround... return self.response(url) def predictions(self, stpid="", rt="", vid="", maxpredictions=""): """ Retrieve predictions for 1+ stops or 1+ vehicles. Arguments: `stpid`: unique ID number for bus stop (single or comma-seperated list or iterable) or `vid`: vehicle ID number (single or comma-seperated list or iterable) or `stpid` and `rt` `maxpredictions` (optional): limit number of predictions returned Response: `prd`: (prediction container) contains list of `tmstp`: when prediction was generated `typ`: prediction type ('A' = arrival, 'D' = departure) `stpid`: stop ID for prediction `stpnm`: stop name for prediction `vid`: vehicle ID for prediction `dstp`: vehicle distance to stop (feet) `rt`: bus route `des`: bus destination `prdtm`: ETA/ETD `dly`: True if bus delayed `tablockid`, `tatripid`, `zone`: internal, see `self.vehicles` http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=predictions.jsp """ if (stpid and vid) or (rt and vid): raise ValueError("These parameters cannot be specified simultaneously.") elif not (stpid or rt or vid): raise ValueError("You must specify a parameter.") if listlike(stpid): stpid = ",".join(stpid) if listlike(rt): rt = ",".join(rt) if listlike(vid): vid = ",".join(vid) if stpid or (rt and stpid) or vid: url = self.endpoint('PREDICTION', dict(rt=rt, stpid=stpid, vid=vid, top=maxpredictions)) return self.response(url) def bulletins(self, rt="", rtdir="", stpid=""): """ Return list of service alerts ('bulletins') for a route or stop. Arguments: `rt`: route designator or `stpid`: bus stop number or (`rt` and `rtdir`) or (`rt` and `rtdir` and `stpid`) Response: `sb`: (bulletin container) contains list of `nm`: bulletin name/ID `sbj`: bulletin subject `dtl`: full text and/or `brf`: short text `prty`: priority (high, medium, low) `srvc`: (routes bulletin applies to) contains list of `rt`: route designator `rtdir`: route direction `stpid`: bus stop ID number `stpnm`: bus stop name http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=serviceBulletins.jsp """ if not (rt or stpid) or (rtdir and not (rt or stpid)): raise ValueError("You must specify a parameter.") if listlike(stpid): stpid = ",".join(stpid) if listlike(rt): rt = ",".join(rt) url = self.endpoint('BULLETINS', dict(rt=rt, rtdir=rtdir, stpid=stpid)) return self.response(url) def detournotices(self, rt): from BeautifulSoup import BeautifulSoup from datetime import datetime URL = "http://www.portauthority.org/paac/apps/detoursdnn/pgDetours.asp?mode=results&s=Route&Type=Detour" _strptime = "%m/%d/%Y" rt = str(rt) formdata = { "txtRoute": "0"*(4-len(rt)) + rt, "submit1": "Search" } data = requests.post(URL, data=formdata) if "No Detours are running" in data.content: return False else: detours = [] parser = BeautifulSoup(data.content) titles = parser.findAll('td', attrs={'colspan': '2'})[0:-1] dates = parser.findAll('td', attrs={'colspan': '1', 'class': 'RegularFormText'}) notices = zip(titles, dates) for rawTitle, rawDates in notices: title = rawTitle.p.a.text memoID = dict(rawTitle.p.a.attrs)['href'].split("MemoID=")[-1] fromDate, toDate = rawDates.p.text.replace('&nbsp;', ' ').replace('\r', '').replace('\n', '').replace('\t', '').split(' to ') try: fromDate = datetime.strptime(fromDate, _strptime) except: None try: toDate = datetime.strptime(toDate, _strptime) except: None detour = DetourNotice(memoID, title, fromDate, toDate) detours.append(detour) return detours
nhfruchter/pgh-bustime
pghbustime/interface.py
BustimeAPI.route_directions
python
def route_directions(self, rt): url = self.endpoint('R_DIRECTIONS', dict(rt=rt)) return self.response(url)
Return a list of directions for a route. The directions seem to always be INBOUND and OUTBOUND for the busses currently, where INBOUND is towards downtown and OUTBOUND is away from downtown. (No idea if this is going to change.) Arguments: `rt`: route designator Response: list of `dir`: directions served (e.g., INBOUND, OUTBOUND) http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=routeDirections.jsp
train
https://github.com/nhfruchter/pgh-bustime/blob/b915e8fea28541612f0e79783c2cf12fd3daaac0/pghbustime/interface.py#L202-L219
null
class BustimeAPI(object): """ A `requests` wrapper around the Port Authority's bustime API with some basic error handling and some useful conversions (like an option to convert all responses from JSON to XML.) This attempts to stay relatively close to the actual API's format with a few post-processing liberties taken to make things more Python friendly. Requires: `api_key` Optional: `locale` (defaults to en_US) `_format` (defaults to `json`, can be `xml`), `tmres` (time resolution, defaults to `s`) `cache` (cache non-dynamic information, defaults to False; currently caches stops, routes) Implements: `bulletins`, `geopatterns`, `predictions`, `route_directions`, `routes`, `stops`, `systemtime`, `vehicles If you have an API key: >>> bus = PAACBustime(my_api_key) Official API documentation can be found at the Port Authority site: http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=documentation.jsp """ __api_version__ = 'v1' ENDPOINTS = dict( SYSTIME = "http://realtime.portauthority.org/bustime/api/v1/gettime", VEHICLES = "http://realtime.portauthority.org/bustime/api/v1/getvehicles", ROUTES = "http://realtime.portauthority.org/bustime/api/v1/getroutes", R_DIRECTIONS = "http://realtime.portauthority.org/bustime/api/v1/getdirections", STOPS = "http://realtime.portauthority.org/bustime/api/v1/getstops", R_GEO = "http://realtime.portauthority.org/bustime/api/v1/getpatterns", PREDICTION = "http://realtime.portauthority.org/bustime/api/v1/getpredictions", BULLETINS = "http://realtime.portauthority.org/bustime/api/v1/getservicebulletins" ) RESPONSE_TOKEN = "bustime-response" ERROR_TOKEN = "error" STRPTIME = "%Y%m%d %H:%M:%S" def __init__(self, apikey, locale="en_US", _format="json", tmres="s"): self.key = apikey self.format = _format self.args = dict( localestring = locale, tmres = tmres ) def endpoint(self, endpt, argdict=None): """ Construct API endpoint URLs using instance options in `self.args` and local arguments passed to the function as a dictionary `argdict`. >>> api = BustimeAPI("BOGUSAPIKEY") >>> api.endpoint('VEHICLES') 'http://realtime.portauthority.org/bustime/api/v1/getvehicles?key=BOGUSAPIKEY&tmres=s&localestring=en_US' >>> api.endpoint('PREDICTION', dict(stpid=4123, rt="61C")) 'http://realtime.portauthority.org/bustime/api/v1/getpredictions?key=BOGUSAPIKEY&tmres=s&localestring=en_US&format=json&rt=61C&stpid=4123' """ instanceargs = "{}&{}".format(queryjoin(key=self.key), queryjoin(self.args)) if argdict: localargs = queryjoin(argdict) querystring = "{}&{}".format(instanceargs, localargs) else: querystring = instanceargs return "{}?{}".format(self.ENDPOINTS[endpt], querystring) def response(self, url): """Grab an API response.""" resp = requests.get(url).content return self.parseresponse(resp) def errorhandle(self, resp): """Parse API error responses and raise appropriate exceptions.""" if self.format == 'json': parsed = xmltodict.parse(resp) errors = parsed[self.RESPONSE_TOKEN][self.ERROR_TOKEN] # Create list of errors if more than one error response is given if type(errors) is list and len(errors) > 1: messages = ", ".join([" ".join(["{}: {}".format(k,v) for k, v in e.items()]) for e in errors]) else: overlimit = any('transaction limit' in msg.lower() for msg in errors.values()) if overlimit: raise APILimitExceeded("This API key has used up its daily quota of calls.") else: messages = " ".join(["{}: {}".format(k,v) for k, v in errors.items()]) elif self.format == 'xml': import xml.etree.ElementTree as ET errors = ET.fromstring(resp).findall(self.ERROR_TOKEN) messages = ", ".join(err.find('msg').text for err in errors) else: raise ValueError("Invalid API response format specified: {}." % self.format) raise BustimeError("API returned: {}".format(messages)) def parseresponse(self, resp): """Parse an API response.""" # Support Python 3's bytes type from socket repsonses if sys.version_info.major > 2: resp = resp.decode('utf-8') if self.RESPONSE_TOKEN not in resp: raise BustimeError("The Bustime API returned an invalid response: {}".format(resp)) elif self.ERROR_TOKEN in resp: return self.errorhandle(resp) else: if self.format == 'json': return xmltodict.parse(resp)[self.RESPONSE_TOKEN] elif self.format == 'xml': return resp def systemtime(self): """ Get the API's official time (local, eastern). Arguments: none. Response: `tm`: "Date and time is represented in the following format: YYYYMMDD HH:MM:SS." http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=time.jsp """ return self.response(self.endpoint('SYSTIME')) def vehicles(self, vid=None, rt=None): """ Get busses by route or by vehicle ID. Arguments: either `vid`: "Set of one or more vehicle IDs whose location should be returned." Maximum of 10 `vid`s, either in a comma-separated list or an iterable. `rt`: "Set of one or more route designators for which matching vehicles should be returned." Maximum of 10 routes, either in a comma-separated list or an iterable. Response: `vehicle`: (vehicle container) contains list of `vid`: bus # `tmstmp`: local date/time of vehicle update `lat`, `lon`: position `hdg`: vehicle heading (e.g., 0: north, 180: south) `pid`: pattern ID of current trip (see `self.geopatterns`) `pdist`: distance into trip `rt`: route (e.g, 88) `des`: bus destinations (e.g., "Penn to Bakery Square") `dly` (optional): True if bus is delayed `spd`: speed in mph `zone`: current zone (usually `None` here) `tablockid`, `tatripid`: unsure, seems internal? http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=vehicles.jsp """ if vid and rt: raise ValueError("The `vid` and `route` parameters cannot be specified simultaneously.") if not (vid or rt): raise ValueError("You must specify either the `vid` or `rt` parameter.") # Turn list into comma separated string if listlike(rt): rt = ",".join( map(str, rt) ) if listlike(vid): vid = ",".join( map(str, vid) ) url = self.endpoint('VEHICLES', dict(vid=vid, rt=rt)) return self.response(url) def routes(self): """ Return a list of routes currently tracked by the API. Arguments: none Response: `route`: (route container) contains list of `rt`: route designator (e.g, P1, 88) `rtnm`: route name (e.g. EAST BUSWAY-ALL STOPS, PENN) `rtclr`: color of route used in map display (e.g. #9900ff), usually unimportant http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=routes.jsp """ return self.response(self.endpoint('ROUTES')) def route_directions(self, rt): """ Return a list of directions for a route. The directions seem to always be INBOUND and OUTBOUND for the busses currently, where INBOUND is towards downtown and OUTBOUND is away from downtown. (No idea if this is going to change.) Arguments: `rt`: route designator Response: list of `dir`: directions served (e.g., INBOUND, OUTBOUND) http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=routeDirections.jsp """ url = self.endpoint('R_DIRECTIONS', dict(rt=rt)) return self.response(url) def stops(self, rt, direction): """ Return a list of stops for a particular route. Arguments: `rt`: route designator `dir`: route direction (INBOUND, OUTBOUND) Response: `stop`: (stop container) contains list of `stpid`: unique ID number for bus stop `stpnm`: stop name (what shows up on the display in the bus, e.g., "Forbes and Murray") `lat`, `lng`: location of stop http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=stops.jsp """ url = self.endpoint('STOPS', dict(rt=rt, dir=direction)) return self.response(url) def geopatterns(self, rt=None, pid=None): """ Returns a set of geographic points that make up a particular routing ('pattern', in API terminology) for a bus route. A bus route can have more than one routing. Arguments: either `rt`: route designator or `pid`: comma-separated list or an iterable of pattern IDs (max 10) Response: `ptr`: (pattern container) contains list of `pid`: pattern ID `ln`: length of pattern in feet `rtdir`: route direction (see `self.route_directions`) `pt`: geo points, contains list of `seq`: position of point in pattern `typ`: 'S' = stop, 'W' = waypoint -> if `typ` is a stop, will contain: `stpid`, `stpnm`, `pdist` (see `self.stops`) `lat`, `lon`: position of point http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=patterns.jsp """ if rt and pid: raise ValueError("The `rt` and `pid` parameters cannot be specified simultaneously.") if not (rt or pid): ValueError("You must specify either the `rt` or `pid` parameter.") if listlike(pid): pid = ",".join(pid) url = self.endpoint("R_GEO", dict(rt=rt, pid=pid)) return self._lru_geopatterns(url) def _lru_geopatterns(self, url): # @lru_cache doesn't support kwargs so this is a bit of a workaround... return self.response(url) def predictions(self, stpid="", rt="", vid="", maxpredictions=""): """ Retrieve predictions for 1+ stops or 1+ vehicles. Arguments: `stpid`: unique ID number for bus stop (single or comma-seperated list or iterable) or `vid`: vehicle ID number (single or comma-seperated list or iterable) or `stpid` and `rt` `maxpredictions` (optional): limit number of predictions returned Response: `prd`: (prediction container) contains list of `tmstp`: when prediction was generated `typ`: prediction type ('A' = arrival, 'D' = departure) `stpid`: stop ID for prediction `stpnm`: stop name for prediction `vid`: vehicle ID for prediction `dstp`: vehicle distance to stop (feet) `rt`: bus route `des`: bus destination `prdtm`: ETA/ETD `dly`: True if bus delayed `tablockid`, `tatripid`, `zone`: internal, see `self.vehicles` http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=predictions.jsp """ if (stpid and vid) or (rt and vid): raise ValueError("These parameters cannot be specified simultaneously.") elif not (stpid or rt or vid): raise ValueError("You must specify a parameter.") if listlike(stpid): stpid = ",".join(stpid) if listlike(rt): rt = ",".join(rt) if listlike(vid): vid = ",".join(vid) if stpid or (rt and stpid) or vid: url = self.endpoint('PREDICTION', dict(rt=rt, stpid=stpid, vid=vid, top=maxpredictions)) return self.response(url) def bulletins(self, rt="", rtdir="", stpid=""): """ Return list of service alerts ('bulletins') for a route or stop. Arguments: `rt`: route designator or `stpid`: bus stop number or (`rt` and `rtdir`) or (`rt` and `rtdir` and `stpid`) Response: `sb`: (bulletin container) contains list of `nm`: bulletin name/ID `sbj`: bulletin subject `dtl`: full text and/or `brf`: short text `prty`: priority (high, medium, low) `srvc`: (routes bulletin applies to) contains list of `rt`: route designator `rtdir`: route direction `stpid`: bus stop ID number `stpnm`: bus stop name http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=serviceBulletins.jsp """ if not (rt or stpid) or (rtdir and not (rt or stpid)): raise ValueError("You must specify a parameter.") if listlike(stpid): stpid = ",".join(stpid) if listlike(rt): rt = ",".join(rt) url = self.endpoint('BULLETINS', dict(rt=rt, rtdir=rtdir, stpid=stpid)) return self.response(url) def detournotices(self, rt): from BeautifulSoup import BeautifulSoup from datetime import datetime URL = "http://www.portauthority.org/paac/apps/detoursdnn/pgDetours.asp?mode=results&s=Route&Type=Detour" _strptime = "%m/%d/%Y" rt = str(rt) formdata = { "txtRoute": "0"*(4-len(rt)) + rt, "submit1": "Search" } data = requests.post(URL, data=formdata) if "No Detours are running" in data.content: return False else: detours = [] parser = BeautifulSoup(data.content) titles = parser.findAll('td', attrs={'colspan': '2'})[0:-1] dates = parser.findAll('td', attrs={'colspan': '1', 'class': 'RegularFormText'}) notices = zip(titles, dates) for rawTitle, rawDates in notices: title = rawTitle.p.a.text memoID = dict(rawTitle.p.a.attrs)['href'].split("MemoID=")[-1] fromDate, toDate = rawDates.p.text.replace('&nbsp;', ' ').replace('\r', '').replace('\n', '').replace('\t', '').split(' to ') try: fromDate = datetime.strptime(fromDate, _strptime) except: None try: toDate = datetime.strptime(toDate, _strptime) except: None detour = DetourNotice(memoID, title, fromDate, toDate) detours.append(detour) return detours
nhfruchter/pgh-bustime
pghbustime/interface.py
BustimeAPI.stops
python
def stops(self, rt, direction): url = self.endpoint('STOPS', dict(rt=rt, dir=direction)) return self.response(url)
Return a list of stops for a particular route. Arguments: `rt`: route designator `dir`: route direction (INBOUND, OUTBOUND) Response: `stop`: (stop container) contains list of `stpid`: unique ID number for bus stop `stpnm`: stop name (what shows up on the display in the bus, e.g., "Forbes and Murray") `lat`, `lng`: location of stop http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=stops.jsp
train
https://github.com/nhfruchter/pgh-bustime/blob/b915e8fea28541612f0e79783c2cf12fd3daaac0/pghbustime/interface.py#L221-L239
null
class BustimeAPI(object): """ A `requests` wrapper around the Port Authority's bustime API with some basic error handling and some useful conversions (like an option to convert all responses from JSON to XML.) This attempts to stay relatively close to the actual API's format with a few post-processing liberties taken to make things more Python friendly. Requires: `api_key` Optional: `locale` (defaults to en_US) `_format` (defaults to `json`, can be `xml`), `tmres` (time resolution, defaults to `s`) `cache` (cache non-dynamic information, defaults to False; currently caches stops, routes) Implements: `bulletins`, `geopatterns`, `predictions`, `route_directions`, `routes`, `stops`, `systemtime`, `vehicles If you have an API key: >>> bus = PAACBustime(my_api_key) Official API documentation can be found at the Port Authority site: http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=documentation.jsp """ __api_version__ = 'v1' ENDPOINTS = dict( SYSTIME = "http://realtime.portauthority.org/bustime/api/v1/gettime", VEHICLES = "http://realtime.portauthority.org/bustime/api/v1/getvehicles", ROUTES = "http://realtime.portauthority.org/bustime/api/v1/getroutes", R_DIRECTIONS = "http://realtime.portauthority.org/bustime/api/v1/getdirections", STOPS = "http://realtime.portauthority.org/bustime/api/v1/getstops", R_GEO = "http://realtime.portauthority.org/bustime/api/v1/getpatterns", PREDICTION = "http://realtime.portauthority.org/bustime/api/v1/getpredictions", BULLETINS = "http://realtime.portauthority.org/bustime/api/v1/getservicebulletins" ) RESPONSE_TOKEN = "bustime-response" ERROR_TOKEN = "error" STRPTIME = "%Y%m%d %H:%M:%S" def __init__(self, apikey, locale="en_US", _format="json", tmres="s"): self.key = apikey self.format = _format self.args = dict( localestring = locale, tmres = tmres ) def endpoint(self, endpt, argdict=None): """ Construct API endpoint URLs using instance options in `self.args` and local arguments passed to the function as a dictionary `argdict`. >>> api = BustimeAPI("BOGUSAPIKEY") >>> api.endpoint('VEHICLES') 'http://realtime.portauthority.org/bustime/api/v1/getvehicles?key=BOGUSAPIKEY&tmres=s&localestring=en_US' >>> api.endpoint('PREDICTION', dict(stpid=4123, rt="61C")) 'http://realtime.portauthority.org/bustime/api/v1/getpredictions?key=BOGUSAPIKEY&tmres=s&localestring=en_US&format=json&rt=61C&stpid=4123' """ instanceargs = "{}&{}".format(queryjoin(key=self.key), queryjoin(self.args)) if argdict: localargs = queryjoin(argdict) querystring = "{}&{}".format(instanceargs, localargs) else: querystring = instanceargs return "{}?{}".format(self.ENDPOINTS[endpt], querystring) def response(self, url): """Grab an API response.""" resp = requests.get(url).content return self.parseresponse(resp) def errorhandle(self, resp): """Parse API error responses and raise appropriate exceptions.""" if self.format == 'json': parsed = xmltodict.parse(resp) errors = parsed[self.RESPONSE_TOKEN][self.ERROR_TOKEN] # Create list of errors if more than one error response is given if type(errors) is list and len(errors) > 1: messages = ", ".join([" ".join(["{}: {}".format(k,v) for k, v in e.items()]) for e in errors]) else: overlimit = any('transaction limit' in msg.lower() for msg in errors.values()) if overlimit: raise APILimitExceeded("This API key has used up its daily quota of calls.") else: messages = " ".join(["{}: {}".format(k,v) for k, v in errors.items()]) elif self.format == 'xml': import xml.etree.ElementTree as ET errors = ET.fromstring(resp).findall(self.ERROR_TOKEN) messages = ", ".join(err.find('msg').text for err in errors) else: raise ValueError("Invalid API response format specified: {}." % self.format) raise BustimeError("API returned: {}".format(messages)) def parseresponse(self, resp): """Parse an API response.""" # Support Python 3's bytes type from socket repsonses if sys.version_info.major > 2: resp = resp.decode('utf-8') if self.RESPONSE_TOKEN not in resp: raise BustimeError("The Bustime API returned an invalid response: {}".format(resp)) elif self.ERROR_TOKEN in resp: return self.errorhandle(resp) else: if self.format == 'json': return xmltodict.parse(resp)[self.RESPONSE_TOKEN] elif self.format == 'xml': return resp def systemtime(self): """ Get the API's official time (local, eastern). Arguments: none. Response: `tm`: "Date and time is represented in the following format: YYYYMMDD HH:MM:SS." http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=time.jsp """ return self.response(self.endpoint('SYSTIME')) def vehicles(self, vid=None, rt=None): """ Get busses by route or by vehicle ID. Arguments: either `vid`: "Set of one or more vehicle IDs whose location should be returned." Maximum of 10 `vid`s, either in a comma-separated list or an iterable. `rt`: "Set of one or more route designators for which matching vehicles should be returned." Maximum of 10 routes, either in a comma-separated list or an iterable. Response: `vehicle`: (vehicle container) contains list of `vid`: bus # `tmstmp`: local date/time of vehicle update `lat`, `lon`: position `hdg`: vehicle heading (e.g., 0: north, 180: south) `pid`: pattern ID of current trip (see `self.geopatterns`) `pdist`: distance into trip `rt`: route (e.g, 88) `des`: bus destinations (e.g., "Penn to Bakery Square") `dly` (optional): True if bus is delayed `spd`: speed in mph `zone`: current zone (usually `None` here) `tablockid`, `tatripid`: unsure, seems internal? http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=vehicles.jsp """ if vid and rt: raise ValueError("The `vid` and `route` parameters cannot be specified simultaneously.") if not (vid or rt): raise ValueError("You must specify either the `vid` or `rt` parameter.") # Turn list into comma separated string if listlike(rt): rt = ",".join( map(str, rt) ) if listlike(vid): vid = ",".join( map(str, vid) ) url = self.endpoint('VEHICLES', dict(vid=vid, rt=rt)) return self.response(url) def routes(self): """ Return a list of routes currently tracked by the API. Arguments: none Response: `route`: (route container) contains list of `rt`: route designator (e.g, P1, 88) `rtnm`: route name (e.g. EAST BUSWAY-ALL STOPS, PENN) `rtclr`: color of route used in map display (e.g. #9900ff), usually unimportant http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=routes.jsp """ return self.response(self.endpoint('ROUTES')) def route_directions(self, rt): """ Return a list of directions for a route. The directions seem to always be INBOUND and OUTBOUND for the busses currently, where INBOUND is towards downtown and OUTBOUND is away from downtown. (No idea if this is going to change.) Arguments: `rt`: route designator Response: list of `dir`: directions served (e.g., INBOUND, OUTBOUND) http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=routeDirections.jsp """ url = self.endpoint('R_DIRECTIONS', dict(rt=rt)) return self.response(url) def stops(self, rt, direction): """ Return a list of stops for a particular route. Arguments: `rt`: route designator `dir`: route direction (INBOUND, OUTBOUND) Response: `stop`: (stop container) contains list of `stpid`: unique ID number for bus stop `stpnm`: stop name (what shows up on the display in the bus, e.g., "Forbes and Murray") `lat`, `lng`: location of stop http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=stops.jsp """ url = self.endpoint('STOPS', dict(rt=rt, dir=direction)) return self.response(url) def geopatterns(self, rt=None, pid=None): """ Returns a set of geographic points that make up a particular routing ('pattern', in API terminology) for a bus route. A bus route can have more than one routing. Arguments: either `rt`: route designator or `pid`: comma-separated list or an iterable of pattern IDs (max 10) Response: `ptr`: (pattern container) contains list of `pid`: pattern ID `ln`: length of pattern in feet `rtdir`: route direction (see `self.route_directions`) `pt`: geo points, contains list of `seq`: position of point in pattern `typ`: 'S' = stop, 'W' = waypoint -> if `typ` is a stop, will contain: `stpid`, `stpnm`, `pdist` (see `self.stops`) `lat`, `lon`: position of point http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=patterns.jsp """ if rt and pid: raise ValueError("The `rt` and `pid` parameters cannot be specified simultaneously.") if not (rt or pid): ValueError("You must specify either the `rt` or `pid` parameter.") if listlike(pid): pid = ",".join(pid) url = self.endpoint("R_GEO", dict(rt=rt, pid=pid)) return self._lru_geopatterns(url) def _lru_geopatterns(self, url): # @lru_cache doesn't support kwargs so this is a bit of a workaround... return self.response(url) def predictions(self, stpid="", rt="", vid="", maxpredictions=""): """ Retrieve predictions for 1+ stops or 1+ vehicles. Arguments: `stpid`: unique ID number for bus stop (single or comma-seperated list or iterable) or `vid`: vehicle ID number (single or comma-seperated list or iterable) or `stpid` and `rt` `maxpredictions` (optional): limit number of predictions returned Response: `prd`: (prediction container) contains list of `tmstp`: when prediction was generated `typ`: prediction type ('A' = arrival, 'D' = departure) `stpid`: stop ID for prediction `stpnm`: stop name for prediction `vid`: vehicle ID for prediction `dstp`: vehicle distance to stop (feet) `rt`: bus route `des`: bus destination `prdtm`: ETA/ETD `dly`: True if bus delayed `tablockid`, `tatripid`, `zone`: internal, see `self.vehicles` http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=predictions.jsp """ if (stpid and vid) or (rt and vid): raise ValueError("These parameters cannot be specified simultaneously.") elif not (stpid or rt or vid): raise ValueError("You must specify a parameter.") if listlike(stpid): stpid = ",".join(stpid) if listlike(rt): rt = ",".join(rt) if listlike(vid): vid = ",".join(vid) if stpid or (rt and stpid) or vid: url = self.endpoint('PREDICTION', dict(rt=rt, stpid=stpid, vid=vid, top=maxpredictions)) return self.response(url) def bulletins(self, rt="", rtdir="", stpid=""): """ Return list of service alerts ('bulletins') for a route or stop. Arguments: `rt`: route designator or `stpid`: bus stop number or (`rt` and `rtdir`) or (`rt` and `rtdir` and `stpid`) Response: `sb`: (bulletin container) contains list of `nm`: bulletin name/ID `sbj`: bulletin subject `dtl`: full text and/or `brf`: short text `prty`: priority (high, medium, low) `srvc`: (routes bulletin applies to) contains list of `rt`: route designator `rtdir`: route direction `stpid`: bus stop ID number `stpnm`: bus stop name http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=serviceBulletins.jsp """ if not (rt or stpid) or (rtdir and not (rt or stpid)): raise ValueError("You must specify a parameter.") if listlike(stpid): stpid = ",".join(stpid) if listlike(rt): rt = ",".join(rt) url = self.endpoint('BULLETINS', dict(rt=rt, rtdir=rtdir, stpid=stpid)) return self.response(url) def detournotices(self, rt): from BeautifulSoup import BeautifulSoup from datetime import datetime URL = "http://www.portauthority.org/paac/apps/detoursdnn/pgDetours.asp?mode=results&s=Route&Type=Detour" _strptime = "%m/%d/%Y" rt = str(rt) formdata = { "txtRoute": "0"*(4-len(rt)) + rt, "submit1": "Search" } data = requests.post(URL, data=formdata) if "No Detours are running" in data.content: return False else: detours = [] parser = BeautifulSoup(data.content) titles = parser.findAll('td', attrs={'colspan': '2'})[0:-1] dates = parser.findAll('td', attrs={'colspan': '1', 'class': 'RegularFormText'}) notices = zip(titles, dates) for rawTitle, rawDates in notices: title = rawTitle.p.a.text memoID = dict(rawTitle.p.a.attrs)['href'].split("MemoID=")[-1] fromDate, toDate = rawDates.p.text.replace('&nbsp;', ' ').replace('\r', '').replace('\n', '').replace('\t', '').split(' to ') try: fromDate = datetime.strptime(fromDate, _strptime) except: None try: toDate = datetime.strptime(toDate, _strptime) except: None detour = DetourNotice(memoID, title, fromDate, toDate) detours.append(detour) return detours
nhfruchter/pgh-bustime
pghbustime/interface.py
BustimeAPI.geopatterns
python
def geopatterns(self, rt=None, pid=None): if rt and pid: raise ValueError("The `rt` and `pid` parameters cannot be specified simultaneously.") if not (rt or pid): ValueError("You must specify either the `rt` or `pid` parameter.") if listlike(pid): pid = ",".join(pid) url = self.endpoint("R_GEO", dict(rt=rt, pid=pid)) return self._lru_geopatterns(url)
Returns a set of geographic points that make up a particular routing ('pattern', in API terminology) for a bus route. A bus route can have more than one routing. Arguments: either `rt`: route designator or `pid`: comma-separated list or an iterable of pattern IDs (max 10) Response: `ptr`: (pattern container) contains list of `pid`: pattern ID `ln`: length of pattern in feet `rtdir`: route direction (see `self.route_directions`) `pt`: geo points, contains list of `seq`: position of point in pattern `typ`: 'S' = stop, 'W' = waypoint -> if `typ` is a stop, will contain: `stpid`, `stpnm`, `pdist` (see `self.stops`) `lat`, `lon`: position of point http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=patterns.jsp
train
https://github.com/nhfruchter/pgh-bustime/blob/b915e8fea28541612f0e79783c2cf12fd3daaac0/pghbustime/interface.py#L241-L278
null
class BustimeAPI(object): """ A `requests` wrapper around the Port Authority's bustime API with some basic error handling and some useful conversions (like an option to convert all responses from JSON to XML.) This attempts to stay relatively close to the actual API's format with a few post-processing liberties taken to make things more Python friendly. Requires: `api_key` Optional: `locale` (defaults to en_US) `_format` (defaults to `json`, can be `xml`), `tmres` (time resolution, defaults to `s`) `cache` (cache non-dynamic information, defaults to False; currently caches stops, routes) Implements: `bulletins`, `geopatterns`, `predictions`, `route_directions`, `routes`, `stops`, `systemtime`, `vehicles If you have an API key: >>> bus = PAACBustime(my_api_key) Official API documentation can be found at the Port Authority site: http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=documentation.jsp """ __api_version__ = 'v1' ENDPOINTS = dict( SYSTIME = "http://realtime.portauthority.org/bustime/api/v1/gettime", VEHICLES = "http://realtime.portauthority.org/bustime/api/v1/getvehicles", ROUTES = "http://realtime.portauthority.org/bustime/api/v1/getroutes", R_DIRECTIONS = "http://realtime.portauthority.org/bustime/api/v1/getdirections", STOPS = "http://realtime.portauthority.org/bustime/api/v1/getstops", R_GEO = "http://realtime.portauthority.org/bustime/api/v1/getpatterns", PREDICTION = "http://realtime.portauthority.org/bustime/api/v1/getpredictions", BULLETINS = "http://realtime.portauthority.org/bustime/api/v1/getservicebulletins" ) RESPONSE_TOKEN = "bustime-response" ERROR_TOKEN = "error" STRPTIME = "%Y%m%d %H:%M:%S" def __init__(self, apikey, locale="en_US", _format="json", tmres="s"): self.key = apikey self.format = _format self.args = dict( localestring = locale, tmres = tmres ) def endpoint(self, endpt, argdict=None): """ Construct API endpoint URLs using instance options in `self.args` and local arguments passed to the function as a dictionary `argdict`. >>> api = BustimeAPI("BOGUSAPIKEY") >>> api.endpoint('VEHICLES') 'http://realtime.portauthority.org/bustime/api/v1/getvehicles?key=BOGUSAPIKEY&tmres=s&localestring=en_US' >>> api.endpoint('PREDICTION', dict(stpid=4123, rt="61C")) 'http://realtime.portauthority.org/bustime/api/v1/getpredictions?key=BOGUSAPIKEY&tmres=s&localestring=en_US&format=json&rt=61C&stpid=4123' """ instanceargs = "{}&{}".format(queryjoin(key=self.key), queryjoin(self.args)) if argdict: localargs = queryjoin(argdict) querystring = "{}&{}".format(instanceargs, localargs) else: querystring = instanceargs return "{}?{}".format(self.ENDPOINTS[endpt], querystring) def response(self, url): """Grab an API response.""" resp = requests.get(url).content return self.parseresponse(resp) def errorhandle(self, resp): """Parse API error responses and raise appropriate exceptions.""" if self.format == 'json': parsed = xmltodict.parse(resp) errors = parsed[self.RESPONSE_TOKEN][self.ERROR_TOKEN] # Create list of errors if more than one error response is given if type(errors) is list and len(errors) > 1: messages = ", ".join([" ".join(["{}: {}".format(k,v) for k, v in e.items()]) for e in errors]) else: overlimit = any('transaction limit' in msg.lower() for msg in errors.values()) if overlimit: raise APILimitExceeded("This API key has used up its daily quota of calls.") else: messages = " ".join(["{}: {}".format(k,v) for k, v in errors.items()]) elif self.format == 'xml': import xml.etree.ElementTree as ET errors = ET.fromstring(resp).findall(self.ERROR_TOKEN) messages = ", ".join(err.find('msg').text for err in errors) else: raise ValueError("Invalid API response format specified: {}." % self.format) raise BustimeError("API returned: {}".format(messages)) def parseresponse(self, resp): """Parse an API response.""" # Support Python 3's bytes type from socket repsonses if sys.version_info.major > 2: resp = resp.decode('utf-8') if self.RESPONSE_TOKEN not in resp: raise BustimeError("The Bustime API returned an invalid response: {}".format(resp)) elif self.ERROR_TOKEN in resp: return self.errorhandle(resp) else: if self.format == 'json': return xmltodict.parse(resp)[self.RESPONSE_TOKEN] elif self.format == 'xml': return resp def systemtime(self): """ Get the API's official time (local, eastern). Arguments: none. Response: `tm`: "Date and time is represented in the following format: YYYYMMDD HH:MM:SS." http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=time.jsp """ return self.response(self.endpoint('SYSTIME')) def vehicles(self, vid=None, rt=None): """ Get busses by route or by vehicle ID. Arguments: either `vid`: "Set of one or more vehicle IDs whose location should be returned." Maximum of 10 `vid`s, either in a comma-separated list or an iterable. `rt`: "Set of one or more route designators for which matching vehicles should be returned." Maximum of 10 routes, either in a comma-separated list or an iterable. Response: `vehicle`: (vehicle container) contains list of `vid`: bus # `tmstmp`: local date/time of vehicle update `lat`, `lon`: position `hdg`: vehicle heading (e.g., 0: north, 180: south) `pid`: pattern ID of current trip (see `self.geopatterns`) `pdist`: distance into trip `rt`: route (e.g, 88) `des`: bus destinations (e.g., "Penn to Bakery Square") `dly` (optional): True if bus is delayed `spd`: speed in mph `zone`: current zone (usually `None` here) `tablockid`, `tatripid`: unsure, seems internal? http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=vehicles.jsp """ if vid and rt: raise ValueError("The `vid` and `route` parameters cannot be specified simultaneously.") if not (vid or rt): raise ValueError("You must specify either the `vid` or `rt` parameter.") # Turn list into comma separated string if listlike(rt): rt = ",".join( map(str, rt) ) if listlike(vid): vid = ",".join( map(str, vid) ) url = self.endpoint('VEHICLES', dict(vid=vid, rt=rt)) return self.response(url) def routes(self): """ Return a list of routes currently tracked by the API. Arguments: none Response: `route`: (route container) contains list of `rt`: route designator (e.g, P1, 88) `rtnm`: route name (e.g. EAST BUSWAY-ALL STOPS, PENN) `rtclr`: color of route used in map display (e.g. #9900ff), usually unimportant http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=routes.jsp """ return self.response(self.endpoint('ROUTES')) def route_directions(self, rt): """ Return a list of directions for a route. The directions seem to always be INBOUND and OUTBOUND for the busses currently, where INBOUND is towards downtown and OUTBOUND is away from downtown. (No idea if this is going to change.) Arguments: `rt`: route designator Response: list of `dir`: directions served (e.g., INBOUND, OUTBOUND) http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=routeDirections.jsp """ url = self.endpoint('R_DIRECTIONS', dict(rt=rt)) return self.response(url) def stops(self, rt, direction): """ Return a list of stops for a particular route. Arguments: `rt`: route designator `dir`: route direction (INBOUND, OUTBOUND) Response: `stop`: (stop container) contains list of `stpid`: unique ID number for bus stop `stpnm`: stop name (what shows up on the display in the bus, e.g., "Forbes and Murray") `lat`, `lng`: location of stop http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=stops.jsp """ url = self.endpoint('STOPS', dict(rt=rt, dir=direction)) return self.response(url) def geopatterns(self, rt=None, pid=None): """ Returns a set of geographic points that make up a particular routing ('pattern', in API terminology) for a bus route. A bus route can have more than one routing. Arguments: either `rt`: route designator or `pid`: comma-separated list or an iterable of pattern IDs (max 10) Response: `ptr`: (pattern container) contains list of `pid`: pattern ID `ln`: length of pattern in feet `rtdir`: route direction (see `self.route_directions`) `pt`: geo points, contains list of `seq`: position of point in pattern `typ`: 'S' = stop, 'W' = waypoint -> if `typ` is a stop, will contain: `stpid`, `stpnm`, `pdist` (see `self.stops`) `lat`, `lon`: position of point http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=patterns.jsp """ if rt and pid: raise ValueError("The `rt` and `pid` parameters cannot be specified simultaneously.") if not (rt or pid): ValueError("You must specify either the `rt` or `pid` parameter.") if listlike(pid): pid = ",".join(pid) url = self.endpoint("R_GEO", dict(rt=rt, pid=pid)) return self._lru_geopatterns(url) def _lru_geopatterns(self, url): # @lru_cache doesn't support kwargs so this is a bit of a workaround... return self.response(url) def predictions(self, stpid="", rt="", vid="", maxpredictions=""): """ Retrieve predictions for 1+ stops or 1+ vehicles. Arguments: `stpid`: unique ID number for bus stop (single or comma-seperated list or iterable) or `vid`: vehicle ID number (single or comma-seperated list or iterable) or `stpid` and `rt` `maxpredictions` (optional): limit number of predictions returned Response: `prd`: (prediction container) contains list of `tmstp`: when prediction was generated `typ`: prediction type ('A' = arrival, 'D' = departure) `stpid`: stop ID for prediction `stpnm`: stop name for prediction `vid`: vehicle ID for prediction `dstp`: vehicle distance to stop (feet) `rt`: bus route `des`: bus destination `prdtm`: ETA/ETD `dly`: True if bus delayed `tablockid`, `tatripid`, `zone`: internal, see `self.vehicles` http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=predictions.jsp """ if (stpid and vid) or (rt and vid): raise ValueError("These parameters cannot be specified simultaneously.") elif not (stpid or rt or vid): raise ValueError("You must specify a parameter.") if listlike(stpid): stpid = ",".join(stpid) if listlike(rt): rt = ",".join(rt) if listlike(vid): vid = ",".join(vid) if stpid or (rt and stpid) or vid: url = self.endpoint('PREDICTION', dict(rt=rt, stpid=stpid, vid=vid, top=maxpredictions)) return self.response(url) def bulletins(self, rt="", rtdir="", stpid=""): """ Return list of service alerts ('bulletins') for a route or stop. Arguments: `rt`: route designator or `stpid`: bus stop number or (`rt` and `rtdir`) or (`rt` and `rtdir` and `stpid`) Response: `sb`: (bulletin container) contains list of `nm`: bulletin name/ID `sbj`: bulletin subject `dtl`: full text and/or `brf`: short text `prty`: priority (high, medium, low) `srvc`: (routes bulletin applies to) contains list of `rt`: route designator `rtdir`: route direction `stpid`: bus stop ID number `stpnm`: bus stop name http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=serviceBulletins.jsp """ if not (rt or stpid) or (rtdir and not (rt or stpid)): raise ValueError("You must specify a parameter.") if listlike(stpid): stpid = ",".join(stpid) if listlike(rt): rt = ",".join(rt) url = self.endpoint('BULLETINS', dict(rt=rt, rtdir=rtdir, stpid=stpid)) return self.response(url) def detournotices(self, rt): from BeautifulSoup import BeautifulSoup from datetime import datetime URL = "http://www.portauthority.org/paac/apps/detoursdnn/pgDetours.asp?mode=results&s=Route&Type=Detour" _strptime = "%m/%d/%Y" rt = str(rt) formdata = { "txtRoute": "0"*(4-len(rt)) + rt, "submit1": "Search" } data = requests.post(URL, data=formdata) if "No Detours are running" in data.content: return False else: detours = [] parser = BeautifulSoup(data.content) titles = parser.findAll('td', attrs={'colspan': '2'})[0:-1] dates = parser.findAll('td', attrs={'colspan': '1', 'class': 'RegularFormText'}) notices = zip(titles, dates) for rawTitle, rawDates in notices: title = rawTitle.p.a.text memoID = dict(rawTitle.p.a.attrs)['href'].split("MemoID=")[-1] fromDate, toDate = rawDates.p.text.replace('&nbsp;', ' ').replace('\r', '').replace('\n', '').replace('\t', '').split(' to ') try: fromDate = datetime.strptime(fromDate, _strptime) except: None try: toDate = datetime.strptime(toDate, _strptime) except: None detour = DetourNotice(memoID, title, fromDate, toDate) detours.append(detour) return detours
nhfruchter/pgh-bustime
pghbustime/interface.py
BustimeAPI.predictions
python
def predictions(self, stpid="", rt="", vid="", maxpredictions=""): if (stpid and vid) or (rt and vid): raise ValueError("These parameters cannot be specified simultaneously.") elif not (stpid or rt or vid): raise ValueError("You must specify a parameter.") if listlike(stpid): stpid = ",".join(stpid) if listlike(rt): rt = ",".join(rt) if listlike(vid): vid = ",".join(vid) if stpid or (rt and stpid) or vid: url = self.endpoint('PREDICTION', dict(rt=rt, stpid=stpid, vid=vid, top=maxpredictions)) return self.response(url)
Retrieve predictions for 1+ stops or 1+ vehicles. Arguments: `stpid`: unique ID number for bus stop (single or comma-seperated list or iterable) or `vid`: vehicle ID number (single or comma-seperated list or iterable) or `stpid` and `rt` `maxpredictions` (optional): limit number of predictions returned Response: `prd`: (prediction container) contains list of `tmstp`: when prediction was generated `typ`: prediction type ('A' = arrival, 'D' = departure) `stpid`: stop ID for prediction `stpnm`: stop name for prediction `vid`: vehicle ID for prediction `dstp`: vehicle distance to stop (feet) `rt`: bus route `des`: bus destination `prdtm`: ETA/ETD `dly`: True if bus delayed `tablockid`, `tatripid`, `zone`: internal, see `self.vehicles` http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=predictions.jsp
train
https://github.com/nhfruchter/pgh-bustime/blob/b915e8fea28541612f0e79783c2cf12fd3daaac0/pghbustime/interface.py#L284-L325
null
class BustimeAPI(object): """ A `requests` wrapper around the Port Authority's bustime API with some basic error handling and some useful conversions (like an option to convert all responses from JSON to XML.) This attempts to stay relatively close to the actual API's format with a few post-processing liberties taken to make things more Python friendly. Requires: `api_key` Optional: `locale` (defaults to en_US) `_format` (defaults to `json`, can be `xml`), `tmres` (time resolution, defaults to `s`) `cache` (cache non-dynamic information, defaults to False; currently caches stops, routes) Implements: `bulletins`, `geopatterns`, `predictions`, `route_directions`, `routes`, `stops`, `systemtime`, `vehicles If you have an API key: >>> bus = PAACBustime(my_api_key) Official API documentation can be found at the Port Authority site: http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=documentation.jsp """ __api_version__ = 'v1' ENDPOINTS = dict( SYSTIME = "http://realtime.portauthority.org/bustime/api/v1/gettime", VEHICLES = "http://realtime.portauthority.org/bustime/api/v1/getvehicles", ROUTES = "http://realtime.portauthority.org/bustime/api/v1/getroutes", R_DIRECTIONS = "http://realtime.portauthority.org/bustime/api/v1/getdirections", STOPS = "http://realtime.portauthority.org/bustime/api/v1/getstops", R_GEO = "http://realtime.portauthority.org/bustime/api/v1/getpatterns", PREDICTION = "http://realtime.portauthority.org/bustime/api/v1/getpredictions", BULLETINS = "http://realtime.portauthority.org/bustime/api/v1/getservicebulletins" ) RESPONSE_TOKEN = "bustime-response" ERROR_TOKEN = "error" STRPTIME = "%Y%m%d %H:%M:%S" def __init__(self, apikey, locale="en_US", _format="json", tmres="s"): self.key = apikey self.format = _format self.args = dict( localestring = locale, tmres = tmres ) def endpoint(self, endpt, argdict=None): """ Construct API endpoint URLs using instance options in `self.args` and local arguments passed to the function as a dictionary `argdict`. >>> api = BustimeAPI("BOGUSAPIKEY") >>> api.endpoint('VEHICLES') 'http://realtime.portauthority.org/bustime/api/v1/getvehicles?key=BOGUSAPIKEY&tmres=s&localestring=en_US' >>> api.endpoint('PREDICTION', dict(stpid=4123, rt="61C")) 'http://realtime.portauthority.org/bustime/api/v1/getpredictions?key=BOGUSAPIKEY&tmres=s&localestring=en_US&format=json&rt=61C&stpid=4123' """ instanceargs = "{}&{}".format(queryjoin(key=self.key), queryjoin(self.args)) if argdict: localargs = queryjoin(argdict) querystring = "{}&{}".format(instanceargs, localargs) else: querystring = instanceargs return "{}?{}".format(self.ENDPOINTS[endpt], querystring) def response(self, url): """Grab an API response.""" resp = requests.get(url).content return self.parseresponse(resp) def errorhandle(self, resp): """Parse API error responses and raise appropriate exceptions.""" if self.format == 'json': parsed = xmltodict.parse(resp) errors = parsed[self.RESPONSE_TOKEN][self.ERROR_TOKEN] # Create list of errors if more than one error response is given if type(errors) is list and len(errors) > 1: messages = ", ".join([" ".join(["{}: {}".format(k,v) for k, v in e.items()]) for e in errors]) else: overlimit = any('transaction limit' in msg.lower() for msg in errors.values()) if overlimit: raise APILimitExceeded("This API key has used up its daily quota of calls.") else: messages = " ".join(["{}: {}".format(k,v) for k, v in errors.items()]) elif self.format == 'xml': import xml.etree.ElementTree as ET errors = ET.fromstring(resp).findall(self.ERROR_TOKEN) messages = ", ".join(err.find('msg').text for err in errors) else: raise ValueError("Invalid API response format specified: {}." % self.format) raise BustimeError("API returned: {}".format(messages)) def parseresponse(self, resp): """Parse an API response.""" # Support Python 3's bytes type from socket repsonses if sys.version_info.major > 2: resp = resp.decode('utf-8') if self.RESPONSE_TOKEN not in resp: raise BustimeError("The Bustime API returned an invalid response: {}".format(resp)) elif self.ERROR_TOKEN in resp: return self.errorhandle(resp) else: if self.format == 'json': return xmltodict.parse(resp)[self.RESPONSE_TOKEN] elif self.format == 'xml': return resp def systemtime(self): """ Get the API's official time (local, eastern). Arguments: none. Response: `tm`: "Date and time is represented in the following format: YYYYMMDD HH:MM:SS." http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=time.jsp """ return self.response(self.endpoint('SYSTIME')) def vehicles(self, vid=None, rt=None): """ Get busses by route or by vehicle ID. Arguments: either `vid`: "Set of one or more vehicle IDs whose location should be returned." Maximum of 10 `vid`s, either in a comma-separated list or an iterable. `rt`: "Set of one or more route designators for which matching vehicles should be returned." Maximum of 10 routes, either in a comma-separated list or an iterable. Response: `vehicle`: (vehicle container) contains list of `vid`: bus # `tmstmp`: local date/time of vehicle update `lat`, `lon`: position `hdg`: vehicle heading (e.g., 0: north, 180: south) `pid`: pattern ID of current trip (see `self.geopatterns`) `pdist`: distance into trip `rt`: route (e.g, 88) `des`: bus destinations (e.g., "Penn to Bakery Square") `dly` (optional): True if bus is delayed `spd`: speed in mph `zone`: current zone (usually `None` here) `tablockid`, `tatripid`: unsure, seems internal? http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=vehicles.jsp """ if vid and rt: raise ValueError("The `vid` and `route` parameters cannot be specified simultaneously.") if not (vid or rt): raise ValueError("You must specify either the `vid` or `rt` parameter.") # Turn list into comma separated string if listlike(rt): rt = ",".join( map(str, rt) ) if listlike(vid): vid = ",".join( map(str, vid) ) url = self.endpoint('VEHICLES', dict(vid=vid, rt=rt)) return self.response(url) def routes(self): """ Return a list of routes currently tracked by the API. Arguments: none Response: `route`: (route container) contains list of `rt`: route designator (e.g, P1, 88) `rtnm`: route name (e.g. EAST BUSWAY-ALL STOPS, PENN) `rtclr`: color of route used in map display (e.g. #9900ff), usually unimportant http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=routes.jsp """ return self.response(self.endpoint('ROUTES')) def route_directions(self, rt): """ Return a list of directions for a route. The directions seem to always be INBOUND and OUTBOUND for the busses currently, where INBOUND is towards downtown and OUTBOUND is away from downtown. (No idea if this is going to change.) Arguments: `rt`: route designator Response: list of `dir`: directions served (e.g., INBOUND, OUTBOUND) http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=routeDirections.jsp """ url = self.endpoint('R_DIRECTIONS', dict(rt=rt)) return self.response(url) def stops(self, rt, direction): """ Return a list of stops for a particular route. Arguments: `rt`: route designator `dir`: route direction (INBOUND, OUTBOUND) Response: `stop`: (stop container) contains list of `stpid`: unique ID number for bus stop `stpnm`: stop name (what shows up on the display in the bus, e.g., "Forbes and Murray") `lat`, `lng`: location of stop http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=stops.jsp """ url = self.endpoint('STOPS', dict(rt=rt, dir=direction)) return self.response(url) def geopatterns(self, rt=None, pid=None): """ Returns a set of geographic points that make up a particular routing ('pattern', in API terminology) for a bus route. A bus route can have more than one routing. Arguments: either `rt`: route designator or `pid`: comma-separated list or an iterable of pattern IDs (max 10) Response: `ptr`: (pattern container) contains list of `pid`: pattern ID `ln`: length of pattern in feet `rtdir`: route direction (see `self.route_directions`) `pt`: geo points, contains list of `seq`: position of point in pattern `typ`: 'S' = stop, 'W' = waypoint -> if `typ` is a stop, will contain: `stpid`, `stpnm`, `pdist` (see `self.stops`) `lat`, `lon`: position of point http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=patterns.jsp """ if rt and pid: raise ValueError("The `rt` and `pid` parameters cannot be specified simultaneously.") if not (rt or pid): ValueError("You must specify either the `rt` or `pid` parameter.") if listlike(pid): pid = ",".join(pid) url = self.endpoint("R_GEO", dict(rt=rt, pid=pid)) return self._lru_geopatterns(url) def _lru_geopatterns(self, url): # @lru_cache doesn't support kwargs so this is a bit of a workaround... return self.response(url) def predictions(self, stpid="", rt="", vid="", maxpredictions=""): """ Retrieve predictions for 1+ stops or 1+ vehicles. Arguments: `stpid`: unique ID number for bus stop (single or comma-seperated list or iterable) or `vid`: vehicle ID number (single or comma-seperated list or iterable) or `stpid` and `rt` `maxpredictions` (optional): limit number of predictions returned Response: `prd`: (prediction container) contains list of `tmstp`: when prediction was generated `typ`: prediction type ('A' = arrival, 'D' = departure) `stpid`: stop ID for prediction `stpnm`: stop name for prediction `vid`: vehicle ID for prediction `dstp`: vehicle distance to stop (feet) `rt`: bus route `des`: bus destination `prdtm`: ETA/ETD `dly`: True if bus delayed `tablockid`, `tatripid`, `zone`: internal, see `self.vehicles` http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=predictions.jsp """ if (stpid and vid) or (rt and vid): raise ValueError("These parameters cannot be specified simultaneously.") elif not (stpid or rt or vid): raise ValueError("You must specify a parameter.") if listlike(stpid): stpid = ",".join(stpid) if listlike(rt): rt = ",".join(rt) if listlike(vid): vid = ",".join(vid) if stpid or (rt and stpid) or vid: url = self.endpoint('PREDICTION', dict(rt=rt, stpid=stpid, vid=vid, top=maxpredictions)) return self.response(url) def bulletins(self, rt="", rtdir="", stpid=""): """ Return list of service alerts ('bulletins') for a route or stop. Arguments: `rt`: route designator or `stpid`: bus stop number or (`rt` and `rtdir`) or (`rt` and `rtdir` and `stpid`) Response: `sb`: (bulletin container) contains list of `nm`: bulletin name/ID `sbj`: bulletin subject `dtl`: full text and/or `brf`: short text `prty`: priority (high, medium, low) `srvc`: (routes bulletin applies to) contains list of `rt`: route designator `rtdir`: route direction `stpid`: bus stop ID number `stpnm`: bus stop name http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=serviceBulletins.jsp """ if not (rt or stpid) or (rtdir and not (rt or stpid)): raise ValueError("You must specify a parameter.") if listlike(stpid): stpid = ",".join(stpid) if listlike(rt): rt = ",".join(rt) url = self.endpoint('BULLETINS', dict(rt=rt, rtdir=rtdir, stpid=stpid)) return self.response(url) def detournotices(self, rt): from BeautifulSoup import BeautifulSoup from datetime import datetime URL = "http://www.portauthority.org/paac/apps/detoursdnn/pgDetours.asp?mode=results&s=Route&Type=Detour" _strptime = "%m/%d/%Y" rt = str(rt) formdata = { "txtRoute": "0"*(4-len(rt)) + rt, "submit1": "Search" } data = requests.post(URL, data=formdata) if "No Detours are running" in data.content: return False else: detours = [] parser = BeautifulSoup(data.content) titles = parser.findAll('td', attrs={'colspan': '2'})[0:-1] dates = parser.findAll('td', attrs={'colspan': '1', 'class': 'RegularFormText'}) notices = zip(titles, dates) for rawTitle, rawDates in notices: title = rawTitle.p.a.text memoID = dict(rawTitle.p.a.attrs)['href'].split("MemoID=")[-1] fromDate, toDate = rawDates.p.text.replace('&nbsp;', ' ').replace('\r', '').replace('\n', '').replace('\t', '').split(' to ') try: fromDate = datetime.strptime(fromDate, _strptime) except: None try: toDate = datetime.strptime(toDate, _strptime) except: None detour = DetourNotice(memoID, title, fromDate, toDate) detours.append(detour) return detours
nhfruchter/pgh-bustime
pghbustime/interface.py
BustimeAPI.bulletins
python
def bulletins(self, rt="", rtdir="", stpid=""): if not (rt or stpid) or (rtdir and not (rt or stpid)): raise ValueError("You must specify a parameter.") if listlike(stpid): stpid = ",".join(stpid) if listlike(rt): rt = ",".join(rt) url = self.endpoint('BULLETINS', dict(rt=rt, rtdir=rtdir, stpid=stpid)) return self.response(url)
Return list of service alerts ('bulletins') for a route or stop. Arguments: `rt`: route designator or `stpid`: bus stop number or (`rt` and `rtdir`) or (`rt` and `rtdir` and `stpid`) Response: `sb`: (bulletin container) contains list of `nm`: bulletin name/ID `sbj`: bulletin subject `dtl`: full text and/or `brf`: short text `prty`: priority (high, medium, low) `srvc`: (routes bulletin applies to) contains list of `rt`: route designator `rtdir`: route direction `stpid`: bus stop ID number `stpnm`: bus stop name http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=serviceBulletins.jsp
train
https://github.com/nhfruchter/pgh-bustime/blob/b915e8fea28541612f0e79783c2cf12fd3daaac0/pghbustime/interface.py#L327-L360
null
class BustimeAPI(object): """ A `requests` wrapper around the Port Authority's bustime API with some basic error handling and some useful conversions (like an option to convert all responses from JSON to XML.) This attempts to stay relatively close to the actual API's format with a few post-processing liberties taken to make things more Python friendly. Requires: `api_key` Optional: `locale` (defaults to en_US) `_format` (defaults to `json`, can be `xml`), `tmres` (time resolution, defaults to `s`) `cache` (cache non-dynamic information, defaults to False; currently caches stops, routes) Implements: `bulletins`, `geopatterns`, `predictions`, `route_directions`, `routes`, `stops`, `systemtime`, `vehicles If you have an API key: >>> bus = PAACBustime(my_api_key) Official API documentation can be found at the Port Authority site: http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=documentation.jsp """ __api_version__ = 'v1' ENDPOINTS = dict( SYSTIME = "http://realtime.portauthority.org/bustime/api/v1/gettime", VEHICLES = "http://realtime.portauthority.org/bustime/api/v1/getvehicles", ROUTES = "http://realtime.portauthority.org/bustime/api/v1/getroutes", R_DIRECTIONS = "http://realtime.portauthority.org/bustime/api/v1/getdirections", STOPS = "http://realtime.portauthority.org/bustime/api/v1/getstops", R_GEO = "http://realtime.portauthority.org/bustime/api/v1/getpatterns", PREDICTION = "http://realtime.portauthority.org/bustime/api/v1/getpredictions", BULLETINS = "http://realtime.portauthority.org/bustime/api/v1/getservicebulletins" ) RESPONSE_TOKEN = "bustime-response" ERROR_TOKEN = "error" STRPTIME = "%Y%m%d %H:%M:%S" def __init__(self, apikey, locale="en_US", _format="json", tmres="s"): self.key = apikey self.format = _format self.args = dict( localestring = locale, tmres = tmres ) def endpoint(self, endpt, argdict=None): """ Construct API endpoint URLs using instance options in `self.args` and local arguments passed to the function as a dictionary `argdict`. >>> api = BustimeAPI("BOGUSAPIKEY") >>> api.endpoint('VEHICLES') 'http://realtime.portauthority.org/bustime/api/v1/getvehicles?key=BOGUSAPIKEY&tmres=s&localestring=en_US' >>> api.endpoint('PREDICTION', dict(stpid=4123, rt="61C")) 'http://realtime.portauthority.org/bustime/api/v1/getpredictions?key=BOGUSAPIKEY&tmres=s&localestring=en_US&format=json&rt=61C&stpid=4123' """ instanceargs = "{}&{}".format(queryjoin(key=self.key), queryjoin(self.args)) if argdict: localargs = queryjoin(argdict) querystring = "{}&{}".format(instanceargs, localargs) else: querystring = instanceargs return "{}?{}".format(self.ENDPOINTS[endpt], querystring) def response(self, url): """Grab an API response.""" resp = requests.get(url).content return self.parseresponse(resp) def errorhandle(self, resp): """Parse API error responses and raise appropriate exceptions.""" if self.format == 'json': parsed = xmltodict.parse(resp) errors = parsed[self.RESPONSE_TOKEN][self.ERROR_TOKEN] # Create list of errors if more than one error response is given if type(errors) is list and len(errors) > 1: messages = ", ".join([" ".join(["{}: {}".format(k,v) for k, v in e.items()]) for e in errors]) else: overlimit = any('transaction limit' in msg.lower() for msg in errors.values()) if overlimit: raise APILimitExceeded("This API key has used up its daily quota of calls.") else: messages = " ".join(["{}: {}".format(k,v) for k, v in errors.items()]) elif self.format == 'xml': import xml.etree.ElementTree as ET errors = ET.fromstring(resp).findall(self.ERROR_TOKEN) messages = ", ".join(err.find('msg').text for err in errors) else: raise ValueError("Invalid API response format specified: {}." % self.format) raise BustimeError("API returned: {}".format(messages)) def parseresponse(self, resp): """Parse an API response.""" # Support Python 3's bytes type from socket repsonses if sys.version_info.major > 2: resp = resp.decode('utf-8') if self.RESPONSE_TOKEN not in resp: raise BustimeError("The Bustime API returned an invalid response: {}".format(resp)) elif self.ERROR_TOKEN in resp: return self.errorhandle(resp) else: if self.format == 'json': return xmltodict.parse(resp)[self.RESPONSE_TOKEN] elif self.format == 'xml': return resp def systemtime(self): """ Get the API's official time (local, eastern). Arguments: none. Response: `tm`: "Date and time is represented in the following format: YYYYMMDD HH:MM:SS." http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=time.jsp """ return self.response(self.endpoint('SYSTIME')) def vehicles(self, vid=None, rt=None): """ Get busses by route or by vehicle ID. Arguments: either `vid`: "Set of one or more vehicle IDs whose location should be returned." Maximum of 10 `vid`s, either in a comma-separated list or an iterable. `rt`: "Set of one or more route designators for which matching vehicles should be returned." Maximum of 10 routes, either in a comma-separated list or an iterable. Response: `vehicle`: (vehicle container) contains list of `vid`: bus # `tmstmp`: local date/time of vehicle update `lat`, `lon`: position `hdg`: vehicle heading (e.g., 0: north, 180: south) `pid`: pattern ID of current trip (see `self.geopatterns`) `pdist`: distance into trip `rt`: route (e.g, 88) `des`: bus destinations (e.g., "Penn to Bakery Square") `dly` (optional): True if bus is delayed `spd`: speed in mph `zone`: current zone (usually `None` here) `tablockid`, `tatripid`: unsure, seems internal? http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=vehicles.jsp """ if vid and rt: raise ValueError("The `vid` and `route` parameters cannot be specified simultaneously.") if not (vid or rt): raise ValueError("You must specify either the `vid` or `rt` parameter.") # Turn list into comma separated string if listlike(rt): rt = ",".join( map(str, rt) ) if listlike(vid): vid = ",".join( map(str, vid) ) url = self.endpoint('VEHICLES', dict(vid=vid, rt=rt)) return self.response(url) def routes(self): """ Return a list of routes currently tracked by the API. Arguments: none Response: `route`: (route container) contains list of `rt`: route designator (e.g, P1, 88) `rtnm`: route name (e.g. EAST BUSWAY-ALL STOPS, PENN) `rtclr`: color of route used in map display (e.g. #9900ff), usually unimportant http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=routes.jsp """ return self.response(self.endpoint('ROUTES')) def route_directions(self, rt): """ Return a list of directions for a route. The directions seem to always be INBOUND and OUTBOUND for the busses currently, where INBOUND is towards downtown and OUTBOUND is away from downtown. (No idea if this is going to change.) Arguments: `rt`: route designator Response: list of `dir`: directions served (e.g., INBOUND, OUTBOUND) http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=routeDirections.jsp """ url = self.endpoint('R_DIRECTIONS', dict(rt=rt)) return self.response(url) def stops(self, rt, direction): """ Return a list of stops for a particular route. Arguments: `rt`: route designator `dir`: route direction (INBOUND, OUTBOUND) Response: `stop`: (stop container) contains list of `stpid`: unique ID number for bus stop `stpnm`: stop name (what shows up on the display in the bus, e.g., "Forbes and Murray") `lat`, `lng`: location of stop http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=stops.jsp """ url = self.endpoint('STOPS', dict(rt=rt, dir=direction)) return self.response(url) def geopatterns(self, rt=None, pid=None): """ Returns a set of geographic points that make up a particular routing ('pattern', in API terminology) for a bus route. A bus route can have more than one routing. Arguments: either `rt`: route designator or `pid`: comma-separated list or an iterable of pattern IDs (max 10) Response: `ptr`: (pattern container) contains list of `pid`: pattern ID `ln`: length of pattern in feet `rtdir`: route direction (see `self.route_directions`) `pt`: geo points, contains list of `seq`: position of point in pattern `typ`: 'S' = stop, 'W' = waypoint -> if `typ` is a stop, will contain: `stpid`, `stpnm`, `pdist` (see `self.stops`) `lat`, `lon`: position of point http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=patterns.jsp """ if rt and pid: raise ValueError("The `rt` and `pid` parameters cannot be specified simultaneously.") if not (rt or pid): ValueError("You must specify either the `rt` or `pid` parameter.") if listlike(pid): pid = ",".join(pid) url = self.endpoint("R_GEO", dict(rt=rt, pid=pid)) return self._lru_geopatterns(url) def _lru_geopatterns(self, url): # @lru_cache doesn't support kwargs so this is a bit of a workaround... return self.response(url) def predictions(self, stpid="", rt="", vid="", maxpredictions=""): """ Retrieve predictions for 1+ stops or 1+ vehicles. Arguments: `stpid`: unique ID number for bus stop (single or comma-seperated list or iterable) or `vid`: vehicle ID number (single or comma-seperated list or iterable) or `stpid` and `rt` `maxpredictions` (optional): limit number of predictions returned Response: `prd`: (prediction container) contains list of `tmstp`: when prediction was generated `typ`: prediction type ('A' = arrival, 'D' = departure) `stpid`: stop ID for prediction `stpnm`: stop name for prediction `vid`: vehicle ID for prediction `dstp`: vehicle distance to stop (feet) `rt`: bus route `des`: bus destination `prdtm`: ETA/ETD `dly`: True if bus delayed `tablockid`, `tatripid`, `zone`: internal, see `self.vehicles` http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=predictions.jsp """ if (stpid and vid) or (rt and vid): raise ValueError("These parameters cannot be specified simultaneously.") elif not (stpid or rt or vid): raise ValueError("You must specify a parameter.") if listlike(stpid): stpid = ",".join(stpid) if listlike(rt): rt = ",".join(rt) if listlike(vid): vid = ",".join(vid) if stpid or (rt and stpid) or vid: url = self.endpoint('PREDICTION', dict(rt=rt, stpid=stpid, vid=vid, top=maxpredictions)) return self.response(url) def bulletins(self, rt="", rtdir="", stpid=""): """ Return list of service alerts ('bulletins') for a route or stop. Arguments: `rt`: route designator or `stpid`: bus stop number or (`rt` and `rtdir`) or (`rt` and `rtdir` and `stpid`) Response: `sb`: (bulletin container) contains list of `nm`: bulletin name/ID `sbj`: bulletin subject `dtl`: full text and/or `brf`: short text `prty`: priority (high, medium, low) `srvc`: (routes bulletin applies to) contains list of `rt`: route designator `rtdir`: route direction `stpid`: bus stop ID number `stpnm`: bus stop name http://realtime.portauthority.org/bustime/apidoc/v1/main.jsp?section=serviceBulletins.jsp """ if not (rt or stpid) or (rtdir and not (rt or stpid)): raise ValueError("You must specify a parameter.") if listlike(stpid): stpid = ",".join(stpid) if listlike(rt): rt = ",".join(rt) url = self.endpoint('BULLETINS', dict(rt=rt, rtdir=rtdir, stpid=stpid)) return self.response(url) def detournotices(self, rt): from BeautifulSoup import BeautifulSoup from datetime import datetime URL = "http://www.portauthority.org/paac/apps/detoursdnn/pgDetours.asp?mode=results&s=Route&Type=Detour" _strptime = "%m/%d/%Y" rt = str(rt) formdata = { "txtRoute": "0"*(4-len(rt)) + rt, "submit1": "Search" } data = requests.post(URL, data=formdata) if "No Detours are running" in data.content: return False else: detours = [] parser = BeautifulSoup(data.content) titles = parser.findAll('td', attrs={'colspan': '2'})[0:-1] dates = parser.findAll('td', attrs={'colspan': '1', 'class': 'RegularFormText'}) notices = zip(titles, dates) for rawTitle, rawDates in notices: title = rawTitle.p.a.text memoID = dict(rawTitle.p.a.attrs)['href'].split("MemoID=")[-1] fromDate, toDate = rawDates.p.text.replace('&nbsp;', ' ').replace('\r', '').replace('\n', '').replace('\t', '').split(' to ') try: fromDate = datetime.strptime(fromDate, _strptime) except: None try: toDate = datetime.strptime(toDate, _strptime) except: None detour = DetourNotice(memoID, title, fromDate, toDate) detours.append(detour) return detours
aacanakin/glim
glim/utils.py
import_source
python
def import_source(module, path, pass_errors=False): try: m = imp.load_source(module, path) return m except Exception as e: return None
Function imports a module given full path Args ---- module (string): the module name path (string): the full path of module pass_errors(boolean): the switch for function to skip errors or not. Returns ------- module (module): the module object. Raises ------ e (Exception): any kind of exceptions during importing.
train
https://github.com/aacanakin/glim/blob/71a20ac149a1292c0d6c1dc7414985ea51854f7a/glim/utils.py#L17-L40
null
""" The utils module is a bunch of functions used inside the implementation of glim framework. """ import shutil import os import traceback import imp from exception import FolderExistsError # function performs an import given full path & module # function performs a parametric import statement, returns None if not found def import_module(module, pass_errors=False): """ Function imports a module given module name Args ---- module (string): the module name pass_errors(boolean): the switch for function to skip errors or not. Returns ------- module (module): the module object. Raises ------ exception (Exception): any kind of exceptions during importing. import_error(ImportError): import errors during importing. Note: pass_errors switch will not pass any errors other than ImportError """ frm = module.split('.') try: m = __import__(module, fromlist=[frm[1]]) return m except ImportError as e: if pass_errors: return None else: print(traceback.format_exc()) return None except Exception as e: print(traceback.format_exc()) return None # function performs a recursive copy of files and folders in the filesystem def copytree(src, dst, symlinks=False, ignore=None): """ Function recursively copies from directory to directory. Args ---- src (string): the full path of source directory dst (string): the full path of destination directory symlinks (boolean): the switch for tracking symlinks ignore (list): the ignore list """ if not os.path.exists(dst): os.mkdir(dst) try: for item in os.listdir(src): s = os.path.join(src, item) d = os.path.join(dst, item) if os.path.isdir(s): shutil.copytree(s, d, symlinks, ignore) else: shutil.copy2(s, d) except Exception as e: raise FolderExistsError("Folder already exists in %s" % dst) def empty(key, dict): """ Function determines if the dict key exists or it is empty Args ---- key (string): the dict key dict (dict): the dict to be searched """ if key in dict.keys(): if dict[key]: return False return True
aacanakin/glim
glim/utils.py
import_module
python
def import_module(module, pass_errors=False): frm = module.split('.') try: m = __import__(module, fromlist=[frm[1]]) return m except ImportError as e: if pass_errors: return None else: print(traceback.format_exc()) return None except Exception as e: print(traceback.format_exc()) return None
Function imports a module given module name Args ---- module (string): the module name pass_errors(boolean): the switch for function to skip errors or not. Returns ------- module (module): the module object. Raises ------ exception (Exception): any kind of exceptions during importing. import_error(ImportError): import errors during importing. Note: pass_errors switch will not pass any errors other than ImportError
train
https://github.com/aacanakin/glim/blob/71a20ac149a1292c0d6c1dc7414985ea51854f7a/glim/utils.py#L45-L79
null
""" The utils module is a bunch of functions used inside the implementation of glim framework. """ import shutil import os import traceback import imp from exception import FolderExistsError # function performs an import given full path & module def import_source(module, path, pass_errors=False): """ Function imports a module given full path Args ---- module (string): the module name path (string): the full path of module pass_errors(boolean): the switch for function to skip errors or not. Returns ------- module (module): the module object. Raises ------ e (Exception): any kind of exceptions during importing. """ try: m = imp.load_source(module, path) return m except Exception as e: return None # function performs a parametric import statement, returns None if not found # function performs a recursive copy of files and folders in the filesystem def copytree(src, dst, symlinks=False, ignore=None): """ Function recursively copies from directory to directory. Args ---- src (string): the full path of source directory dst (string): the full path of destination directory symlinks (boolean): the switch for tracking symlinks ignore (list): the ignore list """ if not os.path.exists(dst): os.mkdir(dst) try: for item in os.listdir(src): s = os.path.join(src, item) d = os.path.join(dst, item) if os.path.isdir(s): shutil.copytree(s, d, symlinks, ignore) else: shutil.copy2(s, d) except Exception as e: raise FolderExistsError("Folder already exists in %s" % dst) def empty(key, dict): """ Function determines if the dict key exists or it is empty Args ---- key (string): the dict key dict (dict): the dict to be searched """ if key in dict.keys(): if dict[key]: return False return True
aacanakin/glim
glim/utils.py
copytree
python
def copytree(src, dst, symlinks=False, ignore=None): if not os.path.exists(dst): os.mkdir(dst) try: for item in os.listdir(src): s = os.path.join(src, item) d = os.path.join(dst, item) if os.path.isdir(s): shutil.copytree(s, d, symlinks, ignore) else: shutil.copy2(s, d) except Exception as e: raise FolderExistsError("Folder already exists in %s" % dst)
Function recursively copies from directory to directory. Args ---- src (string): the full path of source directory dst (string): the full path of destination directory symlinks (boolean): the switch for tracking symlinks ignore (list): the ignore list
train
https://github.com/aacanakin/glim/blob/71a20ac149a1292c0d6c1dc7414985ea51854f7a/glim/utils.py#L84-L106
null
""" The utils module is a bunch of functions used inside the implementation of glim framework. """ import shutil import os import traceback import imp from exception import FolderExistsError # function performs an import given full path & module def import_source(module, path, pass_errors=False): """ Function imports a module given full path Args ---- module (string): the module name path (string): the full path of module pass_errors(boolean): the switch for function to skip errors or not. Returns ------- module (module): the module object. Raises ------ e (Exception): any kind of exceptions during importing. """ try: m = imp.load_source(module, path) return m except Exception as e: return None # function performs a parametric import statement, returns None if not found def import_module(module, pass_errors=False): """ Function imports a module given module name Args ---- module (string): the module name pass_errors(boolean): the switch for function to skip errors or not. Returns ------- module (module): the module object. Raises ------ exception (Exception): any kind of exceptions during importing. import_error(ImportError): import errors during importing. Note: pass_errors switch will not pass any errors other than ImportError """ frm = module.split('.') try: m = __import__(module, fromlist=[frm[1]]) return m except ImportError as e: if pass_errors: return None else: print(traceback.format_exc()) return None except Exception as e: print(traceback.format_exc()) return None # function performs a recursive copy of files and folders in the filesystem def empty(key, dict): """ Function determines if the dict key exists or it is empty Args ---- key (string): the dict key dict (dict): the dict to be searched """ if key in dict.keys(): if dict[key]: return False return True
aacanakin/glim
glim/utils.py
empty
python
def empty(key, dict): if key in dict.keys(): if dict[key]: return False return True
Function determines if the dict key exists or it is empty Args ---- key (string): the dict key dict (dict): the dict to be searched
train
https://github.com/aacanakin/glim/blob/71a20ac149a1292c0d6c1dc7414985ea51854f7a/glim/utils.py#L109-L121
null
""" The utils module is a bunch of functions used inside the implementation of glim framework. """ import shutil import os import traceback import imp from exception import FolderExistsError # function performs an import given full path & module def import_source(module, path, pass_errors=False): """ Function imports a module given full path Args ---- module (string): the module name path (string): the full path of module pass_errors(boolean): the switch for function to skip errors or not. Returns ------- module (module): the module object. Raises ------ e (Exception): any kind of exceptions during importing. """ try: m = imp.load_source(module, path) return m except Exception as e: return None # function performs a parametric import statement, returns None if not found def import_module(module, pass_errors=False): """ Function imports a module given module name Args ---- module (string): the module name pass_errors(boolean): the switch for function to skip errors or not. Returns ------- module (module): the module object. Raises ------ exception (Exception): any kind of exceptions during importing. import_error(ImportError): import errors during importing. Note: pass_errors switch will not pass any errors other than ImportError """ frm = module.split('.') try: m = __import__(module, fromlist=[frm[1]]) return m except ImportError as e: if pass_errors: return None else: print(traceback.format_exc()) return None except Exception as e: print(traceback.format_exc()) return None # function performs a recursive copy of files and folders in the filesystem def copytree(src, dst, symlinks=False, ignore=None): """ Function recursively copies from directory to directory. Args ---- src (string): the full path of source directory dst (string): the full path of destination directory symlinks (boolean): the switch for tracking symlinks ignore (list): the ignore list """ if not os.path.exists(dst): os.mkdir(dst) try: for item in os.listdir(src): s = os.path.join(src, item) d = os.path.join(dst, item) if os.path.isdir(s): shutil.copytree(s, d, symlinks, ignore) else: shutil.copy2(s, d) except Exception as e: raise FolderExistsError("Folder already exists in %s" % dst)
aacanakin/glim
glim/core.py
Registry.get
python
def get(self, key): try: layers = key.split('.') value = self.registrar for key in layers: value = value[key] return value except: return None
Function deeply gets the key with "." notation Args ---- key (string): A key with the "." notation. Returns ------- reg (unknown type): Returns a dict or a primitive type.
train
https://github.com/aacanakin/glim/blob/71a20ac149a1292c0d6c1dc7414985ea51854f7a/glim/core.py#L34-L54
null
class Registry(object): """ This class is basically a dictionary supercharged with useful functions. Attributes ---------- registrar (dict): A registrar to hold a generic configuration of a class. Usage ----- config = { 'a' : 'b', 'c' : { 'd' : 'e' } } reg = Registry(config) reg.get('a') # returns b reg.get('c.d') # returns e reg.set('f', 'g') # sets 'f' key of dict reg.get('f') # returns g """ def __init__(self, registrar): self.registrar = registrar def set(self, key, value): """ Function deeply sets the key with "." notation Args ---- key (string): A key with the "." notation. value (unknown type): A dict or a primitive type. """ target = self.registrar for element in key.split('.')[:-1]: target = target.setdefault(element, dict()) target[key.split(".")[-1]] = value def flush(self): """ Function clears the registrar Note: After this function is called, all of your data in your registry will be lost. So, use this smartly. """ self.registrar.clear() def update(self, registrar): """ Function batch updates the registry. This function is an alias of dict.update() Args ---- registrar (dict): A dict of configuration. Note: After this function is called, all of your data may be overriden and lost by the registrar you passed. So, use this smartly. """ self.registrar.update(registrar) def all(self): """ Function returns all the data in registrar. Returns ------- registrar (dict): The current registry in the class. """ return self.registrar def __str__(self): return self.registrar
aacanakin/glim
glim/core.py
Registry.set
python
def set(self, key, value): target = self.registrar for element in key.split('.')[:-1]: target = target.setdefault(element, dict()) target[key.split(".")[-1]] = value
Function deeply sets the key with "." notation Args ---- key (string): A key with the "." notation. value (unknown type): A dict or a primitive type.
train
https://github.com/aacanakin/glim/blob/71a20ac149a1292c0d6c1dc7414985ea51854f7a/glim/core.py#L56-L68
null
class Registry(object): """ This class is basically a dictionary supercharged with useful functions. Attributes ---------- registrar (dict): A registrar to hold a generic configuration of a class. Usage ----- config = { 'a' : 'b', 'c' : { 'd' : 'e' } } reg = Registry(config) reg.get('a') # returns b reg.get('c.d') # returns e reg.set('f', 'g') # sets 'f' key of dict reg.get('f') # returns g """ def __init__(self, registrar): self.registrar = registrar def get(self, key): """ Function deeply gets the key with "." notation Args ---- key (string): A key with the "." notation. Returns ------- reg (unknown type): Returns a dict or a primitive type. """ try: layers = key.split('.') value = self.registrar for key in layers: value = value[key] return value except: return None def flush(self): """ Function clears the registrar Note: After this function is called, all of your data in your registry will be lost. So, use this smartly. """ self.registrar.clear() def update(self, registrar): """ Function batch updates the registry. This function is an alias of dict.update() Args ---- registrar (dict): A dict of configuration. Note: After this function is called, all of your data may be overriden and lost by the registrar you passed. So, use this smartly. """ self.registrar.update(registrar) def all(self): """ Function returns all the data in registrar. Returns ------- registrar (dict): The current registry in the class. """ return self.registrar def __str__(self): return self.registrar
aacanakin/glim
glim/core.py
Facade.boot
python
def boot(cls, *args, **kwargs): if cls.accessor is not None: if cls.instance is None: cls.instance = cls.accessor(*args, **kwargs)
Function creates the instance of accessor with dynamic positional & keyword arguments. Args ---- args (positional arguments): the positional arguments that are passed to the class of accessor. kwargs (keyword arguments): the keyword arguments that are passed to the class of accessor.
train
https://github.com/aacanakin/glim/blob/71a20ac149a1292c0d6c1dc7414985ea51854f7a/glim/core.py#L150-L164
null
class Facade(MetaMixin): """ This magical class is basically a singleton implementation without using any kind of singleton :) It's used to register glim framework instances for only once and reach the class without disturbing readability. """ instance = None # accessor is the object which will be registered during runtime accessor = None @classmethod @classmethod def register(cls, config={}): """ This function is basically a shortcut of boot for accessors that have only the config dict argument. Args ---- config (dict): the configuration dictionary """ if cls.accessor is not None: if cls.instance is None: cls.instance = cls.accessor(config) @classmethod def _get(cls): """Function returns the instance""" return cls.instance