def get_task_list(self): def get_time_from_interval(td_object): seconds = int(td_object.total_seconds()) periods = [('year', 60 * 60 * 24 * 365), ('month', 60 * 60 * 24 * 30), ('day', 60 * 60 * 24), ('hour', 60 * 60), ('minute', 60), ('second', 1)] strings = [] for period_name, period_seconds in periods: if seconds > period_seconds: period_value, seconds = divmod(seconds, period_seconds) has_s = 's' if period_value > 1 else '' strings.append("%s %s%s" % (period_value, period_name, has_s)) return ", ".join(strings) def get_time_from_cron(cron): year = str(cron[0]) if year == "2100": return "Never" day = str(cron[4]) hour = str(cron[5]) if day == "*": text = "everyday" else: text = "every " + day_name[int(day)] if hour != "*": text += " at " + hour + ":00" return text task_list = [] for job in self.aps_scheduler.get_jobs(): if isinstance(job.trigger, CronTrigger): if str(job.trigger.__getstate__()['fields'][0]) == "2100": next_run = 'Never' else: next_run = pretty.date( job.next_run_time.replace(tzinfo=None)) else: next_run = pretty.date(job.next_run_time.replace(tzinfo=None)) if isinstance(job.trigger, IntervalTrigger): interval = "every " + get_time_from_interval( job.trigger.__getstate__()['interval']) task_list.append([job.name, interval, next_run, job.id]) elif isinstance(job.trigger, CronTrigger): task_list.append([ job.name, get_time_from_cron(job.trigger.fields), next_run, job.id ]) return task_list
def toString( self ): who = [ "@%s" % i for i in self.who.split( " " ) ] who = ",".join( who ) when = self.when.replace(tzinfo=None) s = "#who %s #what %s #where %s #when %s" % ( who, self.what, self.where, pretty.date( when ) ) return s
def convert_image_dict(a): """ Drop some keys and change some values to pretty-print image dict. """ b = {} for k, v in a.items(): if k not in ['RepoTags', 'RepoDigests', 'Labels', 'Size']: b[k] = v if k == 'Created' and v and re_digits.search(str(v)): b[k] = pretty.date(v) if k == 'VirtualSize': b[k] = filesize(v) # If we have more than one repo tag, return as many dicts if a.get('RepoTags', None) is None: a['RepoTags'] = ['<none>:<none>'] for rt in a['RepoTags']: repo, tag = rt.rsplit(':', 1) c = {} c.update(b) c['Repository'] = repo c['Tag'] = tag yield c
def search(text,limit,off): url='https://www.devrant.io/api/devrant/search?app=3&term='+str(text)+'&limit'+str(limit) response = requests.get(url) print response tags = [] data = response.json() search_dic = {} search_list = [] for rant in range(len(data['results']))[off:limit]: search_dic = {} search_dic['name'] = data['results'][rant]['user_username'] search_dic['img'] = data['results'][rant]['attached_image'] or {"url":"#"} search_dic['image'] = str(search_dic['img']['url'] or '#') tags = data['results'][rant]['tags'] search_dic['tags'] = tags search_dic['comments'] = str(data['results'][rant]['num_comments'] or 0) search_dic['text'] = str(data['results'][rant]['text'] or None) search_dic['score'] = data['results'][rant]['score'] search_dic['time'] = pretty.date(data['results'][rant]['created_time']) search_dic['id'] = data['results'][rant]['id'] search_dic['user_id'] = data['results'][rant]['user_id'] search_dic['user_score'] = data['results'][rant]['user_score'] search_list.insert(rant,search_dic) return search_list,limit
def get(self): start = request.args.get('start') or 0 length = request.args.get('length') or -1 data = TableBlacklist.select(TableShows.title.alias('seriesTitle'), TableEpisodes.season.concat('x').concat(TableEpisodes.episode).alias('episode_number'), TableEpisodes.title.alias('episodeTitle'), TableEpisodes.sonarrSeriesId, TableBlacklist.provider, TableBlacklist.subs_id, TableBlacklist.language, TableBlacklist.timestamp)\ .join(TableEpisodes, on=(TableBlacklist.sonarr_episode_id == TableEpisodes.sonarrEpisodeId))\ .join(TableShows, on=(TableBlacklist.sonarr_series_id == TableShows.sonarrSeriesId))\ .order_by(TableBlacklist.timestamp.desc())\ .limit(length)\ .offset(start)\ .dicts() data = list(data) for item in data: # Make timestamp pretty item["parsed_timestamp"] = datetime.datetime.fromtimestamp( int(item['timestamp'])).strftime('%x %X') item.update({ 'timestamp': pretty.date(datetime.datetime.fromtimestamp(item['timestamp'])) }) postprocessEpisode(item) return jsonify(data=data)
def _dateInWords(d): import pretty from datetime import datetime return pretty.date( datetime.strptime(d, '%Y-%m-%d %H:%M:%S') )
def unban(self, event, match): groupdict = match.groupdict() target = groupdict['nick'] delay = groupdict['timestr'] channel = event.channel if delay: try: delay = parse_time(delay) except ValueError as e: event.reply(str(e)) return try: hostmask = (yield self._nick_to_hostmask(target)) except ircutil.NoSuchNick: event.reply( "There is no user by that nick on the network. " "Try specifying a full hostmask. Use “/mode +b” to see the channel ban list" .format(target, )) return except ValueError: event.reply( "Malformed hostmask. Hostmask syntax is <nick>!<username>@<host>", direct=True, notice=True) return try: yield self._do_modederequest(channel, 'b', hostmask, delay) except ircop.OpFailed as e: event.reply(str(e)) if delay: event.reply("Unbanning {}".format( pretty.date(int(time.time() + delay))))
def unban(self, event, match): groupdict = match.groupdict() target = groupdict["nick"] delay = groupdict["timestr"] channel = event.channel if delay: try: delay = parse_time(delay) except ValueError as e: event.reply(str(e)) return try: hostmask = (yield self._nick_to_hostmask(target)) except ircutil.NoSuchNick: event.reply( "There is no user by that nick on the network. " "Try specifying a full hostmask. Use “/mode +b” to see the channel ban list".format(target) ) return except ValueError: event.reply("Malformed hostmask. Hostmask syntax is <nick>!<username>@<host>", direct=True, notice=True) return try: yield self._do_modederequest(channel, "b", hostmask, delay) except ircop.OpFailed as e: event.reply(str(e)) if delay: event.reply("Unbanning {}".format(pretty.date(int(time.time() + delay))))
def get_pretty_datetime_format(datetime_or_utc_sec): if isinstance(datetime_or_utc_sec, datetime.datetime): ts = datetime_or_utc_sec else: ts = datetime.datetime.fromtimestamp(float(datetime_or_utc_sec)) now = datetime.datetime.now() delta = now - ts if delta.days > 1: month = ts.strftime('%h') day = str(ts.day).lstrip('0') year = str(ts.year) since = "%s %s, %s" % (month, day, year) else: since = pretty.date(now-delta) if delta.days > 0: hour = ts.strftime("%I").lstrip('0') minute = ts.strftime("%M") locale = ts.strftime("%p").lower() time_str = "%s:%s%s" % (hour, minute, locale) since = since.title() + " at " + time_str
def rants(text,limit,skip): #'weekly': # url = 'https://www.devrant.io/api/devrant/weekly-rants?app=3' url='https://www.devrant.io/api/devrant/rants?app=3&limit='+str(limit)+'&skip='+str(skip)+'&sort='+text response = requests.get(url) print response tags = [] rant_list = [] data = response.json() for rant in range(len(data['rants'])): rant_dic = {} rant_dic['name'] = data['rants'][rant]['user_username'] rant_dic['img'] = data['rants'][rant]['attached_image'] or {"url":"#"} rant_dic['image'] = str(rant_dic['img']['url'] or '#') tags = data['rants'][rant]['tags'] rant_dic['tags'] = tags rant_dic['comments'] = str(data['rants'][rant]['num_comments'] or 0) rant_dic['text'] = str(data['rants'][rant]['text'] or None) rant_dic['score'] = data['rants'][rant]['score'] rant_dic['time'] = pretty.date(data['rants'][rant]['created_time']) rant_dic['id'] = data['rants'][rant]['id'] rant_dic['user_id'] = data['rants'][rant]['user_id'] rant_dic['user_score'] = data['rants'][rant]['user_score'] rant_list.insert(rant,rant_dic) return rant_list,skip
def containers(self, *_, **kwargs): """ Return the list of containers. Equivalent of docker ps. :return: list of dicts """ # Truncate by default. if 'trunc' in kwargs and kwargs['trunc'] is None: kwargs['trunc'] = True csdict = self.instance.containers(**kwargs) if len(csdict) > 0: if 'quiet' not in kwargs or not kwargs['quiet']: # Container names start with /. # Let's strip this for readability. for i in range(len(csdict)): csdict[i]['Names'] = list(map( lambda x: x.lstrip('/'), csdict[i]['Names'])) csdict[i]['Created'] = pretty.date(csdict[i]['Created']) if 'Labels' in csdict[i]: del csdict[i]['Labels'] return csdict else: return ['There are no containers to list.']
def get(self): start = request.args.get('start') or 0 length = request.args.get('length') or -1 data = TableBlacklistMovie.select(TableMovies.title, TableMovies.radarrId, TableBlacklistMovie.provider, TableBlacklistMovie.subs_id, TableBlacklistMovie.language, TableBlacklistMovie.timestamp)\ .join(TableMovies, on=(TableBlacklistMovie.radarr_id == TableMovies.radarrId))\ .order_by(TableBlacklistMovie.timestamp.desc())\ .limit(length)\ .offset(start)\ .dicts() data = list(data) for item in data: postprocessMovie(item) # Make timestamp pretty item["parsed_timestamp"] = datetime.datetime.fromtimestamp(int(item['timestamp'])).strftime('%x %X') item.update({'timestamp': pretty.date(datetime.datetime.fromtimestamp(item['timestamp']))}) return jsonify(data=data)
def list_throttled_providers(): update_throttled_provider() throttled_providers = [] providers = get_array_from(settings.general.enabled_providers) for provider in providers: reason, until, throttle_desc = tp.get(provider, (None, None, None)) throttled_providers.append([provider, reason, pretty.date(until)]) return throttled_providers
def list_throttled_providers(): update_throttled_provider() throttled_providers = [] if settings.general.enabled_providers: for provider in settings.general.enabled_providers.lower().split(','): reason, until, throttle_desc = tp.get(provider, (None, None, None)) throttled_providers.append([provider, reason, pretty.date(until)]) return throttled_providers
def list_throttled_providers(): update_throttled_provider() throttled_providers = [] existing_providers = provider_registry.names() providers = [x for x in get_array_from(settings.general.enabled_providers) if x in existing_providers] for provider in providers: reason, until, throttle_desc = tp.get(provider, (None, None, None)) throttled_providers.append([provider, reason, pretty.date(until)]) return throttled_providers
def pretty_ents(inp): import pretty, datetime outa = [] for ent in inp.entries: username = ent.author[ent.author.find('(')+1:ent.author.find(')')] thistime = datetime.datetime.fromtimestamp(time.mktime(ent.updated_parsed)) prettytime = pretty.date(thistime) form = 'Leaky Bukkit: %s (%s) - %s - %s' % (ent.title, username, prettytime, ent.links[0].url) outa.append(form) return outa
def format_datetime(value, format='medium'): if format == 'full': format = "EEEE, d. MMMM y 'at' HH:mm" elif format == 'medium': format = "EE dd.MM.y HH:mm" elif format == 'pretty': now = datetime.now() delta = now - value return pretty.date(now - delta) return babel_format_datetime(value, format)
def mode(self, event, match): channel = event.channel gd = match.groupdict() mode = gd["mode"] param = gd["param"] timespec = gd["timespec"] if timespec: try: time_to_wait = parse_time(timespec) except ValueError as e: event.reply(e) return if timespec.startswith("in") or timespec.startswith("at"): # 'in' or 'at' indicate this is when we want to do the mode. as # opposed to 'do the mode until/for <time> and then revert it' self._set_timer(time_to_wait, param, channel, mode) event.reply( "Doing a {0}{1} {2}".format( mode, " " + param if param else "", pretty.date(int(time.time() + time_to_wait)) ) ) return try: yield self.transport.issue_request("ircop.mode", channel, mode, param) except (ircop.OpFailed, ValueError) as e: event.reply(str(e)) return if timespec: reversemode = {"-": "+", "+": "-"}[mode[0]] + mode[1] self._set_timer(time_to_wait, param, channel, reversemode) event.reply( "Doing a {0}{1} {2}".format( reversemode, " " + param if param else "", pretty.date(int(time.time() + time_to_wait)) ), direct=True, notice=True, )
def mode(self, event, match): channel = event.channel gd = match.groupdict() mode = gd['mode'] param = gd['param'] timespec = gd['timespec'] if timespec: try: time_to_wait = parse_time(timespec) except ValueError as e: event.reply(e) return if timespec.startswith("in") or timespec.startswith("at"): # 'in' or 'at' indicate this is when we want to do the mode. as # opposed to 'do the mode until/for <time> and then revert it' self._set_timer(time_to_wait, param, channel, mode) event.reply(u"Doing a {0}{1} {2}".format( mode, u" " + param if param else "", pretty.date(int(time.time() + time_to_wait)))) return try: yield self.transport.issue_request("ircop.mode", channel, mode, param) except (ircop.OpFailed, ValueError) as e: event.reply(str(e)) return if timespec: reversemode = {"-": "+", "+": "-"}[mode[0]] + mode[1] self._set_timer(time_to_wait, param, channel, reversemode) event.reply(u"Doing a {0}{1} {2}".format( reversemode, u" " + param if param else "", pretty.date(int(time.time() + time_to_wait))), direct=True, notice=True)
def objectify(self, currentUid): response = { 'postId' : self.page.id, 'commentId' : self.id, 'uid' : self.user.id, 'username' : self.user.username, 'userImage' : 'path/image.png', 'body' : self.body, 'date' : pretty.date( localtime( self.created ).replace(tzinfo=None) ), } if self.user.id == currentUid: response['editable'] = True else: response['editable'] = False return response
def quiet(self, event, match): groupdict = match.groupdict() target = groupdict['nick'] duration = groupdict['timestr'] channel = event.channel if duration: try: duration = parse_time(duration) except ValueError as e: # use the default (set below) duration = None if not duration and self.config['defaulttime']: duration = self.config['defaulttime'] try: hostmask = (yield self._nick_to_hostmask(target)) except ircutil.NoSuchNick: event.reply( "There is no user by that nick on the network. " "Try {0}!*@* to quiet anyone with that nick, or specify a full hostmask." .format(target, )) return except ValueError: event.reply( "Malformed hostmask. Hostmask syntax is <nick>!<username>@<host>", direct=True, notice=True) return try: yield self._do_moderequest(channel, 'q', hostmask, duration) except ircop.OpFailed as e: event.reply(str(e)) if duration: event.reply( "Will unquiet {} {}".format( hostmask, # bug: pretty.date doesn't accept floats as timestamps pretty.date(int(time.time() + duration))), direct=True, notice=True) else: event.reply("Warning: no duration given. Quiet will be permanent", direct=True, notice=True)
def get_status(): """Returns a dictionary containing site status information""" notice = get_notice() guests = models.Guest.count() subscribers = models.Subscriber.count() full_path_to_file = path.join(module_directory, "updated.txt") updated_file = open(full_path_to_file, "r") timestamp = datetime.fromtimestamp(float(updated_file.readline())) updated_file.close() updated = date(timestamp) return dict(notice=notice, version=__version__, updated=updated, guests=guests, subscribers=subscribers)
def _timestamp(message, user_timezone): '''Return a dict containing the timestamp in a bunch of formats.''' ts = message['timestamp'] ts_obj = datetime.datetime.fromtimestamp(ts) utc = timezone('UTC') utc_obj = utc.normalize(utc.localize(ts_obj)) localized = utc_obj.astimezone(timezone(user_timezone)) return { 'ago': pretty.date(ts_obj), 'iso': localized.isoformat(), 'usadate': localized.strftime("%m/%d/%Y"), 'fulldate': localized.strftime("%A, %B %d, %Y"), 'time': localized.strftime("%H:%M"), 'epoch': str(ts), }
def _get_activities_(self): session = DBSession() base_query = session.query(Activity)\ .filter_by(user_id=self.session['user_id']) count_unseen = base_query.filter_by(seen_at=None).count() activities = base_query.order_by(Activity.created_at.desc()).limit(5) response = [] for activity in activities: response.append({'message': activity.message, 'unseen': activity.unseen, 'absolute_path': activity.absolute_path, 'created_by': activity.created_by, 'created_at': pretty.date(activity.created_at)}) transaction.commit() return count_unseen, response
def quiet(self, event, match): groupdict = match.groupdict() target = groupdict["nick"] duration = groupdict["timestr"] channel = event.channel if duration: try: duration = parse_time(duration) except ValueError as e: # use the default (set below) duration = None if not duration and self.config["defaulttime"]: duration = self.config["defaulttime"] try: hostmask = (yield self._nick_to_hostmask(target)) except ircutil.NoSuchNick: event.reply( "There is no user by that nick on the network. " "Try {0}!*@* to quiet anyone with that nick, or specify a full hostmask.".format(target) ) return except ValueError: event.reply("Malformed hostmask. Hostmask syntax is <nick>!<username>@<host>", direct=True, notice=True) return try: yield self._do_moderequest(channel, "q", hostmask, duration) except ircop.OpFailed as e: event.reply(str(e)) if duration: event.reply( "Will unquiet {} {}".format( hostmask, # bug: pretty.date doesn't accept floats as timestamps pretty.date(int(time.time() + duration)), ), direct=True, notice=True, ) else: event.reply("Warning: no duration given. Quiet will be permanent", direct=True, notice=True)
def list_containers(client: docker.Client, args, state: dict): containers = client.containers(all=args.all, quiet=args.quiet) if args.pprint: pprint(containers) return if args.json: print(json.dumps(containers, indent=4, sort_keys=True)) return table = [] if args.quiet: headers = () else: headers = ["ID", "NAME", "IMAGE", "CMD", "CREATED", "STATUS", "PORTS"] for container in containers: row = [] table.append(row) if args.quiet: row.append(container['Id']) continue row.append(container['Id'][:12]) row.append(container['Names'][0][1:]) row.append(container['Image']) row.append(container['Command']) created_seconds = container['Created'] created_date = datetime.fromtimestamp(created_seconds) row.append(re.sub(r"\.[0-9]+", '', pretty.date(created_date, short=True))) row.append(container['Status']) ports = "" if 'Ports' in container: ports = ', '.join([_port_string(p) for p in container['Ports']]) row.append(ports) print(tabulate(table, headers=headers, tablefmt="plain"))
def surprise(): url='https://www.devrant.io/api/devrant/rants/surprise?app=3' response = requests.get(url) print response tags = [] data = response.json() surprise_dic = {} surprise_dic['name'] = data['rant']['user_username'] surprise_dic['img'] = data['rant']['attached_image'] or {"url":"#"} surprise_dic['image'] = str(surprise_dic['img']['url'] or '#') tags = data['rant']['tags'] surprise_dic['tags'] = tags surprise_dic['comments'] = str(data['rant']['num_comments'] or 0) surprise_dic['text'] = str(data['rant']['text'] or None) surprise_dic['score'] = data['rant']['score'] surprise_dic['time'] = pretty.date(data['rant']['created_time']) surprise_dic['id'] = data['rant']['id'] surprise_dic['user_id'] = data['rant']['user_id'] surprise_dic['user_score'] = data['rant']['user_score'] return surprise_dic
def convert_image_dict(a): """ Drop some keys and change some values to pretty-print image dict. """ b = {} for k, v in a.items(): if k not in ['RepoTags', 'RepoDigests', 'Labels', 'Size']: b[k] = v if k == 'Created' and v and re_digits.search(str(v)): b[k] = pretty.date(v) if k == 'VirtualSize': b[k] = filesize(v) # If we have more than one repo tag, return as many dicts for rt in a['RepoTags']: repo, tag = rt.rsplit(':', 1) c = {} c.update(b) c['Repository'] = repo c['Tag'] = tag yield c
def __init__(self, name, address): self.name = name self.address = address try: addr = REPORT_FILES.format(self.address) self.report = json.load(open(addr)) self.error = self.report.get("error", None) dt = datetime.strptime(self.report["date"], '%Y-%m-%d %H:%M') self.report_date = self.report["date"] + " ({})".format( pretty.date(dt)) if self.error: self.uptime = self.error + ": " + self.report.get( "description") self.headers = [] else: self.uptime = self.report["uptime"]["text"] self.headers = [r.keys()[0] for r in monitor.short_reports] except: import sys print sys.exc_info() self.report = None self.uptime = "No report for this server yet" self.report_date = "Unknown" self.headers = [] self.short_reports = [] for header in self.headers: try: report_json = self.report["short_reports"][header] short_report = ShortReport(report_json["value"], report_json["measure"], report_json["text"]) self.short_reports.append(short_report) except: self.short_reports.append( ShortReport(100, "%", "No report for data [{}]".format(header)))
def read_tweets(self, param): nickname = param username = self.app.addressbook.get_twitter_username(nickname.lower()) if not username: self.app.say("Sorry, I cannot find the twitter username") return statuses = self.twitter.get_tweets(username) sentences = [] for status in statuses: # Twitter returns GMT time in the format like this: # Mon Sep 16 06:57:38 +0000 2013 # Python 2.x does not support %z, so converting to "GMT" tweeted_at = datetime.datetime.strptime( status["created_at"].replace("+0000", "GMT"), "%a %b %d %H:%M:%S %Z %Y") tweeted_at = tweeted_at - datetime.timedelta(seconds=time.timezone - 3600 * time.daylight) tweeted_at_pretty = pretty.date(tweeted_at) sentences.append(status["text"]) sentences.append(tweeted_at_pretty) self.app.recite(sentences)
def bans(self, event, match): """A user has issued the bans command, a query to see who is banned and for how long. """ reply = event.reply groupdict = match.groupdict() mask = groupdict['mask'] if not mask: mask = "all" LaterItem = namedtuple("LaterItem", ["channel", "time", "mask", "mode"]) # Filter out all but bans and quiets. also put in a list of namedtuples # so it's easier to work with laters = [ LaterItem(time=int(x[0]), mask=x[1], channel=x[2], mode=x[3]) for x in self.config['laters'] if x[3][1] in "bq" ] # Sort in the order of the namedtuple parameters: by channel and then by time laters.sort() if mask != "all": laters = [x for x in laters if x.mask == mask] if not laters: reply("No pending events for {0}".format(mask)) return for later in laters: when = pretty.date(later.time) reply("In {channel} setting {mode} {mask} {when}".format( channel=later.channel, mode=later.mode, mask=later.mask, when=when))
def bans(self, event, match): """A user has issued the bans command, a query to see who is banned and for how long. """ reply = event.reply groupdict = match.groupdict() mask = groupdict["mask"] if not mask: mask = "all" LaterItem = namedtuple("LaterItem", ["channel", "time", "mask", "mode"]) # Filter out all but bans and quiets. also put in a list of namedtuples # so it's easier to work with laters = [ LaterItem(time=int(x[0]), mask=x[1], channel=x[2], mode=x[3]) for x in self.config["laters"] if x[3][1] in "bq" ] # Sort in the order of the namedtuple parameters: by channel and then by time laters.sort() if mask != "all": laters = [x for x in laters if x.mask == mask] if not laters: reply("No pending events for {0}".format(mask)) return for later in laters: when = pretty.date(later.time) reply( "In {channel} setting {mode} {mask} {when}".format( channel=later.channel, mode=later.mode, mask=later.mask, when=when ) )
def time_ago(klass, time): if isinstance(time, basestring): time = dateutil.parser.parse(time) if time == NEVER: return "Never" else: p = pretty.date(time) p = p.replace(" ago", "") p = p.replace("years", "yr") p = p.replace("year", "yr") p = p.replace("minutes", "min") p = p.replace("seconds", "sec") p = p.replace("second", "sec") p = p.replace("minute", "min") p = p.replace("hours", "hr") p = p.replace("hour", "hr") p = p.replace("days", "d") p = p.replace("day", "d") p = p.replace("weeks", "wk") p = p.replace("week", "wk") p = p.replace("months", "mth") p = p.replace("month", "mth") return p
def containers(self, *_, **kwargs): """ Return the list of containers. Equivalent of docker ps. :return: list of dicts """ # Truncate by default. if 'trunc' in kwargs and kwargs['trunc'] is None: kwargs['trunc'] = True def format_names(names): """ Container names start with /. Let's strip this for readability. """ if isinstance(names, list): formatted = [] for name in names: if isinstance(name, six.string_types): formatted.append(name.lstrip('/')) else: formatted.append(name) return formatted return names csdict = self.instance.containers(**kwargs) if len(csdict) > 0: if 'quiet' not in kwargs or not kwargs['quiet']: for i in range(len(csdict)): csdict[i]['Names'] = format_names(csdict[i]['Names']) csdict[i]['Created'] = pretty.date(csdict[i]['Created']) return csdict else: return ['There are no containers to list.']
def containers(self, *_, **kwargs): """ Return the list of containers. Equivalent of docker ps. :return: list of dicts """ # Truncate by default. if 'trunc' in kwargs and kwargs['trunc'] is None: kwargs['trunc'] = True def format_names(names): """ Container names start with /. Let's strip this for readability. """ if isinstance(names, list): formatted = [] for name in names: if isinstance(name, basestring): formatted.append(name.lstrip('/')) else: formatted.append(name) return formatted return names csdict = self.instance.containers(**kwargs) if len(csdict) > 0: if 'quiet' not in kwargs or not kwargs['quiet']: for i in range(len(csdict)): csdict[i]['Names'] = format_names(csdict[i]['Names']) csdict[i]['Created'] = pretty.date(csdict[i]['Created']) return csdict else: return ['There are no containers to list.']
def default(self, country='no', bracket=1, arg3=None,arg4=None, **kwargs): try: if (country == 'admin'): #return self.admin(bracket,arg3,arg4) return self.admin(bracket,arg3,arg4,**kwargs) elif (country == 'faq'): mytemplate = Template(filename="%s/frontend/faq.html" % self.base, input_encoding='utf-8', output_encoding='utf-8') return mytemplate.render() elif (bracket == 'achievements'): rows = self.sc2.achievement_ladder(country) data = [] for row in rows: (nrank, player, ap) = (row[0], row[1], row[2]) aPlayer = { 'nrank' : nrank, 'player' : player, 'ap' : ap } data.append(aPlayer) mytemplate = Template(filename="%s/frontend/achievement.html" % self.base, input_encoding='utf-8', output_encoding='utf-8', default_filters=['decode.utf8']) return mytemplate.render(data=data, crawling=os.path.isfile("/tmp/daemon-sc2ladder.pid")) elif (country == 'graphs'): return self.graphs(bracket,arg3, **kwargs) elif (country == 'cup'): return self.cup(**kwargs) else: try: bracket = int(bracket) except ValueError: return None if(bracket<1 or bracket>4): return None query = "select \ array_to_string(array_agg(p.nick), ',') as players, array_to_string(array_agg(p.bnet_id), ',') as playerids, array_to_string(array_agg(tp.fav_race), ',') as fav_race,array_to_string(array_agg(p.last_updated), ',') as last_updated, array_to_string(array_agg(p.cronjob), ',') as cronjob, s2.wins, s2.losses, s2.points, s2.national_rank, s2.region_rank, s2.bracket, s2.teamid, s2.division_id, s2.division_rank, s2.is_random, s2.league, s2.points_adj, s2.world_rank \ FROM \ ( \ SELECT \ rank() OVER(ORDER BY t.league,t.points desc) AS national_rank, t.bracket,t.division_id, t.division_rank, t.is_random, t.league, t.losses, t.wins, t.points, t.region_rank, t.world_rank, t.teamid, t.points_adj \ FROM \ ( \ select \ distinct on (t.teamid) \ t.teamid, t.bracket,t.division_id, t.division_rank, t.is_random, t.league, t.losses, t.wins, t.points, t.region_rank,t.world_rank, t.points_adj \ FROM \ team t \ ORDER BY \ t.teamid \ ) as t \ JOIN \ teamplayer tp \ ON (t.teamid = tp.teamid AND t.bracket=%i) \ JOIN \ player p \ ON (tp.playerid = p.playerid) \ GROUP BY \ t.teamid,p.country,t.bracket,t.division_id, t.division_rank, t.is_random, t.league, t.losses, t.wins, t.points, t.region_rank,t.world_rank, t.points_adj \ HAVING \ count(p.country) = %i AND p.country = '%s' \ ) as s2 \ JOIN \ teamplayer tp \ ON (s2.teamid = tp.teamid) \ JOIN \ player p \ ON (tp.playerid = p.playerid) \ WHERE \ s2.teamid in \ ( \ select \ t.teamid \ from \ team t \ JOIN \ teamplayer tp \ ON (t.teamid = tp.teamid AND t.bracket=%i) \ JOIN \ player p \ ON (tp.playerid = p.playerid) \ GROUP BY \ t.teamid,p.country \ HAVING \ count(p.country) = %i AND p.country = '%s' \ ) \ GROUP by \ s2.wins, s2.losses, s2.points, s2.national_rank, s2.region_rank,s2.world_rank, s2.bracket, s2.teamid, s2.division_id, s2.division_rank, s2.is_random, s2.league, s2.points_adj \ ORDER BY \ national_rank asc" % (bracket, bracket, country , bracket, bracket, country) db_con = psycopg2.connect(database = self.database, host = self.dbhost, user = self.dbuser, password = self.dbpassword) cursor = db_con.cursor() cursor.execute(query) rows = cursor.fetchall() cursor.close() db_con.close() teams = [] for row in rows: #players | wins | losses | points | national_rank | region_rank | bracket | teamid (players, playerids, favteams, last_updated, cronjob, wins, losses, points, nrank, eurank, bracket, teamid, divisionid, divisionrank, israndom, league, pointsadj, wrank) = (row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9], row[10], row[11], row[12], row[13], row[14], row[15], row[16], row[17]) #lu = [datetime.strptime(x.split(".")[0] , '%Y-%m-%d %H:%M:%S') for x in last_updated.split(",")] lu = [dateutil.parser.parse("%s %s" % (x.split(".")[0], "Z")) for x in last_updated.split(",")] cronjoblu = [dateutil.parser.parse("%s %s" % (x.split(".")[0], " CEST")) for x in cronjob.split(",")] #print lu if not pointsadj: pointsadj = 0 if not points: points = 0 newest = datetime(1970,1,1,tzinfo=dateutil.tz.tzutc()) for y in lu: if y > newest: newest = y newestcj = datetime(1970,1,1,tzinfo=dateutil.tz.gettz("Europe/Oslo")) for y in cronjoblu: if y > newestcj: newestcj = y #print lu #test = zip([pretty.date(datetime.strptime(x.split(".")[0], '%Y-%m-%d %H:%M:%S')) for x in lu], [pretty.date(datetime.strptime(y.split(".")[0], '%Y-%m-%d %H:%M:%S')) for y in cronjob.split(",")]) #print test aTeam = { 'teamid' : teamid, 'bracket' : bracket, 'nrank' : nrank, 'eurank' : eurank, 'worldrank' : wrank, 'points' : points, 'wins' : wins, 'losses' : losses, 'divisionid' : divisionid, 'divisionrank' : divisionrank, 'israndom' : israndom, 'league' : self.sc2.league_from_int(league), 'players' : zip(players.split(","),playerids.split(","), favteams.split(",")), 'lastupdated' : zip(lu, cronjoblu), 'cronjoblastupdated' : pretty.date(newestcj), 'humanlastupdated' : pretty.date(newest.astimezone(dateutil.tz.gettz("Europe/Oslo"))), 'helper' : len(lu), 'historypoints' : points-pointsadj, 'pointsadj' : pointsadj } #'humanlastupdated' : zip([pretty.date(datetime.strptime(x.split(".")[0], '%Y-%m-%d %H:%M:%S')) for x in lu], [pretty.date(datetime.strptime(y.split(".")[0], '%Y-%m-%d %H:%M:%S')) for y in cronjob.split(",")]), teams.append(aTeam) #print teams mytemplate = Template(filename="%s/frontend/index.html" % self.base, input_encoding='UTF-8', output_encoding='UTF-8', default_filters=['decode.utf8']) return mytemplate.render(data=teams, bracket=bracket, crawling=os.path.isfile("/tmp/daemon-sc2ladder.pid")) #return json.dumps({"teams" : teams}) except Exception,e: exc_type, exc_value, exc_traceback = sys.exc_info() self.sc2.log("[%s] Broken: %s \n %s" % (datetime.now(), e, repr(traceback.extract_tb(exc_traceback)))) mytemplate = Template(filename="%s/frontend/broken.html" % self.base, input_encoding='utf-8', output_encoding='utf-8') return mytemplate.render()
def ban(self, event, match): groupdict = match.groupdict() # nick here could be a nick, a hostmask (with possible wildcards), or # an extban. target = groupdict["nick"] duration = groupdict["timestr"] channel = event.channel reason = "Banned by " + event.user.split("!")[0] if duration: try: duration = parse_time(duration) except ValueError as e: # Not parsable as a time? Use the string as a reason and use # the default time instead. reason = duration duration = None if not duration and self.config["defaulttime"]: duration = self.config["defaulttime"] if "@" not in target and "!" not in target and "$" not in target: # Just a nick was given. Do a kick on the target as given, but # still lookup the mask and do a ban on that. nick = target do_kick = True else: do_kick = False # Nick is only used for kicking, and for reply() calls. nick = target.split("!", 1)[0] # Unconditionally pass the target through _nick_to_hostmask. If target # is a nick, we get a hostmask out. If target is already a mask of some # sort or an extban, we get the result passed through, but with some # syntax checking. try: hostmask = (yield self._nick_to_hostmask(target)) except ircutil.NoSuchNick: event.reply( "There is no user by that nick on the network. " "Try {0}!*@* to ban anyone with that nick, or specify a full hostmask.".format(nick) ) return except ircutil.WhoisTimedout: event.reply("That's odd, the whois I did on %s didn't work. Sorry." % nick) return except ValueError: event.reply("Malformed hostmask. Hostmask syntax is <nick>!<username>@<host>", direct=True, notice=True) return log.msg("issuing ban for {0}".format(hostmask)) ban_d = self._do_moderequest(channel, "b", hostmask, duration) if do_kick: log.msg("issuing kick for {0} to go with the ban".format(nick)) kick_d = self.transport.issue_request("ircop.kick", channel=channel, target=nick, reason=reason) else: # Silence the static analysis kick_d = defer.succeed(None) try: yield ban_d if do_kick: yield kick_d except ircop.OpFailed as e: event.reply(str(e)) if duration: event.reply( "Will unban {} {}".format( hostmask, # bug: pretty.date doesn't accept floats as timestamps pretty.date(int(time.time() + duration)), ), direct=True, notice=True, ) else: event.reply("Warning: no duration given. Ban will be permanent", direct=True, notice=True)
def timeago(date): return pretty.date(date)
def __unicode__(self): return pretty.date(self.createDateTime) + " - " + self.result_text
def feed(): channels = request.args.get('ch') ch = channels.split('|m|') i = 0 cl = [] feed = [] colors = ['info', 'success', 'warning', '', 'danger'] while i < len(ch): tmp = ch[i].split('-_-') response = urllib2.urlopen( 'https://slack.com/api/channels.history?token=' + session["auth"] + '&channel=' + tmp[0]) cn = tmp[1][0] cn = cn.upper() co_i = i if co_i > len(colors): co_i = co_i - len(colors) color = colors[co_i] data = json.load(response) j = 0 while j < len(data["messages"]): if data["messages"][j]["text"] == "": ts = data["messages"][j]["ts"] dt = datetime.utcfromtimestamp(float(ts)) timeinfo = pretty.date(dt) text = data["messages"][j]["attachments"][0]["text"] matches = re.findall(r'\<(.+?)\>', text) k = 0 while k < len(matches): tag = matches[k].split("|") try: code = "<a href=\"" + tag[ 0] + "\" target=\"_blank\">" + tag[1] + "</a>" except Exception: code = "<a href=\"" + tag[ 0] + "\" target=\"_blank\">" + tag[0] + "</a>" text = text.replace('<' + matches[k] + '>', code) k = k + 1 pretext = data["messages"][j]["attachments"][0]["fallback"] matches = re.findall(r'\<(.+?)\>', pretext) k = 0 while k < len(matches): tag = matches[k].split("|") try: code = "<a href=\"" + tag[ 0] + "\" target=\"_blank\">" + tag[1] + "</a>" except Exception: code = "<a href=\"" + tag[ 0] + "\" target=\"_blank\">" + tag[0] + "</a>" pretext = pretext.replace('<' + matches[k] + '>', code) k = k + 1 feed.append({ "ts": float(ts), "text": text, "pretext": pretext, "cn": cn, "fcn": tmp[1].capitalize(), "color": color, "tsd": timeinfo }) else: ts = data["messages"][j]["ts"] dt = datetime.utcfromtimestamp(float(ts)) timeinfo = pretty.date(dt) text = data["messages"][j]["text"] matches = re.findall(r'\<(.+?)\>', text) k = 0 while k < len(matches): tag = matches[k].split("|") try: code = "<a href=\"" + tag[ 0] + "\" target=\"_blank\">" + tag[1] + "</a>" except Exception: code = "<a href=\"" + tag[ 0] + "\" target=\"_blank\">" + tag[0] + "</a>" text = text.replace('<' + matches[k] + '>', code) k = k + 1 feed.append({ "ts": float(ts), "text": text, "pretext": text, "cn": cn, "fcn": tmp[1].capitalize(), "color": color, "tsd": timeinfo }) j = j + 1 i = i + 1 if not feed: data = {"status": 0, "data": "Failed!"} js = json.dumps(data) resp = Response(js, status=200, mimetype='application/json') return resp nfeed = sorted(feed, key=itemgetter('ts'), reverse=True) data = {"status": 1, "data": nfeed} js = json.dumps(data) resp = Response(js, status=200, mimetype='application/json') return resp
def get(self): start = request.args.get('start') or 0 length = request.args.get('length') or -1 radarrid = request.args.get('radarrid') upgradable_movies = [] upgradable_movies_not_perfect = [] if settings.general.getboolean('upgrade_subs'): days_to_upgrade_subs = settings.general.days_to_upgrade_subs minimum_timestamp = ( (datetime.datetime.now() - timedelta(days=int(days_to_upgrade_subs))) - datetime.datetime(1970, 1, 1)).total_seconds() if settings.general.getboolean('upgrade_manual'): query_actions = [1, 2, 3, 6] else: query_actions = [1, 3] upgradable_movies_conditions = [ (TableHistoryMovie.action.in_(query_actions)), (TableHistoryMovie.timestamp > minimum_timestamp), (TableHistoryMovie.score.is_null(False)) ] upgradable_movies_conditions += get_exclusion_clause('movie') upgradable_movies = TableHistoryMovie.select(TableHistoryMovie.video_path, fn.MAX(TableHistoryMovie.timestamp).alias('timestamp'), TableHistoryMovie.score, TableMovies.tags, TableMovies.monitored)\ .join(TableMovies, on=(TableHistoryMovie.radarrId == TableMovies.radarrId))\ .where(reduce(operator.and_, upgradable_movies_conditions))\ .group_by(TableHistoryMovie.video_path)\ .dicts() upgradable_movies = list(upgradable_movies) for upgradable_movie in upgradable_movies: if upgradable_movie['timestamp'] > minimum_timestamp: try: int(upgradable_movie['score']) except ValueError: pass else: if int(upgradable_movie['score']) < 120: upgradable_movies_not_perfect.append( upgradable_movie) query_conditions = [(TableMovies.title.is_null(False))] if radarrid: query_conditions.append((TableMovies.radarrId == radarrid)) query_condition = reduce(operator.and_, query_conditions) movie_history = TableHistoryMovie.select(TableHistoryMovie.id, TableHistoryMovie.action, TableMovies.title, TableHistoryMovie.timestamp, TableHistoryMovie.description, TableHistoryMovie.radarrId, TableMovies.monitored, TableHistoryMovie.video_path.alias('path'), TableHistoryMovie.language, TableMovies.tags, TableHistoryMovie.score, TableHistoryMovie.subs_id, TableHistoryMovie.provider, TableHistoryMovie.subtitles_path)\ .join(TableMovies, on=(TableHistoryMovie.radarrId == TableMovies.radarrId))\ .where(query_condition)\ .order_by(TableHistoryMovie.timestamp.desc())\ .limit(length)\ .offset(start)\ .dicts() movie_history = list(movie_history) blacklist_db = TableBlacklistMovie.select( TableBlacklistMovie.provider, TableBlacklistMovie.subs_id).dicts() blacklist_db = list(blacklist_db) for item in movie_history: # Mark movies as upgradable or not item.update({"upgradable": False}) if { "video_path": str(item['path']), "timestamp": float(item['timestamp']), "score": str(item['score']), "tags": str(item['tags']), "monitored": str(item['monitored']) } in upgradable_movies_not_perfect: # noqa: E129 if os.path.isfile( path_mappings.path_replace_movie( item['subtitles_path'])): item.update({"upgradable": True}) del item['path'] postprocessMovie(item) if item['score']: item['score'] = str(round( (int(item['score']) * 100 / 120), 2)) + "%" # Make timestamp pretty if item['timestamp']: item["raw_timestamp"] = int(item['timestamp']) item["parsed_timestamp"] = datetime.datetime.fromtimestamp( int(item['timestamp'])).strftime('%x %X') item['timestamp'] = pretty.date(item["raw_timestamp"]) # Check if subtitles is blacklisted item.update({"blacklisted": False}) if item['action'] not in [0, 4, 5]: for blacklisted_item in blacklist_db: if blacklisted_item['provider'] == item[ 'provider'] and blacklisted_item[ 'subs_id'] == item['subs_id']: # noqa: E125 item.update({"blacklisted": True}) break count = TableHistoryMovie.select()\ .join(TableMovies, on=(TableHistoryMovie.radarrId == TableMovies.radarrId))\ .where(TableMovies.title.is_null(False))\ .count() return jsonify(data=movie_history, total=count)
def pretty_date(value, short=None): if short: return pretty.date(value, False, True, False) else: return pretty.date(value)
def human_last_seen(self, _clock=_clock_): ago = _clock.datetime_now() - datetime.fromtimestamp(self.last_seen) return pretty.date(_clock.datetime_now() - ago)
def get_created_date_friendly(self): print "PRETTY: ", pretty.date(self.created_date) return "TEST"
def pub_date_delta(self, lang): if lang == Lang.ru: return distance_of_time_in_words(self.date) else: return date(self.date)
def system(): def get_time_from_interval(interval): interval_clean = interval.split('[') interval_clean = interval_clean[1][:-1] interval_split = interval_clean.split(':') hour = interval_split[0] minute = interval_split[1].lstrip("0") second = interval_split[2].lstrip("0") text = "every " if hour != "0": text = text + hour if hour == "1": text = text + " hour" else: text = text + " hours" if minute != "" and second != "": text = text + ", " elif minute == "" and second != "": text = text + " and " elif minute != "" and second == "": text = text + " and " if minute != "": text = text + minute if minute == "1": text = text + " minute" else: text = text + " minutes" if second != "": text = text + " and " if second != "": text = text + second if second == "1": text = text + " second" else: text = text + " seconds" return text def get_time_from_cron(cron): text = "at " hour = str(cron[5]) minute = str(cron[6]) second = str(cron[7]) if hour != "0" and hour != "*": text = text + hour if hour == "0" or hour == "1": text = text + " hour" else: text = text + " hours" if minute != "*" and second != "0": text = text + ", " elif minute == "*" and second != "0": text = text + " and " elif minute != "0" and minute != "*" and second == "0": text = text + " and " if minute != "0" and minute != "*": text = text + minute if minute == "0" or minute == "1": text = text + " minute" else: text = text + " minutes" if second != "0" and second != "*": text = text + " and " if second != "0" and second != "*": text = text + second if second == "0" or second == "1": text = text + " second" else: text = text + " seconds" return text task_list = [] for job in scheduler.get_jobs(): if job.trigger.__str__().startswith('interval'): task_list.append([ job.name, get_time_from_interval(str(job.trigger)), pretty.date(job.next_run_time.replace(tzinfo=None)), job.id ]) elif job.trigger.__str__().startswith('cron'): task_list.append([ job.name, get_time_from_cron(job.trigger.fields), pretty.date(job.next_run_time.replace(tzinfo=None)), job.id ]) i = 0 with open(os.path.join(os.path.dirname(__file__), 'data/log/oscarr.log')) as f: for i, l in enumerate(f, 1): pass row_count = i max_page = int(math.ceil(row_count / 50.0)) return template('system', __file__=__file__, oscarr_version=oscarr_version, base_url=base_url, task_list=task_list, row_count=row_count, max_page=max_page)
def updatelength(self): now = datetime.utcnow().replace(tzinfo=utc) length = now - self.updated return pretty.date(self.updated)
def addPrettyDate(quote): quote['date_pretty'] = pretty.date(quote['datetime']) return quote
def addDate(c): import pretty from datetime import datetime c["date"] = pretty.date(datetime.strptime(c["committer"]["date"], "%Y-%m-%d %H:%M:%S"))
elif label.name == "Blocked": print('<span class="label label-danger"> </span>') else: print('<span class="label label-success"> </span>') # check if a member's name is present in the card's name, # if so, the card is own by that member if card_name.find("[%s]" % (member.username)) > -1: print( """%s<span class="label label-info">owner</span>""" % (re.sub("\[[%s]*\]" % (member.username), "", card_name)) ) card.fetch() if card.due != "": print("due: %s" % pretty.date(datetime.strptime(card.due, "%Y-%m-%dT%H:%M:%S.000Z"))) else: print("%s" % (card_name)) if (card.id in cardid_by_memberid[member.id]) and (card_name.find("[%s]" % (member.username)) == -1): print(""" <span class="label label-default">supporting</span>""") print("</p>") print("</div></div><!-- row -->") # task print(HTML_END) # who_on_what_template = tmplt_env.get_template('who_on_what.html.j2') # print(who_on_what_template.render(members=syseng_board.get_members(), cards=wip_cards))
def ban(self, event, match): groupdict = match.groupdict() # nick here could be a nick, a hostmask (with possible wildcards), or # an extban. target = groupdict['nick'] duration = groupdict['timestr'] channel = event.channel reason = "Banned by " + event.user.split("!")[0] if duration: try: duration = parse_time(duration) except ValueError as e: # Not parsable as a time? Use the string as a reason and use # the default time instead. reason = duration duration = None if not duration and self.config['defaulttime']: duration = self.config['defaulttime'] if "@" not in target and "!" not in target and "$" not in target: # Just a nick was given. Do a kick on the target as given, but # still lookup the mask and do a ban on that. nick = target do_kick = True else: do_kick = False # Nick is only used for kicking, and for reply() calls. nick = target.split("!", 1)[0] # Unconditionally pass the target through _nick_to_hostmask. If target # is a nick, we get a hostmask out. If target is already a mask of some # sort or an extban, we get the result passed through, but with some # syntax checking. try: hostmask = (yield self._nick_to_hostmask(target)) except ircutil.NoSuchNick: event.reply( "There is no user by that nick on the network. " "Try {0}!*@* to ban anyone with that nick, or specify a full hostmask." .format(nick, )) return except ircutil.WhoisTimedout: event.reply( "That's odd, the whois I did on %s didn't work. Sorry." % nick) return except ValueError: event.reply( "Malformed hostmask. Hostmask syntax is <nick>!<username>@<host>", direct=True, notice=True) return log.msg("issuing ban for {0}".format(hostmask)) ban_d = self._do_moderequest(channel, 'b', hostmask, duration) if do_kick: log.msg("issuing kick for {0} to go with the ban".format(nick)) kick_d = self.transport.issue_request( "ircop.kick", channel=channel, target=nick, reason=reason, ) else: # Silence the static analysis kick_d = defer.succeed(None) try: yield ban_d if do_kick: yield kick_d except ircop.OpFailed as e: event.reply(str(e)) if duration: event.reply( "Will unban {} {}".format( hostmask, # bug: pretty.date doesn't accept floats as timestamps pretty.date(int(time.time() + duration))), direct=True, notice=True) else: event.reply("Warning: no duration given. Ban will be permanent", direct=True, notice=True)
def feed(): channels = request.args.get('ch') ch = channels.split('|m|') i = 0 cl = [] feed = [] colors = ['info', 'success', 'warning', '', 'danger'] while i < len(ch): tmp = ch[i].split('-_-') response = urllib2.urlopen('https://slack.com/api/channels.history?token='+session["auth"]+'&channel='+tmp[0]) cn = tmp[1][0] cn = cn.upper() co_i = i if co_i > len(colors): co_i = co_i - len(colors) color = colors[co_i] data = json.load(response) j = 0 while j < len(data["messages"]): if data["messages"][j]["text"] == "": ts = data["messages"][j]["ts"] dt = datetime.utcfromtimestamp(float(ts)) timeinfo = pretty.date(dt) text = data["messages"][j]["attachments"][0]["text"] matches = re.findall(r'\<(.+?)\>',text) k = 0 while k < len(matches): tag = matches[k].split("|") try: code = "<a href=\""+tag[0]+"\" target=\"_blank\">"+tag[1]+"</a>" except Exception: code = "<a href=\""+tag[0]+"\" target=\"_blank\">"+tag[0]+"</a>" text = text.replace('<'+matches[k]+'>',code) k = k + 1 pretext = data["messages"][j]["attachments"][0]["fallback"] matches = re.findall(r'\<(.+?)\>',pretext) k = 0 while k < len(matches): tag = matches[k].split("|") try: code = "<a href=\""+tag[0]+"\" target=\"_blank\">"+tag[1]+"</a>" except Exception: code = "<a href=\""+tag[0]+"\" target=\"_blank\">"+tag[0]+"</a>" pretext = pretext.replace('<'+matches[k]+'>',code) k = k + 1 feed.append({"ts":float(ts), "text": text, "pretext": pretext, "cn": cn, "fcn": tmp[1].capitalize(), "color": color, "tsd":timeinfo}) else: ts = data["messages"][j]["ts"] dt = datetime.utcfromtimestamp(float(ts)) timeinfo = pretty.date(dt) text = data["messages"][j]["text"] matches = re.findall(r'\<(.+?)\>',text) k = 0 while k < len(matches): tag = matches[k].split("|") try: code = "<a href=\""+tag[0]+"\" target=\"_blank\">"+tag[1]+"</a>" except Exception: code = "<a href=\""+tag[0]+"\" target=\"_blank\">"+tag[0]+"</a>" text = text.replace('<'+matches[k]+'>',code) k = k + 1 feed.append({"ts":float(ts), "text": text, "pretext": text, "cn": cn, "fcn": tmp[1].capitalize(), "color": color, "tsd":timeinfo}) j = j + 1 i = i + 1 if not feed: data = {"status":0,"data":"Failed!"} js = json.dumps(data) resp = Response(js, status = 200, mimetype = 'application/json') return resp nfeed = sorted(feed, key=itemgetter('ts'), reverse=True) data = {"status":1,"data":nfeed} js = json.dumps(data) resp = Response(js, status = 200, mimetype = 'application/json') return resp