本文整理汇总了Python中rainwave.user.User类的典型用法代码示例。如果您正苦于以下问题:Python User类的具体用法?Python User怎么用?Python User使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了User类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _process_line
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
示例2: Bootstrap
class Bootstrap(api.web.APIHandler):
description = (
"Bootstrap a Rainwave client. Provides user info, API key, station info, relay info, and more. "
"If you run a GET query to this URL, you will receive a Javascript file containing a single variable called BOOTSTRAP. While this is largely intended for the purposes of the main site, you may use this. "
"If you run a POST query to this URL, you will receive a JSON object."
)
phpbb_auth = True
auth_required = False
login_required = False
sid_required = False
allow_get = False
def prepare(self):
super(Bootstrap, self).prepare()
if not self.user:
self.user = User(1)
self.user.ensure_api_key()
# def finish(self, *args, **kwargs):
# self.write_output()
# super(Bootstrap, self).finish(*args, **kwargs)
def get(self):
self.set_header("Content-Type", "text/javascript")
self.append("locales", api.locale.locale_names)
self.append("cookie_domain", config.get("cookie_domain"))
self.post()
self.write("var BOOTSTRAP=")
def post(self):
info.attach_info_to_request(self, extra_list=self.get_cookie("r4_active_list"))
self.append("stream_filename", config.get_station(self.sid, "stream_filename"))
self.append("station_list", config.station_list)
self.append("relays", config.public_relays[self.sid])
示例3: MainIndex
class MainIndex(api.web.HTMLRequest):
description = "Main Rainwave page."
auth_required = False
login_required = False
sid_required = False
def prepare(self):
super(MainIndex, self).prepare()
self.json_payload = []
if not self.user:
self.user = User(1)
self.user.ensure_api_key(self.request.remote_ip)
self.user.data['sid'] = self.sid
def append(self, key, value):
self.json_payload.append({ key: value })
def get(self):
info.attach_info_to_request(self, all_lists=True)
self.append("api_info", { "time": int(time.time()) })
self.render("index.html", request=self,
site_description=self.locale.translate("station_description_id_%s" % self.sid),
revision_number=config.build_number,
api_url=config.get("api_external_url_prefix"),
cookie_domain=config.get("cookie_domain"),
locales=api.locale.locale_names_json)
示例4: MainIndex
class MainIndex(api.web.HTMLRequest):
description = "Main Rainwave page."
auth_required = config.has("index_requires_login") and config.get("index_requires_login")
login_required = config.has("index_requires_login") and config.get("index_requires_login")
sid_required = False
beta = False
page_template = "r4_index.html"
js_dir = "js4"
def set_default_headers(self):
self.set_header("X-Frame-Options", "SAMEORIGIN")
def prepare(self):
super(MainIndex, self).prepare()
self.json_payload = {}
self.jsfiles = None
if not self.user:
self.user = User(1)
self.user.ensure_api_key()
if self.beta or config.get("web_developer_mode") or config.get("developer_mode") or config.get("test_mode"):
buildtools.bake_beta_css()
buildtools.bake_beta_templates()
self.jsfiles = []
for root, subdirs, files in os.walk(
os.path.join(os.path.dirname(__file__), "../static/%s" % self.js_dir)
): # pylint: disable=W0612
for f in files:
if f.endswith(".js"):
self.jsfiles.append(os.path.join(root[root.find("static/%s" % self.js_dir) :], f))
def append(self, key, value):
self.json_payload[key] = value
def get(self):
self.mobile = (
self.request.headers.get("User-Agent").lower().find("mobile") != -1
or self.request.headers.get("User-Agent").lower().find("android") != -1
)
if not self.beta:
info.attach_info_to_request(self, extra_list=self.get_cookie("r4_active_list"))
self.append("api_info", {"time": int(timestamp())})
self.render(
self.page_template,
request=self,
site_description=self.locale.translate("station_description_id_%s" % self.sid),
revision_number=config.build_number,
jsfiles=self.jsfiles,
api_url=config.get("api_external_url_prefix"),
cookie_domain=config.get("cookie_domain"),
locales=api.locale.locale_names_json,
relays=config.public_relays_json[self.sid],
stream_filename=config.get_station(self.sid, "stream_filename"),
station_list=config.station_list_json,
apple_home_screen_icon=config.get_station(self.sid, "apple_home_screen_icon"),
mobile=self.mobile,
)
示例5: get_next
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] or not line[pos]['song_id']:
pass
else:
entry = line.pop(pos)
song = playlist.Song.load_from_id(entry['song_id'], sid)
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()
user_sid = u.get_tuned_in_sid()
if u.has_requests():
u.put_in_request_line(user_sid)
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) "
"VALUES (%s, %s, %s, %s, %s)",
(u.id, song.id, time.time() - entry['line_wait_start'], len(line), request_count))
# Update the user's request cache
u.get_requests(refresh=True)
cache.set_station(sid, "request_line", line, True)
break
return song
示例6: get_next
def get_next(sid):
entry, line = get_next_entry(sid)
if not entry:
return None
user = User(entry['user_id'])
user.data['name'] = entry['username']
song = playlist.Song.load_from_id(entry['song_id'], sid)
mark_request_filled(sid, user, song, entry, line)
return song
示例7: get_next_ignoring_cooldowns
def get_next_ignoring_cooldowns(sid):
line = db.c.fetch_all(LINE_SQL, (sid,))
if not line or len(line) == 0:
return None
entry = line[0]
user = User(entry['user_id'])
user.data['name'] = entry['username']
song = playlist.Song.load_from_id(user.get_top_request_song_id_any(sid), sid)
mark_request_filled(sid, user, song, entry, line)
return song
示例8: test_get_request
def test_get_request(self):
db.c.update("DELETE FROM r4_listeners")
db.c.update("DELETE FROM r4_request_store")
u = User(2)
u.authorize(1, None, None, True)
u.put_in_request_line(1)
# TODO: Use proper request class here instead of DB call
db.c.update("INSERT INTO r4_listeners (sid, user_id, listener_icecast_id) VALUES (1, %s, 1)", (u.id,))
db.c.update("INSERT INTO r4_request_store (user_id, song_id, sid) VALUES (%s, %s, 1)", (u.id, self.song1.id,))
e = Election.create(1)
req = e.get_request()
self.assertNotEqual(None, req)
self.assertEqual(self.song1.id, req.id)
示例9: prepare
def prepare(self):
super(MainIndex, self).prepare()
if not cache.get_station(self.sid, "sched_current"):
raise APIException(
"server_just_started", "Rainwave is Rebooting, Please Try Again in a Few Minutes", http_code=500
)
# self.json_payload = {}
self.jsfiles = None
if not self.user:
self.user = User(1)
self.user.ip_address = self.request.remote_ip
self.user.ensure_api_key()
if self.beta or config.get("web_developer_mode") or config.get("developer_mode") or config.get("test_mode"):
buildtools.bake_beta_css()
buildtools.bake_beta_templates()
self.jsfiles = []
for root, subdirs, files in os.walk(
os.path.join(os.path.dirname(__file__), "../static/%s" % self.js_dir)
): # pylint: disable=W0612
for f in files:
if f.endswith(".js"):
self.jsfiles.append(os.path.join(root[root.find("static/%s" % self.js_dir) :], f))
示例10: _do_auth
def _do_auth(self, message):
try:
if not "user_id" in message or not message['user_id']:
self.write_message({ "wserror": { "tl_key": "missing_argument", "text": self.locale.translate("missing_argument", argument="user_id") } })
if not isinstance(message['user_id'], numbers.Number):
self.write_message({ "wserror": { "tl_key": "invalid_argument", "text": self.locale.translate("invalid_argument", argument="user_id") } })
if not "key" in message or not message['key']:
self.write_message({ "wserror": { "tl_key": "missing_argument", "text": self.locale.translate("missing_argument", argument="key") } })
self.user = User(message['user_id'])
self.user.ip_address = self.request.remote_ip
self.user.authorize(None, message['key'])
if not self.user.authorized:
self.write_message({ "wserror": { "tl_key": "auth_failed", "text": self.locale.translate("auth_failed") } })
self.close()
return
self.authorized = True
self.uuid = str(uuid.uuid4())
global sessions
sessions[self.sid].append(self)
self.votes_by_key = self.request.remote_ip if self.user.is_anonymous() else self.user.id
self.refresh_user()
# no need to send the user's data to the user as that would have come with bootstrap
# and will come with each synchronization of the schedule anyway
self.write_message({ "wsok": True })
# since this will be the first action in any websocket interaction though,
# it'd be a good time to send a station offline message.
self._station_offline_check()
except Exception as e:
log.exception("websocket", "Exception during authentication.", e)
self.close()
示例11: prepare
def prepare(self):
super(MainIndex, self).prepare()
self.json_payload = []
if not self.user:
self.user = User(1)
self.user.ensure_api_key(self.request.remote_ip)
self.user.data['sid'] = self.sid
示例12: prepare
def prepare(self):
if self.local_only and not self.request.remote_ip in config.get("api_trusted_ip_addresses"):
log.info("api", "Rejected %s request from %s, untrusted address." % (self.url, self.request.remote_ip))
raise APIException("rejected", text="You are not coming from a trusted address.")
if self.allow_cors:
self.set_header("Access-Control-Allow-Origin", "*")
self.set_header("Access-Control-Max-Age", "600")
self.set_header("Access-Control-Allow-Credentials", "false")
if not isinstance(self.locale, locale.RainwaveLocale):
self.locale = self.get_browser_locale()
self.setup_output()
if 'in_order' in self.request.arguments:
self._output = []
self._output_array = True
else:
self._output = {}
if not self.sid:
self.sid = fieldtypes.integer(self.get_cookie("r4_sid", None))
hostname = self.request.headers.get('Host', None)
if hostname:
hostname = unicode(hostname).split(":")[0]
if hostname in config.station_hostnames:
self.sid = config.station_hostnames[hostname]
sid_arg = fieldtypes.integer(self.get_argument("sid", None))
if sid_arg is not None:
self.sid = sid_arg
if self.sid is None and self.sid_required:
raise APIException("missing_station_id", http_code=400)
self.arg_parse()
self.sid_check()
if self.sid:
self.set_cookie("r4_sid", str(self.sid), expires_days=365)
if self.phpbb_auth:
self.do_phpbb_auth()
else:
self.rainwave_auth()
if not self.user and self.auth_required:
raise APIException("auth_required", http_code=403)
elif not self.user and not self.auth_required:
self.user = User(1)
self.user.ip_address = self.request.remote_ip
self.user.refresh(self.sid)
if self.user and config.get("store_prefs"):
self.user.save_preferences(self.request.remote_ip, self.get_cookie("r4_prefs", None))
self.permission_checks()
示例13: Bootstrap
class Bootstrap(api.web.APIHandler):
description = (
"Bootstrap a Rainwave client. Provides user info, API key, station info, relay info, and more. "
"If you run a GET query to this URL, you will receive a Javascript file containing a single variable called BOOTSTRAP. While this is largely intended for the purposes of the main site, you may use this. "
"If you run a POST query to this URL, you will receive a JSON object of the same data."
)
phpbb_auth = True
auth_required = False
login_required = False
sid_required = False
allow_get = False
def prepare(self):
super(Bootstrap, self).prepare()
if not self.user:
self.user = User(1)
self.user.ensure_api_key()
self.is_mobile = self.request.headers.get("User-Agent").lower().find("mobile") != -1 or self.request.headers.get("User-Agent").lower().find("android") != -1
def get(self):
self.set_header("Content-Type", "text/javascript")
self.post()
if self.is_mobile:
self.write("window.MOBILE = true;")
else:
self.write("window.MOBILE = false;")
self.write("var BOOTSTRAP=")
def post(self):
info.attach_info_to_request(self, live_voting=True)
self.append("build_version", config.build_number)
self.append("locale", self.locale.code)
self.append("locales", api.locale.locale_names)
self.append("cookie_domain", config.get("cookie_domain"))
self.append("on_init", [])
self.append("on_measure", [])
self.append("on_draw", [])
self.append("websocket_host", config.get("websocket_host"))
self.append("stream_filename", config.get_station(self.sid, "stream_filename"))
self.append("station_list", config.station_list)
self.append("relays", config.public_relays[self.sid])
if self.is_mobile:
self.append("mobile", True)
else:
self.append("mobile", False)
示例14: get_next
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 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()
if u.has_requests():
u.put_in_request_line(u.get_tuned_in_sid())
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, time.time() - 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)
# If we fully update the line, the user may sneak in and get 2 requests in the same election.
# This is not a good idea, so we leave it to the scheduler to issue the full cache update.
cache.set_station(sid, "request_line", line, True)
break
return song
示例15: prepare
def prepare(self):
# TODO: Language
self.info = []
self.sid = fieldtypes.integer(self.get_cookie("r4sid", "1"))
if not self.sid:
self.sid = 1
if self.request.host == "game.rainwave.cc":
self.sid = 1
elif self.request.host == "ocr.rainwave.cc":
self.sid = 2
elif self.request.host == "covers.rainwave.cc" or self.request.host == "cover.rainwave.cc":
self.sid = 3
elif self.request.host == "chiptune.rainwave.cc":
self.sid = 4
elif self.request.host == "all.rainwave.cc":
self.sid = 5
self.set_cookie("r4sid", str(self.sid), expires_days=365, domain=".rainwave.cc")
self.user = None
if not fieldtypes.integer(self.get_cookie("phpbb3_38ie8_u", "")):
self.user = User(1)
else:
user_id = int(self.get_cookie("phpbb3_38ie8_u"))
if self.get_cookie("phpbb3_38ie8_sid"):
session_id = db.c_old.fetch_var("SELECT session_id FROM phpbb_sessions WHERE session_id = %s AND session_user_id = %s", (self.get_cookie("phpbb3_38ie8_sid"), user_id))
if session_id:
db.c_old.update("UPDATE phpbb_sessions SET session_last_visit = %s, session_page = %s WHERE session_id = %s", (time.time(), "rainwave", session_id))
self.user = User(user_id)
self.user.authorize(self.sid, None, None, True)
if not self.user and self.get_cookie("phpbb3_38ie8_k"):
can_login = db.c_old.fetch_var("SELECT 1 FROM phpbb_sessions_keys WHERE key_id = %s AND user_id = %s", (hashlib.md5(self.get_cookie("phpbb3_38ie8_k")).hexdigest(), user_id))
if can_login == 1:
self.user = User(user_id)
self.user.authorize(self.sid, None, None, True)
if not self.user:
self.user = User(1)
self.user.ensure_api_key(self.request.remote_ip)
self.user.data['sid'] = self.sid