def get_updated_albums_dict(sid): global updated_album_ids if not sid in updated_album_ids: return [] previous_newest_album = cache.get_station(sid, "newest_album") if not previous_newest_album: cache.set_station(sid, "newest_album", timestamp()) else: newest_albums = db.c.fetch_list( "SELECT album_id FROM r4_albums JOIN r4_album_sid USING (album_id) WHERE sid = %s AND album_added_on > %s", (sid, previous_newest_album)) for album_id in newest_albums: updated_album_ids[sid][album_id] = True cache.set_station(sid, "newest_album", timestamp()) album_diff = [] for album_id in updated_album_ids[sid]: album = Album.load_from_id_sid(album_id, sid) album.solve_cool_lowest(sid) tmp = album.to_dict_full() # Remove user-related stuff since this gets stuffed straight down the pipe tmp.pop('rating_user', None) tmp.pop('fave', None) album_diff.append(tmp) return album_diff
def post(self): if self.get_argument("date_start"): self.date_start = time.mktime(self.get_argument("date_start").timetuple()) else: self.date_start = (timestamp() - (7 * 86400) + 1) if self.get_argument("date_end"): self.date_end = time.mktime(self.get_argument("date_end").timetuple()) else: self.date_end = timestamp() if self.date_start >= self.date_end: raise APIException("invalid_argument", text="Start date cannot be after end date.") timespan = self.date_end - self.date_start if timespan <= (86400 * 2): sql = "SELECT (lc_time - (lc_time %% 3600)) AS lc_time, ROUND(CAST(AVG(lc_guests) AS NUMERIC), 1) AS lc_listeners FROM r4_listener_counts WHERE lc_time > %s AND lc_time < %s AND sid = %s GROUP BY (lc_time - (lc_time %% 3600)) ORDER BY lc_time" dateformat = "%Y-%m-%d %H:00" elif timespan <= (86400 * 7): sql = "SELECT (lc_time - (lc_time %% (3600 * 6))) AS lc_time, ROUND(CAST(AVG(lc_guests) AS NUMERIC), 1) AS lc_listeners FROM r4_listener_counts WHERE lc_time > %s AND lc_time < %s AND sid = %s GROUP BY (lc_time - (lc_time %% (3600 * 6))) ORDER BY lc_time" dateformat = "%Y-%m-%d %H:00" elif timespan <= (86400 * 30): sql = "SELECT (lc_time - (lc_time %% 86400)) AS lc_time, ROUND(CAST(AVG(lc_guests) AS NUMERIC), 1) AS lc_listeners FROM r4_listener_counts WHERE lc_time > %s AND lc_time < %s AND sid = %s GROUP BY (lc_time - (lc_time %% 86400)) ORDER BY lc_time" dateformat = "%Y-%m-%d" else: sql = "SELECT (lc_time - (lc_time %% (86400 * 7))) AS lc_time, ROUND(CAST(AVG(lc_guests) AS NUMERIC), 1) AS lc_listeners FROM r4_listener_counts WHERE lc_time > %s AND lc_time < %s AND sid = %s GROUP BY (lc_time - (lc_time %% (86400 * 7))) ORDER BY lc_time" dateformat = "%Y-%m-%d" res = {} config.station_ids = (1, 2, 3, 4, 5) for sid in config.station_ids: res[sid] = db.c.fetch_all(sql, (self.date_start, self.date_end, sid)) for row in res[sid]: dt = datetime.datetime.fromtimestamp(row['lc_time']) row['lc_time'] = dt.strftime(dateformat) self.append(self.return_name, res)
def advance_station(sid): db.c.start_transaction() try: log.debug("advance", "Advancing station %s." % sid) start_time = timestamp() # If we need some emergency elections here if len(upnext[sid]) == 0: manage_next(sid) while upnext[sid][0].used or len(upnext[sid][0].songs) == 0: log.warn("advance", "Event ID %s was already used or has zero songs. Deleting." % upnext[sid][0].id) upnext[sid][0].delete() upnext[sid].pop(0) if len(upnext[sid]) == 0: manage_next(sid) start_time = timestamp() upnext[sid][0].prepare_event() db.c.commit() log.debug("advance", "upnext[0] preparation time: %.6f" % (timestamp() - start_time,)) log.info("advance", "Next song: %s" % get_advancing_file(sid)) tornado.ioloop.IOLoop.instance().add_timeout(datetime.timedelta(milliseconds=150), lambda: post_process(sid)) except: db.c.rollback() raise
def _start_cooldown_db(self, sid, cool_time): if config.has_station(sid, "cooldown_enable_for_categories") and not config.get_station(sid, "cooldown_enable_for_categories"): return cool_end = int(cool_time + timestamp()) log.debug("cooldown", "Group ID %s Station ID %s cool_time period: %s" % (self.id, sid, cool_time)) # Make sure to update both the if and else SQL statements if doing any updates if db.c.allows_join_on_update: db.c.update("UPDATE r4_song_sid SET song_cool = TRUE, song_cool_end = %s " "FROM r4_song_group " "WHERE r4_song_sid.song_id = r4_song_group.song_id AND r4_song_group.group_id = %s " "AND r4_song_sid.sid = %s AND r4_song_sid.song_exists = TRUE AND r4_song_sid.song_cool_end <= %s ", (cool_end, self.id, sid, cool_end)) request_only_end = cool_end + 300 db.c.update("UPDATE r4_song_sid SET song_request_only = TRUE, song_request_only_end = %s " "FROM r4_song_group " "WHERE r4_song_sid.song_id = r4_song_group.song_id AND r4_song_group.group_id = %s " "AND r4_song_sid.sid = %s AND r4_song_sid.song_exists = TRUE AND r4_song_sid.song_cool_end <= %s " "AND song_request_only_end IS NOT NULL", (request_only_end, self.id, sid, cool_end)) else: song_ids = db.c.fetch_list( "SELECT song_id " "FROM r4_song_group JOIN r4_song_sid USING (song_id) " "WHERE r4_song_group.group_id = %s AND r4_song_sid.sid = %s AND r4_song_sid.song_exists = TRUE AND r4_song_sid.song_cool_end < %s", (self.id, sid, timestamp() - cool_time)) for song_id in song_ids: db.c.update("UPDATE r4_song_sid SET song_cool = TRUE, song_cool_end = %s WHERE song_id = %s AND sid = %s", (cool_end, song_id, sid))
def update(self): handler = APIHandler(websocket=True) handler.locale = self.locale handler.request = FakeRequestObject({}, self.request.cookies) handler.sid = self.sid handler.user = self.user handler.return_name = "sync_result" try: startclock = timestamp() handler.prepare_standalone() if not cache.get_station(self.sid, "backend_ok"): raise APIException("station_offline") self.refresh_user() api_requests.info.attach_info_to_request(handler, live_voting=True) if self.user.is_dj(): api_requests.info.attach_dj_info_to_request(handler) handler.append("user", self.user.to_private_dict()) handler.append("api_info", { "exectime": timestamp() - startclock, "time": round(timestamp()) }) except Exception as e: if handler: handler.write_error(500, exc_info=sys.exc_info(), no_finish=True) log.exception("websocket", "Exception during update.", e) finally: if handler: self.write_message(handler._output) #pylint: disable=W0212
def post(self): if self.get_argument("date_start"): self.date_start = time.mktime(self.get_argument("date_start").timetuple()) else: self.date_start = (timestamp() - (7 * 86400) + 1) if self.get_argument("date_end"): self.date_end = time.mktime(self.get_argument("date_end").timetuple()) else: self.date_end = timestamp() sql = ("SELECT aggr_time AS lc_time, ROUND(CAST(AVG(lc_guests) AS NUMERIC), 1) AS lc_listeners " "FROM ( " "SELECT (((lc_time %% 86400) / 14400) * 14400) + (((lc_time %% (86400 * 7)) / 86400) * 86400) AS aggr_time, lc_guests " "FROM r4_listener_counts " "WHERE lc_time > %s AND lc_time < %s AND sid = %s " ") AS lc_listeners " "GROUP BY lc_time ORDER BY lc_time " ) res = {} config.station_ids = (1, 2, 3, 4, 5) for sid in config.station_ids: res[sid] = db.c.fetch_all(sql, (self.date_start, self.date_end, sid)) for row in res[sid]: dt = datetime.datetime.fromtimestamp(row['lc_time']) row['lc_time'] = dt.strftime("%a %H:%M") self.append(self.return_name, res)
def _update_inactive(): f = open("%s/r4_inactive_check" % tempfile.gettempdir(), 'w') f.write(str(int(timestamp()))) f.close() time_threshold = timestamp() - (86400 * 30) db.c.update("UPDATE phpbb_users SET radio_inactive = TRUE " "WHERE radio_inactive = FALSE AND radio_last_active < %s", (time_threshold,))
def __init__(self, service_url, ua=UA): """Initialize & call webservice.""" srv = service_url[8:20] last = WEBQuery.T[srv] if srv in WEBQuery.T else 0.0 wait = 0 if timestamp() - last > THROTTLING else THROTTLING sleep(wait) self.url = service_url self.data = webservice.query(service_url, ua) WEBQuery.T[srv] = timestamp()
def manage_next(sid): # pylint: disable=W0612 max_sched_id, max_elec_id, num_elections, max_future_time = _get_schedule_stats(sid) # pylint: enable=W0612 now_producer = get_producer_at_time(sid, timestamp()) next_producer = get_producer_at_time(sid, max_future_time) nextnext_producer_start = db.c.fetch_var( "SELECT sched_start FROM r4_schedule WHERE sid = %s AND sched_used = FALSE AND sched_start > %s AND sched_timed = TRUE", (sid, max_future_time), ) time_to_future_producer = None if nextnext_producer_start: time_to_future_producer = nextnext_producer_start - max_future_time else: time_to_future_producer = 86400 while len(upnext[sid]) < min(now_producer.plan_ahead_limit, next_producer.plan_ahead_limit): target_length = None if time < 20: log.debug("timing", "SID %s <20 seconds to upnext event, not using timing." % sid) if time_to_future_producer < 40: target_length = time_to_future_producer next_producer = rainwave.events.shortest_election.ShortestElectionProducer(sid) log.debug("timing", "SID %s <40 seconds to upnext event, using shortest elections." % sid) elif time_to_future_producer < (playlist.get_average_song_length(sid) * 1.3): target_length = time_to_future_producer log.debug("timing", "SID %s close to event, timing to %s seconds long." % (sid, target_length)) elif time_to_future_producer < (playlist.get_average_song_length(sid) * 2.2): target_length = playlist.get_average_song_length(sid) log.debug("timing", "SID %s has an upcoming event, timing to %s seconds long." % (sid, target_length)) next_event = next_producer.load_next_event(target_length, max_elec_id) if not next_event: log.info( "manage_next", "Producer ID %s type %s did not produce an event." % (next_producer.id, next_producer.type), ) next_producer = election.ElectionProducer(sid) next_event = next_producer.load_next_event(target_length, max_elec_id) upnext[sid].append(next_event) if next_event.is_election: num_elections += 1 if next_event.is_election and next_event.id > max_elec_id: max_elec_id = next_event.id max_future_time += upnext[sid][-1].length() time_to_future_producer -= upnext[sid][-1].length() next_producer = get_producer_at_time(sid, max_future_time) future_time = None if current[sid].start: future_time = current[sid].start + current[sid].length() else: future_time = int(timestamp() + current[sid].length()) for evt in upnext[sid]: evt.start = future_time future_time += evt.length() if evt.is_election: evt.update_vote_counts()
def write_output(self): if hasattr(self, "_output"): if hasattr(self, "_startclock"): exectime = timestamp() - self._startclock else: exectime = -1 if exectime > 0.5: log.warn("long_request", "%s took %s to execute!" % (self.url, exectime)) self.append("api_info", { "exectime": exectime, "time": round(timestamp()) }) self.write(tornado.escape.json_encode(self._output))
def write_output(self): if hasattr(self, "_output"): if hasattr(self, "_startclock"): exectime = timestamp() - self._startclock else: exectime = -1 if exectime > 0.5: log.warn("long_request", "%s took %s to execute!" % (self.url, exectime)) self.append("api_info", { "exectime": exectime, "time": round(timestamp()) }) self.write(json.dumps(self._output, ensure_ascii=False))
def should_vote_throttle(self): if not self.votes_by_key in votes_by: return 0 vote_limit = 3 # log.debug("vote_throttle", "%s - %s - %s" % (vote_limit, votes_by[self.votes_by_key], (timestamp() < (last_vote_by[self.votes_by_key] + vote_once_every_seconds)))) if (votes_by[self.votes_by_key] >= vote_limit) and (timestamp() < (last_vote_by[self.votes_by_key] + vote_once_every_seconds)): # log.debug("vote_throttle", (last_vote_by[self.votes_by_key] + vote_once_every_seconds) - timestamp()) return (last_vote_by[self.votes_by_key] + vote_once_every_seconds) - timestamp() return 0
def time_transform(standard_time): separator = str(standard_time)[4:5] if separator is '/': time = datetime.strptime(standard_time, '%Y/%m/%d %H:%M:%S') return time.timestamp() elif separator is '-': time = datetime.strptime(standard_time, '%Y-%m-%d %H:%M:%S') return time.timestamp() else: print('Wrong input format')
def warm_cooled_albums(sid): if sid == 0: return global updated_album_ids album_list = db.c.fetch_list( "SELECT album_id FROM r4_album_sid WHERE sid = %s AND album_cool_lowest <= %s AND album_cool = TRUE", (sid, timestamp())) for album_id in album_list: updated_album_ids[sid][album_id] = True db.c.update( "UPDATE r4_album_sid SET album_cool = FALSE WHERE sid = %s AND album_cool_lowest <= %s AND album_cool = TRUE", (sid, timestamp()))
def post(self): self.append(self.return_name, db.c.fetch_all("SELECT sched_type as type, sched_id AS id, sched_name AS name, sched_start AS start, sched_end AS end, sched_url AS url, sid, ROUND((sched_end - sched_start) / 60) AS sched_length_minutes, username " "FROM r4_schedule LEFT JOIN phpbb_users ON (sched_dj_user_id = user_id) " "WHERE sched_used = FALSE AND sched_start >= %s ORDER BY sched_start", (timestamp(),))) self.append(self.return_name + "_past", db.c.fetch_all("SELECT sched_type as type, sched_id AS id, sched_name AS name, sched_start AS start, sched_end AS end, sched_url AS url, sid, ROUND((sched_end - sched_start) / 60) AS sched_length_minutes, username " "FROM r4_schedule LEFT JOIN phpbb_users ON (sched_dj_user_id = user_id) " "WHERE sched_type != 'PVPElectionProducer' AND sched_start > %s AND sched_start < %s ORDER BY sched_start DESC", (timestamp() - (86400 * 26), timestamp())))
def build_message_html(time, source, target, message, specialuser, usercolor, emoteset, emotes, displayname): if source.lower() == config['notifyuser']: return '<div class="notification line" data-timestamp="%d">%s</div>' % (time.timestamp(), escape(message)) if message[:4].lower() in (".me ", "/me "): is_action = True message = message[4:] else: is_action = False ret = [] ret.append('<div class="line" data-timestamp="%d">' % time.timestamp()) if 'staff' in specialuser: ret.append('<span class="badge staff"></span> ') if 'admin' in specialuser: ret.append('<span class="badge admin"></span> ') if "#" + source.lower() == target.lower(): ret.append('<span class="badge broadcaster"></span> ') if 'mod' in specialuser: ret.append('<span class="badge mod"></span> ') if 'turbo' in specialuser: ret.append('<span class="badge turbo"></span> ') if 'subscriber' in specialuser: ret.append('<span class="badge subscriber"></span> ') ret.append('<span class="nick"') if usercolor: ret.append(' style="color:%s"' % escape(usercolor)) ret.append('>%s</span>' % escape(displayname or (yield from get_display_name(source)))) if is_action: ret.append(' <span class="action"') if usercolor: ret.append(' style="color:%s"' % escape(usercolor)) ret.append('>') else: ret.append(": ") if 'cleared' in specialuser: ret.append('<span class="deleted"><message deleted></span>') # Use escape() rather than urlize() so as not to have live spam links # either for users to accidentally click, or for Google to see ret.append('<span class="message cleared">%s</span>' % escape(message)) elif emotes is not None: messagehtml = format_message_explicit_emotes(message, emotes) ret.append('<span class="message">%s</span>' % messagehtml) else: messagehtml = format_message(message, (yield from get_filtered_emotes(emoteset))) ret.append('<span class="message">%s</span>' % messagehtml) if is_action: ret.append('</span>') ret.append('</div>') return ''.join(ret)
def wait_for(callback, value, timeout=EFSConnection.DEFAULT_WAIT_TIMEOUT_SECONDS): """ Helper method to wait for desired value returned by callback method """ wait_start = timestamp() while True: if callback() != value: if timeout != 0 and (timestamp() - wait_start > timeout): raise RuntimeError('Wait timeout exceeded (' + str(timeout) + ' sec)') else: sleep(5) continue break
def set_song_rating(sid, song_id, user_id, rating=None, fave=None): db.c.start_transaction() try: existing_rating = db.c.fetch_row( "SELECT song_rating_user, song_fave FROM r4_song_ratings WHERE song_id = %s AND user_id = %s", (song_id, user_id), ) count = db.c.fetch_var("SELECT COUNT(*) FROM r4_song_ratings WHERE user_id = %s", (user_id,)) if not existing_rating: count += 1 rank = db.c.fetch_var("SELECT COUNT(*) FROM phpbb_users WHERE radio_totalratings > %s", (count,)) if existing_rating: if not rating: rating = existing_rating["song_rating_user"] if not fave: fave = existing_rating["song_fave"] db.c.update( "UPDATE r4_song_ratings " "SET song_rating_user = %s, song_fave = %s, song_rated_at = %s, song_rated_at_rank = %s, song_rated_at_count = %s " "WHERE user_id = %s AND song_id = %s", (rating, fave, timestamp(), rank, count, user_id, song_id), ) db.c.update( "UPDATE phpbb_users SET radio_totalmindchange = radio_totalmindchange + 1, radio_inactive = FALSE, radio_last_active = %s WHERE user_id = %s", (timestamp(), user_id), ) else: if not rating: rating = None if not fave: fave = None db.c.update( "INSERT INTO r4_song_ratings " "(song_rating_user, song_fave, song_rated_at, song_rated_at_rank, song_rated_at_count, user_id, song_id) " "VALUES (%s, %s, %s, %s, %s, %s, %s)", (rating, fave, timestamp(), rank, count, user_id, song_id), ) db.c.update( "UPDATE phpbb_users SET radio_totalratings = %s, radio_inactive = FALSE, radio_last_active = %s WHERE user_id = %s", (count, timestamp(), user_id), ) albums = update_album_ratings(sid, song_id, user_id) db.c.commit() cache.set_song_rating(song_id, user_id, {"rating_user": rating, "fave": fave}) return albums except: db.c.rollback() raise
def pair_device(receiver, args): # get all current devices known_devices = [dev.number for dev in receiver] from logitech_receiver import base, hidpp10, status, notifications receiver.status = status.ReceiverStatus(receiver, lambda *args, **kwargs: None) # check if it's necessary to set the notification flags old_notification_flags = hidpp10.get_notification_flags(receiver) or 0 if not (old_notification_flags & hidpp10.NOTIFICATION_FLAG.wireless): hidpp10.set_notification_flags(receiver, old_notification_flags | hidpp10.NOTIFICATION_FLAG.wireless) class HandleWithNotificationHook(int): def notifications_hook(self, n): assert n if n.devnumber == 0xFF: notifications.process(receiver, n) elif n.sub_id == 0x41 and n.address == 0x04: if n.devnumber not in known_devices: receiver.status.new_device = receiver[n.devnumber] timeout = 20 # seconds receiver.handle = HandleWithNotificationHook(receiver.handle) receiver.set_lock(False, timeout=timeout) print ("Pairing: turn your new device on (timing out in", timeout, "seconds).") # the lock-open notification may come slightly later, wait for it a bit from time import time as timestamp pairing_start = timestamp() patience = 5 # seconds while receiver.status.lock_open or timestamp() - pairing_start < patience: n = base.read(receiver.handle) if n: n = base.make_notification(*n) if n: receiver.handle.notifications_hook(n) if not (old_notification_flags & hidpp10.NOTIFICATION_FLAG.wireless): # only clear the flags if they weren't set before, otherwise a # concurrently running Solaar app might stop working properly hidpp10.set_notification_flags(receiver, old_notification_flags) if receiver.status.new_device: dev = receiver.status.new_device print ("Paired device %d: %s [%s:%s:%s]" % (dev.number, dev.name, dev.wpid, dev.codename, dev.serial)) else: error = receiver.status[status.KEYS.ERROR] or 'no device detected?' _fail(error)
def _trim(sid): # Deletes any events in the schedule and elections tables that are old, according to the config current_time = int(timestamp()) db.c.update("DELETE FROM r4_schedule WHERE sched_start_actual <= %s", (current_time - config.get("trim_event_age"),)) db.c.update("DELETE FROM r4_elections WHERE elec_start_actual <= %s", (current_time - config.get("trim_election_age"),)) max_history_id = db.c.fetch_var("SELECT MAX(songhist_id) FROM r4_song_history") db.c.update("DELETE FROM r4_song_history WHERE songhist_id <= %s AND sid = %s", (max_history_id - config.get("trim_history_length"), sid))
def old_row_to_user_id(name, uuid=None, time=None): if not name: return None try: return user_ids.get_or_create(name, add_uuid_dashes(uuid), int(time.timestamp()) if time else 0) except NoSuchMojangUser: log.warning("Can't find user with name '{0}'".format(name))
def _start_cooldown_db(self, sid, cool_time): cool_end = int(cool_time + timestamp()) if db.c.allows_join_on_update: db.c.update( "UPDATE r4_song_sid " "SET song_cool = TRUE, song_cool_end = %s " "FROM r4_songs " "WHERE r4_song_sid.song_id = r4_songs.song_id AND album_id = %s AND sid = %s AND song_cool_end <= %s ", (cool_end, self.id, sid, cool_end), ) request_only_end = cool_end + config.get_station(sid, "cooldown_request_only_period") db.c.update( "UPDATE r4_song_sid " "SET song_request_only = TRUE, song_request_only_end = %s " "FROM r4_songs " "WHERE r4_song_sid.song_id = r4_songs.song_id AND album_id = %s AND sid = %s AND song_cool_end <= %s " "AND song_request_only_end IS NOT NULL", (request_only_end, self.id, sid, cool_end), ) else: songs = db.c.fetch_list( "SELECT song_id FROM r4_song_sid JOIN r4_songs USING (song_id) WHERE album_id = %s AND sid = %s AND song_exists = TRUE AND song_cool_end < %s", (self.id, sid, cool_end), ) for song_id in songs: db.c.update( "UPDATE r4_song_sid SET song_cool = TRUE, song_cool_end = %s WHERE song_id = %s AND song_cool_end < %s AND sid = %s", (cool_end, song_id, cool_end, sid), )
def get_next(sid): line = cache.get_station(sid, "request_line") if not line: return None song = None for pos in range(0, len(line)): if not line[pos]: pass # ?!?! elif 'skip' in line[pos] and line[pos]['skip']: log.debug("request", "Passing on user %s since they're marked as skippable." % line[pos]['username']) elif not line[pos]['song_id']: log.debug("request", "Passing on user %s since they have no valid first song." % line[pos]['username']) else: entry = line.pop(pos) song = playlist.Song.load_from_id(entry['song_id'], sid) log.debug("request", "Fulfilling %s's request for %s." % (entry['username'], song.filename)) song.data['elec_request_user_id'] = entry['user_id'] song.data['elec_request_username'] = entry['username'] u = User(entry['user_id']) db.c.update("DELETE FROM r4_request_store WHERE user_id = %s AND song_id = %s", (u.id, entry['song_id'])) u.remove_from_request_line() request_count = db.c.fetch_var("SELECT COUNT(*) FROM r4_request_history WHERE user_id = %s", (u.id,)) + 1 db.c.update("DELETE FROM r4_request_store WHERE song_id = %s AND user_id = %s", (song.id, u.id)) db.c.update("INSERT INTO r4_request_history (user_id, song_id, request_wait_time, request_line_size, request_at_count, sid) " "VALUES (%s, %s, %s, %s, %s, %s)", (u.id, song.id, timestamp() - entry['line_wait_start'], len(line), request_count, sid)) db.c.update("UPDATE phpbb_users SET radio_totalrequests = %s WHERE user_id = %s", (request_count, u.id)) song.update_request_count(sid) break return song
def dj_heartbeat_check(): # Don't do this in testing environments if config.get("developer_mode"): return for sid in config.station_ids: if cache.get_station(sid, "backend_paused_playing"): hb = cache.get_station(sid, "dj_heartbeat") hbs = cache.get_station(sid, "dj_heartbeat_start") if not hbs or ((timestamp() - hbs) <= 10): pass elif not hb or ((timestamp() - hb) >= 15): log.warn("dj_heartbeat", "DJ heart attack - resetting station to normal.") cache.set_station(sid, "backend_paused", False) cache.set_station(sid, "backend_paused_playing", False) liquidsoap.kick_dj(sid) liquidsoap.skip(sid)
def signInterest(self, interest, keyName=None, wireFormat=None): # Adds the nonce and timestamp here, because there is no # 'makeCommandInterest' call for this yet nonceValue = bytearray(8) for i in range(8): nonceValue[i] = self.random.randint(0,0xff) timestampValue = bytearray(8) ts = int(timestamp()*1000) for i in range(8): byte = ts & 0xff timestampValue[-(i+1)] = byte ts = ts >> 8 if wireFormat is None: wireFormat = WireFormat.getDefaultWireFormat() s = Sha256HmacSignature() s.getKeyLocator().setType(KeyLocatorType.KEYNAME) s.getKeyLocator().setKeyName(keyName) interestName = interest.getName() interestName.append(nonceValue).append(timestampValue) interestName.append(wireFormat.encodeSignatureInfo(s)) interestName.append(Name.Component()) encoding = interest.wireEncode(wireFormat) signer = hmac.new(self.key, encoding.toSignedBuffer(), sha256) s.setSignature(Blob(signer.digest())) interest.setName(interestName.getPrefix(-1).append( wireFormat.encodeSignatureValue(s)))
def _process_line(line, sid): new_line = [] # user_positions has user_id as a key and position as the value, this is cached for quick lookups by API requests # so users know where they are in line user_positions = {} t = int(timestamp()) albums_with_requests = [] position = 1 # For each person for row in line: add_to_line = False u = User(row['user_id']) row['song_id'] = None # If their time is up, remove them and don't add them to the new line if row['line_expiry_tune_in'] and row['line_expiry_tune_in'] <= t: log.debug("request_line", "%s: Removed user ID %s from line for tune in timeout, expiry time %s current time %s" % (sid, u.id, row['line_expiry_tune_in'], t)) u.remove_from_request_line() else: tuned_in_sid = db.c.fetch_var("SELECT sid FROM r4_listeners WHERE user_id = %s AND sid = %s AND listener_purge = FALSE", (u.id, sid)) tuned_in = True if tuned_in_sid == sid else False if tuned_in: # Get their top song ID song_id = u.get_top_request_song_id(sid) # If they have no song and their line expiry has arrived, boot 'em if not song_id and row['line_expiry_election'] and (row['line_expiry_election'] <= t): log.debug("request_line", "%s: Removed user ID %s from line for election timeout, expiry time %s current time %s" % (sid, u.id, row['line_expiry_election'], t)) u.remove_from_request_line() # Give them more chances if they still have requests # They'll get added to the line of whatever station they're tuned in to (if any!) if u.has_requests(): u.put_in_request_line(u.get_tuned_in_sid()) # If they have no song, start the expiry countdown elif not song_id and not row['line_expiry_election']: row['line_expiry_election'] = t + 900 db.c.update("UPDATE r4_request_line SET line_expiry_election = %s WHERE user_id = %s", ((t + 900), row['user_id'])) add_to_line = True # Keep 'em in line else: if song_id: albums_with_requests.append(db.c.fetch_var("SELECT album_id FROM r4_songs WHERE song_id = %s", (song_id,))) row['song_id'] = song_id add_to_line = True elif not row['line_expiry_tune_in'] or row['line_expiry_tune_in'] == 0: db.c.update("UPDATE r4_request_line SET line_expiry_tune_in = %s WHERE user_id = %s", ((t + 600), row['user_id'])) add_to_line = True else: add_to_line = True if add_to_line: new_line.append(row) user_positions[u.id] = position position = position + 1 cache.set_station(sid, "request_line", new_line, True) cache.set_station(sid, "request_user_positions", user_positions, True) db.c.update("UPDATE r4_album_sid SET album_requests_pending = NULL WHERE album_requests_pending = TRUE AND sid = %s", (sid,)) for album_id in albums_with_requests: db.c.update("UPDATE r4_album_sid SET album_requests_pending = TRUE WHERE album_id = %s AND sid = %s", (album_id, sid)) return new_line
def _get_schedule_stats(sid): global upnext global current max_sched_id = 0 max_elec_id = None end_time = int(timestamp()) if sid in current and current[sid]: max_sched_id = current[sid].id if current[sid].start_actual: end_time = current[sid].start_actual + current[sid].length() else: end_time += current[sid].length() if current[sid].is_election: max_elec_id = current[sid].id num_elections = 0 if sid in upnext: for e in upnext[sid]: if e.is_election: num_elections += 1 if e.id > max_elec_id: max_elec_id = e.id elif not e.is_election and e.id > max_sched_id: max_sched_id = e.id end_time += e.length() if not max_elec_id: max_elec_id = db.c.fetch_var( "SELECT elec_id FROM r4_elections WHERE elec_used = TRUE ORDER BY elec_id DESC LIMIT 1" ) return (max_sched_id, max_elec_id, num_elections, end_time)
def get_producer_at_time(sid, at_time): to_ret = None local_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(at_time)) time_ahead = int((at_time - timestamp()) / 60) sched_id = db.c.fetch_var( "SELECT sched_id " "FROM r4_schedule " "WHERE sid = %s AND sched_start <= %s AND sched_end > %s " "ORDER BY sched_id DESC " "LIMIT 1", (sid, at_time + 20, at_time), ) try: to_ret = events.event.BaseProducer.load_producer_by_id(sched_id) if to_ret: to_ret.start_producer() except Exception as e: log.warn("get_producer", "Failed to obtain producer at time %s (%sm ahead)." % (local_time, time_ahead)) log.exception( "get_producer", "Failed to get an appropriate producer at time %s (%sm ahead)." % (local_time, time_ahead), e, ) if not to_ret: log.debug( "get_producer", "No producer at time %s (%sm ahead), defaulting to election." % (local_time, time_ahead) ) return election.ElectionProducer(sid) if not to_ret.has_next_event(): log.warn("get_producer", "Producer ID %s (type %s, %s) has no events." % (to_ret.id, to_ret.type, to_ret.name)) return election.ElectionProducer(sid) return to_ret
async def _msg_handler(self, msg_data : Dict): now = datetime.now() if (now - self.user.state.connection_time).seconds < TIME_BEFORE_TALK: return self.send_json(type='wait',date=timestamp()*1000) if self._check_flood(msg_data['msg']): return # user object instance renders both the output sound and output text output_msg, wav = await self.user.render_message(msg_data["msg"], msg_data.get("lang", "fr")) # estimating the end of the current voice render, to rate limit calc_sendend = max(self.sendend, now) + timedelta(seconds=len(wav) * 8 / 6000000) synth = calc_sendend < now + timedelta(seconds=2.5) if synth: self.sendend = calc_sendend output_msg = escape(output_msg) # send to the backlog info = self.channel_obj.log_to_backlog(self.user.user_id, output_msg) if not self.user.state.is_shadowbanned: if "notext" in msg_data and self.raw_cookie in SOUND_BROADCASTER_COOKIES: self.channel_obj.broadcast(type="audio_broadcast", userid=self.user.user_id, binary_payload=wav if synth else None) else: # broadcast message and rendered audio to all clients in the channel self.channel_obj.broadcast(type='msg', userid=self.user.user_id, msg=output_msg, date=info['date'], binary_payload=wav if synth else None) else: # we just send the message to the current client self.send_json(type='msg', userid=self.user.user_id, msg=output_msg, date=info['date']) if synth: self.send_binary(wav)
async def _attack_handler(self, msg_data : Dict): # cleaning up none values in case of fuckups msg_data = {key: value for key, value in msg_data.items() if value is not None} adversary_id, adversary = self.channel_obj.get_user_by_name(msg_data.get("target", self.user.poke_params.pokename), msg_data.get("order", 1) - 1) now = datetime.now() # checking if the target user is found, and if the current user has waited long enough to attack if adversary is None: self.send_json(type='attack', event='invalid') elif (now - self.user.state.last_attack < timedelta(seconds=ATTACK_RESTING_TIME)): self.send_json(type='attack', event='invalid') else: self.channel_obj.broadcast(type='attack', date=timestamp() * 1000, event='attack', attacker_id=self.user.user_id, defender_id=adversary_id) combat_sim = CombatSimulator() combat_sim.run_attack(self.user, adversary, self.channel_obj) self.channel_obj.broadcast(type='attack', date=timestamp() * 1000, event='dice', attacker_dice=combat_sim.atk_dice, defender_dice=combat_sim.def_dice, attacker_bonus=combat_sim.atk_bonus, defender_bonus=combat_sim.def_bonus, attacker_id=self.user.user_id, defender_id=adversary_id) if combat_sim.affected_users: # there are users affected by some effects for user, effect in combat_sim.affected_users: self.channel_obj.broadcast(type='attack', date=timestamp() * 1000, event='effect', tag=effect.TAG if hasattr(effect, "TAG") else None, target_id=user.user_id, effect=effect.name, timeout=effect.timeout) else: # list is empty, no one was attacked self.channel_obj.broadcast(type='attack', date=timestamp() * 1000, event='nothing') # combat_sim uses the last attack time to compute the bonus, # so it must be updated after the running the attack. self.user.state.last_attack = now
def upload_theme(self, ndthemepack: str): data = json.dumps({ "themePackUrl": ndthemepack, "timestamp": int(timestamp() * 1000) }) response = requests.post( f"{self.api}/x{self.comId}/s/community/settings", data=data, headers=headers.Headers(data=data).headers) if response.status_code == 200: return response.status_code else: return json.loads(response.text)
def test_message_sendlater_invalid_token(): # Test if AccessError is raised when given invalid token clear_v1() user = auth_register_v2('*****@*****.**', 'password1234', 'Harry', 'Lurr') channel = channels_create_v2(user['token'], 'HARRYS CHANNEL', True) time = datetime.now().replace(microsecond=0) + timedelta(0, 3) time_sent = time.timestamp() with pytest.raises(AccessError): message_sendlater_v1(-2382732, channel['channel_id'], 'Poopoo', time_sent)
def update(self): # Overwrite this value since who knows how long we've spent idling self._startclock = timestamp() if not cache.get_station(self.sid, "backend_ok"): raise APIException("station_offline") self.user.refresh(self.sid) if "requests_paused" in self.user.data: del self.user.data["requests_paused"] api_requests.info.attach_info_to_request(self) self.finish()
def find_best_feature(self, x): """ Find the best feature for a median split value. :param DataFrame x: Samples data frame. :return: The best feature name. """ start_time = timestamp() features = [f for f in x.columns if f not in ["time", "event"]] if not self.fix_tree_features: # features = list(np.random.permutation(features))[:self.max_features] features = list(self.rs.permutation(features))[:self.max_features] information_gains = [self.logrank(x, feature) for feature in features] highest_ig = max(information_gains) end_time = timestamp() # self.print(" Find best feature time: {}".format(end_time - start_time)) if highest_ig == 0: return None else: return features[information_gains.index(highest_ig)]
def setNickname(self, nickname, community_id, uid): result = requests.post(self.api + "x" + str(community_id) + "/s/user-profile/" + uid + "?sid=" + self.sid, data=json.dumps({ "nickname": nickname, "timestamp": (int(timestamp() * 1000)) }), headers={ 'Content-Type': 'application/json' }).json() return result
def _trim(sid): # Deletes any events in the schedule and elections tables that are old, according to the config current_time = int(timestamp()) db.c.update("DELETE FROM r4_schedule WHERE sched_start_actual <= %s", (current_time - config.get("trim_event_age"), )) db.c.update("DELETE FROM r4_elections WHERE elec_start_actual <= %s", (current_time - config.get("trim_election_age"), )) max_history_id = db.c.fetch_var( "SELECT MAX(songhist_id) FROM r4_song_history") db.c.update( "DELETE FROM r4_song_history WHERE songhist_id <= %s AND sid = %s", (max_history_id - config.get("trim_history_length"), sid))
def solve_cool_lowest(self, sid): self.data['cool_lowest'] = db.c.fetch_var( "SELECT MIN(song_cool_end) FROM r4_song_sid JOIN r4_songs USING (song_id) WHERE album_id = %s AND sid = %s AND song_exists = TRUE", (self.id, sid)) if self.data['cool_lowest'] > timestamp(): self.data['cool'] = True else: self.data['cool'] = False db.c.update( "UPDATE r4_album_sid SET album_cool_lowest = %s, album_cool = %s WHERE album_id = %s AND sid = %s", (self.data['cool_lowest'], self.data['cool'], self.id, sid)) return self.data['cool_lowest']
def set_privacy_status(self, isAnonymous: bool = False, getNotifications: bool = False): data = {"timestamp": int(timestamp() * 1000)} if not isAnonymous: data["privacyMode"] = 1 if isAnonymous: data["privacyMode"] = 2 if not getNotifications: data["notificationStatus"] = 2 if getNotifications: data["privacyMode"] = 1 data = json.dumps(data) response = requests.post(f"{self.api}/g/s/account/visit-settings", headers=headers.Headers(data=data).headers, data=data) if response.status_code != 200: return json.loads(response.text) else: return response.status_code
async def trigger(self, loultstate): for channel in loultstate.chans.values(): for user in channel.users.values(): if random.randint(1, 10) == 1: effect = self.BienDowmiwEffect() channel.broadcast(type='attack', date=timestamp() * 1000, event='effect', tag=effect.TAG, target_id=user.user_id, effect=effect.name, timeout=effect.timeout)
def __setitem__(self, key, value): """Write to cache.""" try: s = self._sh.open(self.filepath) s[key] = {'value': value, 'hits': 0, 'timestamp': timestamp()} self._keys.append(key) status = True except: status = False finally: s.close() return status
def inactive_checking(): last_time = 0 if os.path.isfile("%s/r4_inactive_check" % tempfile.gettempdir()): f = open("%s/r4_inactive_check" % tempfile.gettempdir()) t = f.read() f.close() try: last_time = int(t) except Exception: pass if (not last_time) or (last_time < (timestamp() - 86400)): _update_inactive()
def invite_to_chat(self, community_id, thread_id: str, userId: [str, list]): if isinstance(userId, str): userIds = [userId] elif isinstance(userId, list): userIds = userId else: raise exceptions.WrongType(type(userId)) data = json.dumps({ "uids": userIds, "timestamp": int(timestamp() * 1000) }) response = requests.post(f"{self.api}/x{community_id}/s/chat/thread/{thread_id}/member/invite?sid="+self.sid, headers={'Content-Type': 'application/json'}, data=data) return response.json()
async def trigger(self, loultstate): for channel in loultstate.chans.values(): users_lists = list(channel.users.values()) random.shuffle(users_lists) for user_receiver, user_giver in zip(channel.users.values(), users_lists): user_receiver.state.add_effect( VoiceCloneEffect(user_giver.voice_params)) channel.broadcast(type="notification", event_type="voice_shuffle", date=timestamp() * 1000, msg="Les voix des pokémons ont été mélangées!")
def record_sizes(): global _prefix gc.collect() linecache.clearcache() try: d = os.path.join(tempfile.gettempdir(), "rw_memory_%s_%s.json" % (_prefix, int(timestamp()))) meliae.scanner.dump_all_objects(d) except: pass
def delete_message(self, chatId: str, messageId: str, asStaff: bool = False, reason: str = None): data = { "adminOpName": 102, "adminOpNote": {"content": reason}, "timestamp": int(timestamp() * 1000) } data = json.dumps(data) if not asStaff: response = requests.delete(f"{self.api}/g/s/chat/thread/{chatId}/message/{messageId}", headers=headers.Headers().headers) else: response = requests.post(f"{self.api}/g/s/chat/thread/{chatId}/message/{messageId}/admin", headers=headers.Headers(data=data).headers, data=data) if response.status_code != 200: return json.loads(response.text) else: return response.status_code
def test_datetime_unixts(module, unixts, tz): v = module.Datetime(unixts=unixts, tz=tz) today = date.today() now = datetime.now() if tz is None else datetime.now(UTC).astimezone(tz) assert v(today) == datetime.combine(today, time(tzinfo=tz)) assert v(now) == now assert v.clone() == v assert pickle.loads(pickle.dumps(v)) == v if unixts: ts = timestamp() assert ( v(ts) == datetime.fromtimestamp(ts) if tz is None else datetime.fromtimestamp(ts, UTC).astimezone(tz) ) else: with pytest.raises(exc.InvalidTypeError) as info: v(timestamp()) assert info.value.expected == datetime assert info.value.actual == float
def is_eqmktopen(self, time): second = (time.timestamp() + 8 * 3600) % 86400 if time.weekday() < 5: if second < 3600: return True if second >= 33600 and second < 43200: return True if second >= 46800 and second < 59700: return True if second >= 62100: return True return False
def adminDeleteMessage(self, mid, community_id, thread_id): result = requests.post( f"{self.api}x{community_id}/s/chat/thread/{thread_id}/message/{mid}/admin?sid=" + self.sid, data=json.dumps({ "adminOpName": 102, "timestamp": (int(timestamp() * 1000)) }), headers={ 'Content-Type': 'application/json' }).json() return result
def test_message_sendlater_invalid_channel_id(): # Test if InputError is raised when given invalid channel id clear_v1_http() user = auth_register_v2_http('*****@*****.**', 'password123', 'Terry', 'Wills').json() channels_create_v2_http(user['token'], 'TERRYS CHANNEL', True).json() time = datetime.now().replace(microsecond=0) + timedelta(0, 3) time_sent = time.timestamp() message_sendlater_v1_http(user['token'], -1, 'anyone here?', time_sent).status_code == 400
async def change_module(self, module: str, isEnabled: bool): if module.lower() == "chat": mod = "module.chat.enabled" elif module.lower() == "livechat": mod = "module.chat.avChat.videoEnabled" elif module.lower() == "screeningroom": mod = "module.chat.avChat.screeningRoomEnabled" elif module.lower() == "publicchats": mod = "module.chat.publicChat.enabled" elif module.lower() == "posts": mod = "module.post.enabled" elif module.lower() == "ranking": mod = "module.ranking.enabled" elif module.lower() == "leaderboards": mod = "module.ranking.leaderboardEnabled" elif module.lower() == "featured": mod = "module.featured.enabled" elif module.lower() == "featuredposts": mod = "module.featured.postEnabled" elif module.lower() == "featuredusers": mod = "module.featured.memberEnabled" elif module.lower() == "featuredchats": mod = "module.featured.publicChatRoomEnabled" elif module.lower() == "sharedfolder": mod = "module.sharedFolder.enabled" elif module.lower() == "influencer": mod = "module.influencer.enabled" elif module.lower() == "catalog": mod = "module.catalog.enabled" elif module.lower() == "externalcontent": mod = "module.externalContent.enabled" elif module.lower() == "topiccategories": mod = "module.topicCategories.enabled" else: raise exceptions.SpecifyType(module.lower()) data = json.dumps({ "path": mod, "value": isEnabled, "timestamp": int(timestamp() * 1000) }) if self.comId is None: raise exceptions.CommunityNeeded() async with self.session.post( f"{self.api}/x{self.comId}/s/community/configuration", headers=self.parse_headers(data=data), data=data) as response: if response.status != 200: return exceptions.CheckException( json.loads(await response.text())) else: return response.status
def client_config(self): data = json.dumps({ "deviceID": self.device_id, "bundleID": "com.narvii.amino.master", "clientType": 100, "timezone": -timezone // 1000, "systemPushEnabled": True, "locale": locale()[0], "timestamp": int(timestamp() * 1000) }) response = requests.post(f"{self.api}/g/s/device", headers=headers.Headers(data=data).headers, data=data) if response.status_code == 200: self.configured = True
def change_sidepanel_color(self, color: str): data = json.dumps({ "path": "appearance.leftSidePanel.style.iconColor", "value": color, "timestamp": int(timestamp() * 1000) }) response = requests.post( f"{self.api}/x{self.comId}/s/community/configuration", headers=headers.Headers(data=data).headers, data=data) if response.status_code == 200: return response.status_code else: return json.loads(response.text)
def test_message_sendlater_message_too_long(): # InputError raised if message given is more than 1000 characters clear_v1() user = auth_register_v2('*****@*****.**', 'pasword24323132', 'Tinker', 'Bell') channel = channels_create_v2(user['token'], 'Insert Title Here', True) time = datetime.now().replace(microsecond=0) + timedelta(0, 3) time_sent = time.timestamp() with pytest.raises(InputError): message_sendlater_v1(user['token'], channel['channel_id'], 'L' * 1001, time_sent)
def upload_theme(self, themePackUrl: str): data = json.dumps({ "themePackUrl": themePackUrl, "timestamp": int(timestamp() * 1000) }) if self.comId is None: raise exceptions.CommunityNeeded response = requests.post( f"{self.api}/x{self.comId}/s/community/settings", data=data, headers=headers.Headers(data=data).headers) if response.status_code == 200: return response.status_code else: return json.loads(response.text)
def ajax(request, user, user_id): if user is not False: return JsonResponse( { 'version': '0.1.0', 'status': 302, 'user': { 'id': user.user_id, 'name': user.full_name, 'registered': timestamp(user.date_registered.utctimetuple()), 'last_login': timestamp(user.last_login.utctimetuple()), 'email': { 'primary': user.email_primary, 'secondary': user.email_secondary or None }, 'role': user.role.name if user.role else None, 'schedule': None } }, status=302) return JsonResponse( { 'version': '0.1.0', 'status': 404, 'reason': 'User with ID %s does not exist or is invalid' % user_id }, status=404)
def __exit__(self, exc_type, exc_val, exc_tb): T1 = timestamp() - self.T0 stats = self.stats.get(self.name, [0, 0.0]) stats[0] += 1 stats[1] += T1 self.stats[self.name] = stats msg = self.EXIT_MESSAGE.format(name=self.name, elapsed=T1, count=stats[0], total=stats[1], avg=stats[1] / stats[0]) self.logger.info(msg)
async def reinitialise(self): """Re-instantiates the polls saved to file""" decoded = {} with open(self._dest) as file: decoded = json.loads(file.read()) for key, val in decoded.items(): if val["timestamp"] + val["duration"] <= timestamp(): continue restored_poll = await Poll.restore(val) if restored_poll is not None: self[key] = restored_poll
def add_user_tags(): logger.debug("function add_user_tags __enter__") #print (request.args) if request.method == 'POST' or request.method == 'GET': user_tags = UserTags() user_tags.user_id = request.values.get("user_id", '', type=str) # user_id user_tags.tags = request.values.get("tags", '', type=str).replace(',', '|') # tags user_tags.create_time = timestamp() user_tags.update_time = timestamp() ut = UserTags.query.filter( UserTags.user_id == user_tags.user_id).first() if ut: logger.info("user exist, update. user_id: " + str(ut.user_id)) ut.user_id = user_tags.user_id ut.tags = user_tags.tags.replace(',', '|') ut.update_time = user_tags.update_time if 'user_tags_update_times' in session: session['user_tags_update_times'] = session[ 'user_tags_update_times'] + 1 else: session['user_tags_update_times'] = 1 ut.modify_times = session['user_tags_update_times'] #ut.session.add() db.session.commit() end = '{"code": 1000, "msg": "%s" }' % ("用户标签已更新。") return json.loads(json.dumps(end)) else: db.session.add(user_tags) db.session.commit() logger.info("user tags added, user_id: " + str(user_tags.user_id)) end = '{"code": 1000, "msg": "%s" }' % ("用户标签已添加。") return json.loads(json.dumps(end)) logger.warning("error, GET/POST wrong. ") end = '{"code": 1003, "msg": "%s" }' % ("请求方法不正确。") retstr = json.loads(json.dumps(end.encode('utf-8'))) return retstr
def add_influencer(self, userId: str, monthlyFee: int): data = json.dumps({ "monthlyFee": monthlyFee, "timestamp": int(timestamp() * 1000) }) if self.comId is None: raise exceptions.CommunityNeeded() response = requests.post( f"{self.api}/x{self.comId}/s/influencer/{userId}", headers=headers.Headers(data=data).headers, data=data) if response.status_code == 200: return response.status_code else: return json.loads(response.text)
def change_guidelines(self, message: str): data = json.dumps({ "content": message, "timestamp": int(timestamp() * 1000) }) if self.comId is None: raise exceptions.CommunityNeeded() response = requests.post( f"{self.api}/x{self.comId}/s/community/guideline", headers=headers.Headers(data=data).headers, data=data) if response.status_code == 200: return response.status_code else: return json.loads(response.text)