Fix SQLite Double-Quoted Strings (#2057)

* Fix __init__.py

* Fix activity_pinger.py

* Fix activity_processor.py

* Fix database.py

* Fix datafactory.py

* Fix exporter.py

* Fix graphs.py

* Fix libraries.py

* Fix mobile_app.py

* Fix newsletter_handler.py

* Fix newsletters.py

* Fix notification_handler.py

* Fix notifiers.py

* Fix plexivity_import.py

* Fix plexwatch_import.py

* Fix users.py

* Fix webauth.py
This commit is contained in:
JonnyWong16 2023-05-15 11:03:26 -07:00 committed by GitHub
parent 3a1d6322ae
commit f39b9f9087
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
17 changed files with 2220 additions and 2217 deletions

File diff suppressed because it is too large Load diff

View file

@ -99,22 +99,22 @@ def check_active_sessions(ws_request=False):
# Using the set config parameter as the interval, probably not the most accurate but # Using the set config parameter as the interval, probably not the most accurate but
# it will have to do for now. If it's a websocket request don't use this method. # it will have to do for now. If it's a websocket request don't use this method.
paused_counter = int(stream['paused_counter']) + plexpy.CONFIG.MONITORING_INTERVAL paused_counter = int(stream['paused_counter']) + plexpy.CONFIG.MONITORING_INTERVAL
monitor_db.action('UPDATE sessions SET paused_counter = ? ' monitor_db.action("UPDATE sessions SET paused_counter = ? "
'WHERE session_key = ? AND rating_key = ?', "WHERE session_key = ? AND rating_key = ?",
[paused_counter, stream['session_key'], stream['rating_key']]) [paused_counter, stream['session_key'], stream['rating_key']])
if session['state'] == 'buffering' and plexpy.CONFIG.BUFFER_THRESHOLD > 0: if session['state'] == 'buffering' and plexpy.CONFIG.BUFFER_THRESHOLD > 0:
# The stream is buffering so we need to increment the buffer_count # The stream is buffering so we need to increment the buffer_count
# We're going just increment on every monitor ping, # We're going just increment on every monitor ping,
# would be difficult to keep track otherwise # would be difficult to keep track otherwise
monitor_db.action('UPDATE sessions SET buffer_count = buffer_count + 1 ' monitor_db.action("UPDATE sessions SET buffer_count = buffer_count + 1 "
'WHERE session_key = ? AND rating_key = ?', "WHERE session_key = ? AND rating_key = ?",
[stream['session_key'], stream['rating_key']]) [stream['session_key'], stream['rating_key']])
# Check the current buffer count and last buffer to determine if we should notify # Check the current buffer count and last buffer to determine if we should notify
buffer_values = monitor_db.select('SELECT buffer_count, buffer_last_triggered ' buffer_values = monitor_db.select("SELECT buffer_count, buffer_last_triggered "
'FROM sessions ' "FROM sessions "
'WHERE session_key = ? AND rating_key = ?', "WHERE session_key = ? AND rating_key = ?",
[stream['session_key'], stream['rating_key']]) [stream['session_key'], stream['rating_key']])
if buffer_values[0]['buffer_count'] >= plexpy.CONFIG.BUFFER_THRESHOLD: if buffer_values[0]['buffer_count'] >= plexpy.CONFIG.BUFFER_THRESHOLD:
@ -125,9 +125,9 @@ def check_active_sessions(ws_request=False):
logger.info("Tautulli Monitor :: User '%s' has triggered a buffer warning." logger.info("Tautulli Monitor :: User '%s' has triggered a buffer warning."
% stream['user']) % stream['user'])
# Set the buffer trigger time # Set the buffer trigger time
monitor_db.action('UPDATE sessions ' monitor_db.action("UPDATE sessions "
'SET buffer_last_triggered = strftime("%s","now") ' "SET buffer_last_triggered = strftime('%s', 'now') "
'WHERE session_key = ? AND rating_key = ?', "WHERE session_key = ? AND rating_key = ?",
[stream['session_key'], stream['rating_key']]) [stream['session_key'], stream['rating_key']])
plexpy.NOTIFY_QUEUE.put({'stream_data': stream.copy(), 'notify_action': 'on_buffer'}) plexpy.NOTIFY_QUEUE.put({'stream_data': stream.copy(), 'notify_action': 'on_buffer'})
@ -139,9 +139,9 @@ def check_active_sessions(ws_request=False):
logger.info("Tautulli Monitor :: User '%s' has triggered multiple buffer warnings." logger.info("Tautulli Monitor :: User '%s' has triggered multiple buffer warnings."
% stream['user']) % stream['user'])
# Set the buffer trigger time # Set the buffer trigger time
monitor_db.action('UPDATE sessions ' monitor_db.action("UPDATE sessions "
'SET buffer_last_triggered = strftime("%s","now") ' "SET buffer_last_triggered = strftime('%s', 'now') "
'WHERE session_key = ? AND rating_key = ?', "WHERE session_key = ? AND rating_key = ?",
[stream['session_key'], stream['rating_key']]) [stream['session_key'], stream['rating_key']])
plexpy.NOTIFY_QUEUE.put({'stream_data': stream.copy(), 'notify_action': 'on_buffer'}) plexpy.NOTIFY_QUEUE.put({'stream_data': stream.copy(), 'notify_action': 'on_buffer'})
@ -171,8 +171,8 @@ def check_active_sessions(ws_request=False):
if not stream['stopped']: if not stream['stopped']:
# Set the stream stop time # Set the stream stop time
stream['stopped'] = helpers.timestamp() stream['stopped'] = helpers.timestamp()
monitor_db.action('UPDATE sessions SET stopped = ?, state = ? ' monitor_db.action("UPDATE sessions SET stopped = ?, state = ? "
'WHERE session_key = ? AND rating_key = ?', "WHERE session_key = ? AND rating_key = ?",
[stream['stopped'], 'stopped', stream['session_key'], stream['rating_key']]) [stream['stopped'], 'stopped', stream['session_key'], stream['rating_key']])
progress_percent = helpers.get_percent(stream['view_offset'], stream['duration']) progress_percent = helpers.get_percent(stream['view_offset'], stream['duration'])

View file

@ -331,10 +331,10 @@ class ActivityProcessor(object):
if session['live']: if session['live']:
# Check if we should group the session, select the last guid from the user # Check if we should group the session, select the last guid from the user
query = 'SELECT session_history.id, session_history_metadata.guid, session_history.reference_id ' \ query = "SELECT session_history.id, session_history_metadata.guid, session_history.reference_id " \
'FROM session_history ' \ "FROM session_history " \
'JOIN session_history_metadata ON session_history.id == session_history_metadata.id ' \ "JOIN session_history_metadata ON session_history.id == session_history_metadata.id " \
'WHERE session_history.user_id = ? ORDER BY session_history.id DESC LIMIT 1 ' "WHERE session_history.user_id = ? ORDER BY session_history.id DESC LIMIT 1 "
args = [session['user_id']] args = [session['user_id']]
@ -351,8 +351,8 @@ class ActivityProcessor(object):
else: else:
# Check if we should group the session, select the last two rows from the user # Check if we should group the session, select the last two rows from the user
query = 'SELECT id, rating_key, view_offset, reference_id FROM session_history ' \ query = "SELECT id, rating_key, view_offset, reference_id FROM session_history " \
'WHERE user_id = ? AND rating_key = ? ORDER BY id DESC LIMIT 2 ' "WHERE user_id = ? AND rating_key = ? ORDER BY id DESC LIMIT 2 "
args = [session['user_id'], session['rating_key']] args = [session['user_id'], session['rating_key']]
@ -375,7 +375,7 @@ class ActivityProcessor(object):
marker_first, marker_final marker_first, marker_final
) )
query = 'UPDATE session_history SET reference_id = ? WHERE id = ? ' query = "UPDATE session_history SET reference_id = ? WHERE id = ? "
# If previous session view offset less than watched percent, # If previous session view offset less than watched percent,
# and new session view offset is greater, # and new session view offset is greater,
@ -547,12 +547,12 @@ class ActivityProcessor(object):
return session['id'] return session['id']
def get_sessions(self, user_id=None, ip_address=None): def get_sessions(self, user_id=None, ip_address=None):
query = 'SELECT * FROM sessions' query = "SELECT * FROM sessions"
args = [] args = []
if str(user_id).isdigit(): if str(user_id).isdigit():
ip = ' GROUP BY ip_address' if ip_address else '' ip = " GROUP BY ip_address" if ip_address else ""
query += ' WHERE user_id = ?' + ip query += " WHERE user_id = ?" + ip
args.append(user_id) args.append(user_id)
sessions = self.db.select(query, args) sessions = self.db.select(query, args)
@ -560,8 +560,8 @@ class ActivityProcessor(object):
def get_session_by_key(self, session_key=None): def get_session_by_key(self, session_key=None):
if str(session_key).isdigit(): if str(session_key).isdigit():
session = self.db.select_single('SELECT * FROM sessions ' session = self.db.select_single("SELECT * FROM sessions "
'WHERE session_key = ? ', "WHERE session_key = ? ",
args=[session_key]) args=[session_key])
if session: if session:
return session return session
@ -570,8 +570,8 @@ class ActivityProcessor(object):
def get_session_by_id(self, session_id=None): def get_session_by_id(self, session_id=None):
if session_id: if session_id:
session = self.db.select_single('SELECT * FROM sessions ' session = self.db.select_single("SELECT * FROM sessions "
'WHERE session_id = ? ', "WHERE session_id = ? ",
args=[session_id]) args=[session_id])
if session: if session:
return session return session
@ -597,15 +597,15 @@ class ActivityProcessor(object):
def delete_session(self, session_key=None, row_id=None): def delete_session(self, session_key=None, row_id=None):
if str(session_key).isdigit(): if str(session_key).isdigit():
self.db.action('DELETE FROM sessions WHERE session_key = ?', [session_key]) self.db.action("DELETE FROM sessions WHERE session_key = ?", [session_key])
elif str(row_id).isdigit(): elif str(row_id).isdigit():
self.db.action('DELETE FROM sessions WHERE id = ?', [row_id]) self.db.action("DELETE FROM sessions WHERE id = ?", [row_id])
def set_session_last_paused(self, session_key=None, timestamp=None): def set_session_last_paused(self, session_key=None, timestamp=None):
if str(session_key).isdigit(): if str(session_key).isdigit():
result = self.db.select('SELECT last_paused, paused_counter ' result = self.db.select("SELECT last_paused, paused_counter "
'FROM sessions ' "FROM sessions "
'WHERE session_key = ?', args=[session_key]) "WHERE session_key = ?", args=[session_key])
paused_counter = None paused_counter = None
for session in result: for session in result:
@ -626,15 +626,15 @@ class ActivityProcessor(object):
def increment_session_buffer_count(self, session_key=None): def increment_session_buffer_count(self, session_key=None):
if str(session_key).isdigit(): if str(session_key).isdigit():
self.db.action('UPDATE sessions SET buffer_count = buffer_count + 1 ' self.db.action("UPDATE sessions SET buffer_count = buffer_count + 1 "
'WHERE session_key = ?', "WHERE session_key = ?",
[session_key]) [session_key])
def get_session_buffer_count(self, session_key=None): def get_session_buffer_count(self, session_key=None):
if str(session_key).isdigit(): if str(session_key).isdigit():
buffer_count = self.db.select_single('SELECT buffer_count ' buffer_count = self.db.select_single("SELECT buffer_count "
'FROM sessions ' "FROM sessions "
'WHERE session_key = ?', "WHERE session_key = ?",
[session_key]) [session_key])
if buffer_count: if buffer_count:
return buffer_count['buffer_count'] return buffer_count['buffer_count']
@ -643,15 +643,15 @@ class ActivityProcessor(object):
def set_session_buffer_trigger_time(self, session_key=None): def set_session_buffer_trigger_time(self, session_key=None):
if str(session_key).isdigit(): if str(session_key).isdigit():
self.db.action('UPDATE sessions SET buffer_last_triggered = strftime("%s","now") ' self.db.action("UPDATE sessions SET buffer_last_triggered = strftime('%s', 'now') "
'WHERE session_key = ?', "WHERE session_key = ?",
[session_key]) [session_key])
def get_session_buffer_trigger_time(self, session_key=None): def get_session_buffer_trigger_time(self, session_key=None):
if str(session_key).isdigit(): if str(session_key).isdigit():
last_time = self.db.select_single('SELECT buffer_last_triggered ' last_time = self.db.select_single("SELECT buffer_last_triggered "
'FROM sessions ' "FROM sessions "
'WHERE session_key = ?', "WHERE session_key = ?",
[session_key]) [session_key])
if last_time: if last_time:
return last_time['buffer_last_triggered'] return last_time['buffer_last_triggered']
@ -660,12 +660,12 @@ class ActivityProcessor(object):
def set_temp_stopped(self): def set_temp_stopped(self):
stopped_time = helpers.timestamp() stopped_time = helpers.timestamp()
self.db.action('UPDATE sessions SET stopped = ?', [stopped_time]) self.db.action("UPDATE sessions SET stopped = ?", [stopped_time])
def increment_write_attempts(self, session_key=None): def increment_write_attempts(self, session_key=None):
if str(session_key).isdigit(): if str(session_key).isdigit():
session = self.get_session_by_key(session_key=session_key) session = self.get_session_by_key(session_key=session_key)
self.db.action('UPDATE sessions SET write_attempts = ? WHERE session_key = ?', self.db.action("UPDATE sessions SET write_attempts = ? WHERE session_key = ?",
[session['write_attempts'] + 1, session_key]) [session['write_attempts'] + 1, session_key])
def set_marker(self, session_key=None, marker_idx=None, marker_type=None): def set_marker(self, session_key=None, marker_idx=None, marker_type=None):
@ -674,13 +674,13 @@ class ActivityProcessor(object):
int(marker_type == 'commercial'), int(marker_type == 'commercial'),
int(marker_type == 'credits') int(marker_type == 'credits')
] ]
self.db.action('UPDATE sessions SET intro = ?, commercial = ?, credits = ?, marker = ? ' self.db.action("UPDATE sessions SET intro = ?, commercial = ?, credits = ?, marker = ? "
'WHERE session_key = ?', "WHERE session_key = ?",
marker_args + [marker_idx, session_key]) marker_args + [marker_idx, session_key])
def set_watched(self, session_key=None): def set_watched(self, session_key=None):
self.db.action('UPDATE sessions SET watched = ? ' self.db.action("UPDATE sessions SET watched = ? "
'WHERE session_key = ?', "WHERE session_key = ?",
[1, session_key]) [1, session_key])
def write_continued_session(self, user_id=None, machine_id=None, media_type=None, stopped=None): def write_continued_session(self, user_id=None, machine_id=None, media_type=None, stopped=None):
@ -689,9 +689,9 @@ class ActivityProcessor(object):
self.db.upsert(table_name='sessions_continued', key_dict=keys, value_dict=values) self.db.upsert(table_name='sessions_continued', key_dict=keys, value_dict=values)
def is_initial_stream(self, user_id=None, machine_id=None, media_type=None, started=None): def is_initial_stream(self, user_id=None, machine_id=None, media_type=None, started=None):
last_session = self.db.select_single('SELECT stopped ' last_session = self.db.select_single("SELECT stopped "
'FROM sessions_continued ' "FROM sessions_continued "
'WHERE user_id = ? AND machine_id = ? AND media_type = ? ' "WHERE user_id = ? AND machine_id = ? AND media_type = ? "
'ORDER BY stopped DESC', "ORDER BY stopped DESC",
[user_id, machine_id, media_type]) [user_id, machine_id, media_type])
return int(started - last_session.get('stopped', 0) >= plexpy.CONFIG.NOTIFY_CONTINUED_SESSION_THRESHOLD) return int(started - last_session.get('stopped', 0) >= plexpy.CONFIG.NOTIFY_CONTINUED_SESSION_THRESHOLD)

View file

@ -54,7 +54,7 @@ def validate_database(database=None):
return 'Uncaught exception' return 'Uncaught exception'
try: try:
connection.execute('SELECT started from session_history') connection.execute("SELECT started from session_history")
connection.close() connection.close()
except (sqlite3.OperationalError, sqlite3.DatabaseError, ValueError) as e: except (sqlite3.OperationalError, sqlite3.DatabaseError, ValueError) as e:
logger.error("Tautulli Database :: Invalid database specified: %s", e) logger.error("Tautulli Database :: Invalid database specified: %s", e)
@ -92,11 +92,11 @@ def import_tautulli_db(database=None, method=None, backup=False):
set_is_importing(True) set_is_importing(True)
db = MonitorDatabase() db = MonitorDatabase()
db.connection.execute('BEGIN IMMEDIATE') db.connection.execute("BEGIN IMMEDIATE")
db.connection.execute('ATTACH ? AS import_db', [database]) db.connection.execute("ATTACH ? AS import_db", [database])
try: try:
version_info = db.select_single('SELECT * FROM import_db.version_info WHERE key = "version"') version_info = db.select_single("SELECT * FROM import_db.version_info WHERE key = 'version'")
import_db_version = version_info['value'] import_db_version = version_info['value']
except (sqlite3.OperationalError, KeyError): except (sqlite3.OperationalError, KeyError):
import_db_version = 'v2.6.10' import_db_version = 'v2.6.10'
@ -105,7 +105,7 @@ def import_tautulli_db(database=None, method=None, backup=False):
import_db_version = helpers.version_to_tuple(import_db_version) import_db_version = helpers.version_to_tuple(import_db_version)
# Get the current number of used ids in the session_history table # Get the current number of used ids in the session_history table
session_history_seq = db.select_single('SELECT seq FROM sqlite_sequence WHERE name = "session_history"') session_history_seq = db.select_single("SELECT seq FROM sqlite_sequence WHERE name = 'session_history'")
session_history_rows = session_history_seq.get('seq', 0) session_history_rows = session_history_seq.get('seq', 0)
session_history_tables = ('session_history', 'session_history_metadata', 'session_history_media_info') session_history_tables = ('session_history', 'session_history_metadata', 'session_history_media_info')
@ -113,11 +113,11 @@ def import_tautulli_db(database=None, method=None, backup=False):
if method == 'merge': if method == 'merge':
logger.info("Tautulli Database :: Creating temporary database tables to re-index grouped session history.") logger.info("Tautulli Database :: Creating temporary database tables to re-index grouped session history.")
for table_name in session_history_tables: for table_name in session_history_tables:
db.action('CREATE TABLE {table}_copy AS SELECT * FROM import_db.{table}'.format(table=table_name)) db.action("CREATE TABLE {table}_copy AS SELECT * FROM import_db.{table}".format(table=table_name))
db.action('UPDATE {table}_copy SET id = id + ?'.format(table=table_name), db.action("UPDATE {table}_copy SET id = id + ?".format(table=table_name),
[session_history_rows]) [session_history_rows])
if table_name == 'session_history': if table_name == 'session_history':
db.action('UPDATE {table}_copy SET reference_id = reference_id + ?'.format(table=table_name), db.action("UPDATE {table}_copy SET reference_id = reference_id + ?".format(table=table_name),
[session_history_rows]) [session_history_rows])
# Migrate section_id from session_history_metadata to session_history # Migrate section_id from session_history_metadata to session_history
@ -128,28 +128,28 @@ def import_tautulli_db(database=None, method=None, backup=False):
else: else:
from_db_name = 'import_db' from_db_name = 'import_db'
copy = '' copy = ''
db.action('ALTER TABLE {from_db}.session_history{copy} ' db.action("ALTER TABLE {from_db}.session_history{copy} "
'ADD COLUMN section_id INTEGER'.format(from_db=from_db_name, "ADD COLUMN section_id INTEGER".format(from_db=from_db_name,
copy=copy)) copy=copy))
db.action('UPDATE {from_db}.session_history{copy} SET section_id = (' db.action("UPDATE {from_db}.session_history{copy} SET section_id = ("
'SELECT section_id FROM {from_db}.session_history_metadata{copy} ' "SELECT section_id FROM {from_db}.session_history_metadata{copy} "
'WHERE {from_db}.session_history_metadata{copy}.id = ' "WHERE {from_db}.session_history_metadata{copy}.id = "
'{from_db}.session_history{copy}.id)'.format(from_db=from_db_name, "{from_db}.session_history{copy}.id)".format(from_db=from_db_name,
copy=copy)) copy=copy))
# Keep track of all table columns so that duplicates can be removed after importing # Keep track of all table columns so that duplicates can be removed after importing
table_columns = {} table_columns = {}
tables = db.select('SELECT name FROM import_db.sqlite_master ' tables = db.select("SELECT name FROM import_db.sqlite_master "
'WHERE type = "table" AND name NOT LIKE "sqlite_%"' "WHERE type = 'table' AND name NOT LIKE 'sqlite_%'"
'ORDER BY name') "ORDER BY name")
for table in tables: for table in tables:
table_name = table['name'] table_name = table['name']
if table_name == 'sessions' or table_name == 'version_info': if table_name == 'sessions' or table_name == 'version_info':
# Skip temporary sessions table # Skip temporary sessions table
continue continue
current_table = db.select('PRAGMA main.table_info({table})'.format(table=table_name)) current_table = db.select("PRAGMA main.table_info({table})".format(table=table_name))
if not current_table: if not current_table:
# Skip table does not exits # Skip table does not exits
continue continue
@ -158,8 +158,8 @@ def import_tautulli_db(database=None, method=None, backup=False):
if method == 'overwrite': if method == 'overwrite':
# Clear the table and reset the autoincrement ids # Clear the table and reset the autoincrement ids
db.action('DELETE FROM {table}'.format(table=table_name)) db.action("DELETE FROM {table}".format(table=table_name))
db.action('DELETE FROM sqlite_sequence WHERE name = ?', [table_name]) db.action("DELETE FROM sqlite_sequence WHERE name = ?", [table_name])
if method == 'merge' and table_name in session_history_tables: if method == 'merge' and table_name in session_history_tables:
from_db_name = 'main' from_db_name = 'main'
@ -170,7 +170,7 @@ def import_tautulli_db(database=None, method=None, backup=False):
# Get the list of columns to import # Get the list of columns to import
current_columns = [c['name'] for c in current_table] current_columns = [c['name'] for c in current_table]
import_table = db.select('PRAGMA {from_db}.table_info({from_table})'.format(from_db=from_db_name, import_table = db.select("PRAGMA {from_db}.table_info({from_table})".format(from_db=from_db_name,
from_table=from_table_name)) from_table=from_table_name))
if method == 'merge' and table_name not in session_history_tables: if method == 'merge' and table_name not in session_history_tables:
@ -182,29 +182,29 @@ def import_tautulli_db(database=None, method=None, backup=False):
insert_columns = ', '.join(import_columns) insert_columns = ', '.join(import_columns)
# Insert the data with ignore instead of replace to be safe # Insert the data with ignore instead of replace to be safe
db.action('INSERT OR IGNORE INTO {table} ({columns}) ' db.action("INSERT OR IGNORE INTO {table} ({columns}) "
'SELECT {columns} FROM {from_db}.{from_table}'.format(table=table_name, "SELECT {columns} FROM {from_db}.{from_table}".format(table=table_name,
columns=insert_columns, columns=insert_columns,
from_db=from_db_name, from_db=from_db_name,
from_table=from_table_name)) from_table=from_table_name))
db.connection.execute('DETACH import_db') db.connection.execute("DETACH import_db")
if method == 'merge': if method == 'merge':
for table_name, columns in sorted(table_columns.items()): for table_name, columns in sorted(table_columns.items()):
duplicate_columns = ', '.join([c for c in columns if c not in ('id', 'reference_id')]) duplicate_columns = ', '.join([c for c in columns if c not in ('id', 'reference_id')])
logger.info("Tautulli Database :: Removing duplicate rows from database table '%s'.", table_name) logger.info("Tautulli Database :: Removing duplicate rows from database table '%s'.", table_name)
if table_name in session_history_tables[1:]: if table_name in session_history_tables[1:]:
db.action('DELETE FROM {table} WHERE id NOT IN ' db.action("DELETE FROM {table} WHERE id NOT IN "
'(SELECT id FROM session_history)'.format(table=table_name)) "(SELECT id FROM session_history)".format(table=table_name))
else: else:
db.action('DELETE FROM {table} WHERE id NOT IN ' db.action("DELETE FROM {table} WHERE id NOT IN "
'(SELECT MIN(id) FROM {table} GROUP BY {columns})'.format(table=table_name, "(SELECT MIN(id) FROM {table} GROUP BY {columns})".format(table=table_name,
columns=duplicate_columns)) columns=duplicate_columns))
logger.info("Tautulli Database :: Deleting temporary database tables.") logger.info("Tautulli Database :: Deleting temporary database tables.")
for table_name in session_history_tables: for table_name in session_history_tables:
db.action('DROP TABLE {table}_copy'.format(table=table_name)) db.action("DROP TABLE {table}_copy".format(table=table_name))
vacuum() vacuum()
@ -217,7 +217,7 @@ def import_tautulli_db(database=None, method=None, backup=False):
def integrity_check(): def integrity_check():
monitor_db = MonitorDatabase() monitor_db = MonitorDatabase()
result = monitor_db.select_single('PRAGMA integrity_check') result = monitor_db.select_single("PRAGMA integrity_check")
return result return result
@ -227,7 +227,7 @@ def clear_table(table=None):
logger.debug("Tautulli Database :: Clearing database table '%s'." % table) logger.debug("Tautulli Database :: Clearing database table '%s'." % table)
try: try:
monitor_db.action('DELETE FROM %s' % table) monitor_db.action("DELETE FROM %s" % table)
vacuum() vacuum()
return True return True
except Exception as e: except Exception as e:
@ -286,7 +286,7 @@ def delete_user_history(user_id=None):
monitor_db = MonitorDatabase() monitor_db = MonitorDatabase()
# Get all history associated with the user_id # Get all history associated with the user_id
result = monitor_db.select('SELECT id FROM session_history WHERE user_id = ?', result = monitor_db.select("SELECT id FROM session_history WHERE user_id = ?",
[user_id]) [user_id])
row_ids = [row['id'] for row in result] row_ids = [row['id'] for row in result]
@ -299,7 +299,7 @@ def delete_library_history(section_id=None):
monitor_db = MonitorDatabase() monitor_db = MonitorDatabase()
# Get all history associated with the section_id # Get all history associated with the section_id
result = monitor_db.select('SELECT id FROM session_history WHERE section_id = ?', result = monitor_db.select("SELECT id FROM session_history WHERE section_id = ?",
[section_id]) [section_id])
row_ids = [row['id'] for row in result] row_ids = [row['id'] for row in result]
@ -312,7 +312,7 @@ def vacuum():
logger.info("Tautulli Database :: Vacuuming database.") logger.info("Tautulli Database :: Vacuuming database.")
try: try:
monitor_db.action('VACUUM') monitor_db.action("VACUUM")
except Exception as e: except Exception as e:
logger.error("Tautulli Database :: Failed to vacuum database: %s" % e) logger.error("Tautulli Database :: Failed to vacuum database: %s" % e)
@ -322,7 +322,7 @@ def optimize():
logger.info("Tautulli Database :: Optimizing database.") logger.info("Tautulli Database :: Optimizing database.")
try: try:
monitor_db.action('PRAGMA optimize') monitor_db.action("PRAGMA optimize")
except Exception as e: except Exception as e:
logger.error("Tautulli Database :: Failed to optimize database: %s" % e) logger.error("Tautulli Database :: Failed to optimize database: %s" % e)
@ -362,7 +362,7 @@ def make_backup(cleanup=False, scheduler=False):
os.makedirs(backup_folder) os.makedirs(backup_folder)
db = MonitorDatabase() db = MonitorDatabase()
db.connection.execute('BEGIN IMMEDIATE') db.connection.execute("BEGIN IMMEDIATE")
shutil.copyfile(db_filename(), backup_file_fp) shutil.copyfile(db_filename(), backup_file_fp)
db.connection.rollback() db.connection.rollback()
@ -496,6 +496,6 @@ class MonitorDatabase(object):
def last_insert_id(self): def last_insert_id(self):
# Get the last insert row id # Get the last insert row id
result = self.select_single(query='SELECT last_insert_rowid() AS last_id') result = self.select_single(query="SELECT last_insert_rowid() AS last_id")
if result: if result:
return result.get('last_id', None) return result.get('last_id', None)

File diff suppressed because it is too large Load diff

View file

@ -2291,9 +2291,9 @@ class ExportObject(Export):
def get_export(export_id): def get_export(export_id):
db = database.MonitorDatabase() db = database.MonitorDatabase()
result = db.select_single('SELECT timestamp, title, file_format, thumb_level, art_level, ' result = db.select_single("SELECT timestamp, title, file_format, thumb_level, art_level, "
'individual_files, complete ' "individual_files, complete "
'FROM exports WHERE id = ?', "FROM exports WHERE id = ?",
[export_id]) [export_id])
if result: if result:
@ -2324,7 +2324,7 @@ def delete_export(export_id):
if deleted: if deleted:
logger.info("Tautulli Exporter :: Deleting export_id %s from the database.", export_id) logger.info("Tautulli Exporter :: Deleting export_id %s from the database.", export_id)
db = database.MonitorDatabase() db = database.MonitorDatabase()
result = db.action('DELETE FROM exports WHERE id = ?', args=[export_id]) result = db.action("DELETE FROM exports WHERE id = ?", args=[export_id])
return deleted return deleted
else: else:
@ -2349,7 +2349,7 @@ def delete_all_exports():
def cancel_exports(): def cancel_exports():
db = database.MonitorDatabase() db = database.MonitorDatabase()
db.action('UPDATE exports SET complete = -1 WHERE complete = 0') db.action("UPDATE exports SET complete = -1 WHERE complete = 0")
def get_export_datatable(section_id=None, user_id=None, rating_key=None, kwargs=None): def get_export_datatable(section_id=None, user_id=None, rating_key=None, kwargs=None):
@ -2368,27 +2368,27 @@ def get_export_datatable(section_id=None, user_id=None, rating_key=None, kwargs=
if rating_key: if rating_key:
custom_where.append(['exports.rating_key', rating_key]) custom_where.append(['exports.rating_key', rating_key])
columns = ['exports.id AS export_id', columns = ["exports.id AS export_id",
'exports.timestamp', "exports.timestamp",
'exports.section_id', "exports.section_id",
'exports.user_id', "exports.user_id",
'exports.rating_key', "exports.rating_key",
'exports.media_type', "exports.media_type",
'CASE WHEN exports.media_type = "photoalbum" THEN "Photo Album" ELSE ' "CASE WHEN exports.media_type = 'photoalbum' THEN 'Photo Album' ELSE "
'UPPER(SUBSTR(exports.media_type, 1, 1)) || SUBSTR(exports.media_type, 2) END ' "UPPER(SUBSTR(exports.media_type, 1, 1)) || SUBSTR(exports.media_type, 2) END "
'AS media_type_title', "AS media_type_title",
'exports.title', "exports.title",
'exports.file_format', "exports.file_format",
'exports.metadata_level', "exports.metadata_level",
'exports.media_info_level', "exports.media_info_level",
'exports.thumb_level', "exports.thumb_level",
'exports.art_level', "exports.art_level",
'exports.custom_fields', "exports.custom_fields",
'exports.individual_files', "exports.individual_files",
'exports.file_size', "exports.file_size",
'exports.complete', "exports.complete",
'exports.total_items', "exports.total_items",
'exports.exported_items' "exports.exported_items"
] ]
try: try:
query = data_tables.ssp_query(table_name='exports', query = data_tables.ssp_query(table_name='exports',

View file

@ -64,42 +64,42 @@ class Graphs(object):
try: try:
if y_axis == 'plays': if y_axis == 'plays':
query = 'SELECT sh.date_played, ' \ query = "SELECT sh.date_played, " \
'SUM(CASE WHEN sh.media_type = "episode" AND shm.live = 0 THEN 1 ELSE 0 END) AS tv_count, ' \ "SUM(CASE WHEN sh.media_type = 'episode' AND shm.live = 0 THEN 1 ELSE 0 END) AS tv_count, " \
'SUM(CASE WHEN sh.media_type = "movie" AND shm.live = 0 THEN 1 ELSE 0 END) AS movie_count, ' \ "SUM(CASE WHEN sh.media_type = 'movie' AND shm.live = 0 THEN 1 ELSE 0 END) AS movie_count, " \
'SUM(CASE WHEN sh.media_type = "track" AND shm.live = 0 THEN 1 ELSE 0 END) AS music_count, ' \ "SUM(CASE WHEN sh.media_type = 'track' AND shm.live = 0 THEN 1 ELSE 0 END) AS music_count, " \
'SUM(shm.live) AS live_count ' \ "SUM(shm.live) AS live_count " \
'FROM (SELECT *,' \ "FROM (SELECT *," \
' date(started, "unixepoch", "localtime") AS date_played ' \ " date(started, 'unixepoch', 'localtime') AS date_played " \
' FROM session_history ' \ " FROM session_history " \
' WHERE session_history.stopped >= %s %s ' \ " WHERE session_history.stopped >= %s %s " \
' GROUP BY date_played, %s) AS sh ' \ " GROUP BY date_played, %s) AS sh " \
'JOIN session_history_metadata AS shm ON shm.id = sh.id ' \ "JOIN session_history_metadata AS shm ON shm.id = sh.id " \
'GROUP BY sh.date_played ' \ "GROUP BY sh.date_played " \
'ORDER BY sh.started' % (timestamp, user_cond, group_by) "ORDER BY sh.started" % (timestamp, user_cond, group_by)
result = monitor_db.select(query) result = monitor_db.select(query)
else: else:
query = 'SELECT sh.date_played, ' \ query = "SELECT sh.date_played, " \
'SUM(CASE WHEN sh.media_type = "episode" AND shm.live = 0 ' \ "SUM(CASE WHEN sh.media_type = 'episode' AND shm.live = 0 " \
' THEN sh.d ELSE 0 END) AS tv_count, ' \ " THEN sh.d ELSE 0 END) AS tv_count, " \
'SUM(CASE WHEN sh.media_type = "movie" AND shm.live = 0 ' \ "SUM(CASE WHEN sh.media_type = 'movie' AND shm.live = 0 " \
' THEN sh.d ELSE 0 END) AS movie_count, ' \ " THEN sh.d ELSE 0 END) AS movie_count, " \
'SUM(CASE WHEN sh.media_type = "track" AND shm.live = 0 ' \ "SUM(CASE WHEN sh.media_type = 'track' AND shm.live = 0 " \
' THEN sh.d ELSE 0 END) AS music_count, ' \ " THEN sh.d ELSE 0 END) AS music_count, " \
'SUM(CASE WHEN shm.live = 1 ' \ "SUM(CASE WHEN shm.live = 1 " \
' THEN sh.d ELSE 0 END) AS live_count ' \ " THEN sh.d ELSE 0 END) AS live_count " \
'FROM (SELECT *,' \ "FROM (SELECT *," \
' date(started, "unixepoch", "localtime") AS date_played,' \ " date(started, 'unixepoch', 'localtime') AS date_played," \
' SUM(CASE WHEN stopped > 0 THEN (stopped - started) - ' \ " SUM(CASE WHEN stopped > 0 THEN (stopped - started) - " \
' (CASE WHEN paused_counter IS NULL THEN 0 ELSE paused_counter END) ELSE 0 END) ' \ " (CASE WHEN paused_counter IS NULL THEN 0 ELSE paused_counter END) ELSE 0 END) " \
' AS d ' \ " AS d " \
' FROM session_history ' \ " FROM session_history " \
' WHERE session_history.stopped >= %s %s' \ " WHERE session_history.stopped >= %s %s" \
' GROUP BY date_played, %s) AS sh ' \ " GROUP BY date_played, %s) AS sh " \
'JOIN session_history_metadata AS shm ON shm.id = sh.id ' \ "JOIN session_history_metadata AS shm ON shm.id = sh.id " \
'GROUP BY sh.date_played ' \ "GROUP BY sh.date_played " \
'ORDER BY sh.started' % (timestamp, user_cond, group_by) "ORDER BY sh.started" % (timestamp, user_cond, group_by)
result = monitor_db.select(query) result = monitor_db.select(query)
except Exception as e: except Exception as e:
@ -173,9 +173,9 @@ class Graphs(object):
user_cond = '' user_cond = ''
if session.get_session_user_id() and user_id and user_id != str(session.get_session_user_id()): if session.get_session_user_id() and user_id and user_id != str(session.get_session_user_id()):
user_cond = 'AND session_history.user_id = %s ' % session.get_session_user_id() user_cond = "AND session_history.user_id = %s " % session.get_session_user_id()
elif user_id and user_id.isdigit(): elif user_id and user_id.isdigit():
user_cond = 'AND session_history.user_id = %s ' % user_id user_cond = "AND session_history.user_id = %s " % user_id
if grouping is None: if grouping is None:
grouping = plexpy.CONFIG.GROUP_HISTORY_TABLES grouping = plexpy.CONFIG.GROUP_HISTORY_TABLES
@ -184,58 +184,58 @@ class Graphs(object):
try: try:
if y_axis == 'plays': if y_axis == 'plays':
query = 'SELECT sh.daynumber, ' \ query = "SELECT sh.daynumber, " \
'(CASE sh.daynumber ' \ "(CASE sh.daynumber " \
' WHEN 0 THEN "Sunday" ' \ " WHEN 0 THEN 'Sunday' " \
' WHEN 1 THEN "Monday" ' \ " WHEN 1 THEN 'Monday' " \
' WHEN 2 THEN "Tuesday" ' \ " WHEN 2 THEN 'Tuesday' " \
' WHEN 3 THEN "Wednesday" ' \ " WHEN 3 THEN 'Wednesday' " \
' WHEN 4 THEN "Thursday" ' \ " WHEN 4 THEN 'Thursday' " \
' WHEN 5 THEN "Friday" ' \ " WHEN 5 THEN 'Friday' " \
' ELSE "Saturday" END) AS dayofweek, ' \ " ELSE 'Saturday' END) AS dayofweek, " \
'SUM(CASE WHEN sh.media_type = "episode" AND shm.live = 0 THEN 1 ELSE 0 END) AS tv_count, ' \ "SUM(CASE WHEN sh.media_type = 'episode' AND shm.live = 0 THEN 1 ELSE 0 END) AS tv_count, " \
'SUM(CASE WHEN sh.media_type = "movie" AND shm.live = 0 THEN 1 ELSE 0 END) AS movie_count, ' \ "SUM(CASE WHEN sh.media_type = 'movie' AND shm.live = 0 THEN 1 ELSE 0 END) AS movie_count, " \
'SUM(CASE WHEN sh.media_type = "track" AND shm.live = 0 THEN 1 ELSE 0 END) AS music_count, ' \ "SUM(CASE WHEN sh.media_type = 'track' AND shm.live = 0 THEN 1 ELSE 0 END) AS music_count, " \
'SUM(shm.live) AS live_count ' \ "SUM(shm.live) AS live_count " \
'FROM (SELECT *, ' \ "FROM (SELECT *, " \
' CAST(strftime("%%w", date(started, "unixepoch", "localtime")) AS INTEGER) AS daynumber' \ " CAST(strftime('%%w', date(started, 'unixepoch', 'localtime')) AS INTEGER) AS daynumber" \
' FROM session_history ' \ " FROM session_history " \
' WHERE session_history.stopped >= %s %s ' \ " WHERE session_history.stopped >= %s %s " \
' GROUP BY daynumber, %s) AS sh ' \ " GROUP BY daynumber, %s) AS sh " \
'JOIN session_history_metadata AS shm ON shm.id = sh.id ' \ "JOIN session_history_metadata AS shm ON shm.id = sh.id " \
'GROUP BY dayofweek ' \ "GROUP BY dayofweek " \
'ORDER BY sh.daynumber' % (timestamp, user_cond, group_by) "ORDER BY sh.daynumber" % (timestamp, user_cond, group_by)
result = monitor_db.select(query) result = monitor_db.select(query)
else: else:
query = 'SELECT sh.daynumber, ' \ query = "SELECT sh.daynumber, " \
'(CASE sh.daynumber ' \ "(CASE sh.daynumber " \
' WHEN 0 THEN "Sunday" ' \ " WHEN 0 THEN 'Sunday' " \
' WHEN 1 THEN "Monday" ' \ " WHEN 1 THEN 'Monday' " \
' WHEN 2 THEN "Tuesday" ' \ " WHEN 2 THEN 'Tuesday' " \
' WHEN 3 THEN "Wednesday" ' \ " WHEN 3 THEN 'Wednesday' " \
' WHEN 4 THEN "Thursday" ' \ " WHEN 4 THEN 'Thursday' " \
' WHEN 5 THEN "Friday" ' \ " WHEN 5 THEN 'Friday' " \
' ELSE "Saturday" END) AS dayofweek, ' \ " ELSE 'Saturday' END) AS dayofweek, " \
'SUM(CASE WHEN sh.media_type = "episode" AND shm.live = 0 ' \ "SUM(CASE WHEN sh.media_type = 'episode' AND shm.live = 0 " \
' THEN sh.d ELSE 0 END) AS tv_count, ' \ " THEN sh.d ELSE 0 END) AS tv_count, " \
'SUM(CASE WHEN sh.media_type = "movie" AND shm.live = 0 ' \ "SUM(CASE WHEN sh.media_type = 'movie' AND shm.live = 0 " \
' THEN sh.d ELSE 0 END) AS movie_count, ' \ " THEN sh.d ELSE 0 END) AS movie_count, " \
'SUM(CASE WHEN sh.media_type = "track" AND shm.live = 0 ' \ "SUM(CASE WHEN sh.media_type = 'track' AND shm.live = 0 " \
' THEN sh.d ELSE 0 END) AS music_count, ' \ " THEN sh.d ELSE 0 END) AS music_count, " \
'SUM(CASE WHEN shm.live = 1 ' \ "SUM(CASE WHEN shm.live = 1 " \
' THEN sh.d ELSE 0 END) AS live_count ' \ " THEN sh.d ELSE 0 END) AS live_count " \
'FROM (SELECT *, ' \ "FROM (SELECT *, " \
' CAST(strftime("%%w", date(started, "unixepoch", "localtime")) AS INTEGER) AS daynumber, ' \ " CAST(strftime('%%w', date(started, 'unixepoch', 'localtime')) AS INTEGER) AS daynumber, " \
' SUM(CASE WHEN stopped > 0 THEN (stopped - started) - ' \ " SUM(CASE WHEN stopped > 0 THEN (stopped - started) - " \
' (CASE WHEN paused_counter IS NULL THEN 0 ELSE paused_counter END) ELSE 0 END) ' \ " (CASE WHEN paused_counter IS NULL THEN 0 ELSE paused_counter END) ELSE 0 END) " \
' AS d ' \ " AS d " \
' FROM session_history ' \ " FROM session_history " \
' WHERE session_history.stopped >= %s %s' \ " WHERE session_history.stopped >= %s %s" \
' GROUP BY daynumber, %s) AS sh ' \ " GROUP BY daynumber, %s) AS sh " \
'JOIN session_history_metadata AS shm ON shm.id = sh.id ' \ "JOIN session_history_metadata AS shm ON shm.id = sh.id " \
'GROUP BY dayofweek ' \ "GROUP BY dayofweek " \
'ORDER BY sh.daynumber' % (timestamp, user_cond, group_by) "ORDER BY sh.daynumber" % (timestamp, user_cond, group_by)
result = monitor_db.select(query) result = monitor_db.select(query)
except Exception as e: except Exception as e:
@ -321,42 +321,42 @@ class Graphs(object):
try: try:
if y_axis == 'plays': if y_axis == 'plays':
query = 'SELECT sh.hourofday, ' \ query = "SELECT sh.hourofday, " \
'SUM(CASE WHEN sh.media_type = "episode" AND shm.live = 0 THEN 1 ELSE 0 END) AS tv_count, ' \ "SUM(CASE WHEN sh.media_type = 'episode' AND shm.live = 0 THEN 1 ELSE 0 END) AS tv_count, " \
'SUM(CASE WHEN sh.media_type = "movie" AND shm.live = 0 THEN 1 ELSE 0 END) AS movie_count, ' \ "SUM(CASE WHEN sh.media_type = 'movie' AND shm.live = 0 THEN 1 ELSE 0 END) AS movie_count, " \
'SUM(CASE WHEN sh.media_type = "track" AND shm.live = 0 THEN 1 ELSE 0 END) AS music_count, ' \ "SUM(CASE WHEN sh.media_type = 'track' AND shm.live = 0 THEN 1 ELSE 0 END) AS music_count, " \
'SUM(shm.live) AS live_count ' \ "SUM(shm.live) AS live_count " \
'FROM (SELECT *, ' \ "FROM (SELECT *, " \
' strftime("%%H", datetime(started, "unixepoch", "localtime")) AS hourofday' \ " strftime('%%H', datetime(started, 'unixepoch', 'localtime')) AS hourofday" \
' FROM session_history ' \ " FROM session_history " \
' WHERE session_history.stopped >= %s %s ' \ " WHERE session_history.stopped >= %s %s " \
' GROUP BY hourofday, %s) AS sh ' \ " GROUP BY hourofday, %s) AS sh " \
'JOIN session_history_metadata AS shm ON shm.id = sh.id ' \ "JOIN session_history_metadata AS shm ON shm.id = sh.id " \
'GROUP BY sh.hourofday ' \ "GROUP BY sh.hourofday " \
'ORDER BY sh.hourofday' % (timestamp, user_cond, group_by) "ORDER BY sh.hourofday" % (timestamp, user_cond, group_by)
result = monitor_db.select(query) result = monitor_db.select(query)
else: else:
query = 'SELECT sh.hourofday, ' \ query = "SELECT sh.hourofday, " \
'SUM(CASE WHEN sh.media_type = "episode" AND shm.live = 0 ' \ "SUM(CASE WHEN sh.media_type = 'episode' AND shm.live = 0 " \
' THEN sh.d ELSE 0 END) AS tv_count, ' \ " THEN sh.d ELSE 0 END) AS tv_count, " \
'SUM(CASE WHEN sh.media_type = "movie" AND shm.live = 0 ' \ "SUM(CASE WHEN sh.media_type = 'movie' AND shm.live = 0 " \
' THEN sh.d ELSE 0 END) AS movie_count, ' \ " THEN sh.d ELSE 0 END) AS movie_count, " \
'SUM(CASE WHEN sh.media_type = "track" AND shm.live = 0 ' \ "SUM(CASE WHEN sh.media_type = 'track' AND shm.live = 0 " \
' THEN sh.d ELSE 0 END) AS music_count, ' \ " THEN sh.d ELSE 0 END) AS music_count, " \
'SUM(CASE WHEN shm.live = 1 ' \ "SUM(CASE WHEN shm.live = 1 " \
' THEN sh.d ELSE 0 END) AS live_count ' \ " THEN sh.d ELSE 0 END) AS live_count " \
'FROM (SELECT *, ' \ "FROM (SELECT *, " \
' strftime("%%H", datetime(started, "unixepoch", "localtime")) AS hourofday, ' \ " strftime('%%H', datetime(started, 'unixepoch', 'localtime')) AS hourofday, " \
' SUM(CASE WHEN stopped > 0 THEN (stopped - started) - ' \ " SUM(CASE WHEN stopped > 0 THEN (stopped - started) - " \
' (CASE WHEN paused_counter IS NULL THEN 0 ELSE paused_counter END) ELSE 0 END) ' \ " (CASE WHEN paused_counter IS NULL THEN 0 ELSE paused_counter END) ELSE 0 END) " \
' AS d ' \ " AS d " \
' FROM session_history ' \ " FROM session_history " \
' WHERE session_history.stopped >= %s %s' \ " WHERE session_history.stopped >= %s %s" \
' GROUP BY hourofday, %s) AS sh ' \ " GROUP BY hourofday, %s) AS sh " \
'JOIN session_history_metadata AS shm ON shm.id = sh.id ' \ "JOIN session_history_metadata AS shm ON shm.id = sh.id " \
'GROUP BY sh.hourofday ' \ "GROUP BY sh.hourofday " \
'ORDER BY sh.hourofday' % (timestamp, user_cond, group_by) "ORDER BY sh.hourofday" % (timestamp, user_cond, group_by)
result = monitor_db.select(query) result = monitor_db.select(query)
except Exception as e: except Exception as e:
@ -440,42 +440,42 @@ class Graphs(object):
try: try:
if y_axis == 'plays': if y_axis == 'plays':
query = 'SELECT sh.datestring, ' \ query = "SELECT sh.datestring, " \
'SUM(CASE WHEN sh.media_type = "episode" AND shm.live = 0 THEN 1 ELSE 0 END) AS tv_count, ' \ "SUM(CASE WHEN sh.media_type = 'episode' AND shm.live = 0 THEN 1 ELSE 0 END) AS tv_count, " \
'SUM(CASE WHEN sh.media_type = "movie" AND shm.live = 0 THEN 1 ELSE 0 END) AS movie_count, ' \ "SUM(CASE WHEN sh.media_type = 'movie' AND shm.live = 0 THEN 1 ELSE 0 END) AS movie_count, " \
'SUM(CASE WHEN sh.media_type = "track" AND shm.live = 0 THEN 1 ELSE 0 END) AS music_count, ' \ "SUM(CASE WHEN sh.media_type = 'track' AND shm.live = 0 THEN 1 ELSE 0 END) AS music_count, " \
'SUM(shm.live) AS live_count ' \ "SUM(shm.live) AS live_count " \
'FROM (SELECT *, ' \ "FROM (SELECT *, " \
' strftime("%%Y-%%m", datetime(started, "unixepoch", "localtime")) AS datestring' \ " strftime('%%Y-%%m', datetime(started, 'unixepoch', 'localtime')) AS datestring" \
' FROM session_history ' \ " FROM session_history " \
' WHERE session_history.stopped >= %s %s ' \ " WHERE session_history.stopped >= %s %s " \
' GROUP BY datestring, %s) AS sh ' \ " GROUP BY datestring, %s) AS sh " \
'JOIN session_history_metadata AS shm ON shm.id = sh.id ' \ "JOIN session_history_metadata AS shm ON shm.id = sh.id " \
'GROUP BY sh.datestring ' \ "GROUP BY sh.datestring " \
'ORDER BY sh.datestring' % (timestamp, user_cond, group_by) "ORDER BY sh.datestring" % (timestamp, user_cond, group_by)
result = monitor_db.select(query) result = monitor_db.select(query)
else: else:
query = 'SELECT sh.datestring, ' \ query = "SELECT sh.datestring, " \
'SUM(CASE WHEN sh.media_type = "episode" AND shm.live = 0 ' \ "SUM(CASE WHEN sh.media_type = 'episode' AND shm.live = 0 " \
' THEN sh.d ELSE 0 END) AS tv_count, ' \ " THEN sh.d ELSE 0 END) AS tv_count, " \
'SUM(CASE WHEN sh.media_type = "movie" AND shm.live = 0 ' \ "SUM(CASE WHEN sh.media_type = 'movie' AND shm.live = 0 " \
' THEN sh.d ELSE 0 END) AS movie_count, ' \ " THEN sh.d ELSE 0 END) AS movie_count, " \
'SUM(CASE WHEN sh.media_type = "track" AND shm.live = 0 ' \ "SUM(CASE WHEN sh.media_type = 'track' AND shm.live = 0 " \
' THEN sh.d ELSE 0 END) AS music_count, ' \ " THEN sh.d ELSE 0 END) AS music_count, " \
'SUM(CASE WHEN shm.live = 1 ' \ "SUM(CASE WHEN shm.live = 1 " \
' THEN sh.d ELSE 0 END) AS live_count ' \ " THEN sh.d ELSE 0 END) AS live_count " \
'FROM (SELECT *, ' \ "FROM (SELECT *, " \
' strftime("%%Y-%%m", datetime(started, "unixepoch", "localtime")) AS datestring, ' \ " strftime('%%Y-%%m', datetime(started, 'unixepoch', 'localtime')) AS datestring, " \
' SUM(CASE WHEN stopped > 0 THEN (stopped - started) - ' \ " SUM(CASE WHEN stopped > 0 THEN (stopped - started) - " \
' (CASE WHEN paused_counter IS NULL THEN 0 ELSE paused_counter END) ELSE 0 END) ' \ " (CASE WHEN paused_counter IS NULL THEN 0 ELSE paused_counter END) ELSE 0 END) " \
' AS d ' \ " AS d " \
' FROM session_history ' \ " FROM session_history " \
' WHERE session_history.stopped >= %s %s' \ " WHERE session_history.stopped >= %s %s" \
' GROUP BY datestring, %s) AS sh ' \ " GROUP BY datestring, %s) AS sh " \
'JOIN session_history_metadata AS shm ON shm.id = sh.id ' \ "JOIN session_history_metadata AS shm ON shm.id = sh.id " \
'GROUP BY sh.datestring ' \ "GROUP BY sh.datestring " \
'ORDER BY sh.datestring' % (timestamp, user_cond, group_by) "ORDER BY sh.datestring" % (timestamp, user_cond, group_by)
result = monitor_db.select(query) result = monitor_db.select(query)
except Exception as e: except Exception as e:
@ -567,44 +567,44 @@ class Graphs(object):
try: try:
if y_axis == 'plays': if y_axis == 'plays':
query = 'SELECT sh.platform, ' \ query = "SELECT sh.platform, " \
'SUM(CASE WHEN sh.media_type = "episode" AND shm.live = 0 THEN 1 ELSE 0 END) AS tv_count, ' \ "SUM(CASE WHEN sh.media_type = 'episode' AND shm.live = 0 THEN 1 ELSE 0 END) AS tv_count, " \
'SUM(CASE WHEN sh.media_type = "movie" AND shm.live = 0 THEN 1 ELSE 0 END) AS movie_count, ' \ "SUM(CASE WHEN sh.media_type = 'movie' AND shm.live = 0 THEN 1 ELSE 0 END) AS movie_count, " \
'SUM(CASE WHEN sh.media_type = "track" AND shm.live = 0 THEN 1 ELSE 0 END) AS music_count, ' \ "SUM(CASE WHEN sh.media_type = 'track' AND shm.live = 0 THEN 1 ELSE 0 END) AS music_count, " \
'SUM(shm.live) AS live_count, ' \ "SUM(shm.live) AS live_count, " \
'COUNT(sh.id) AS total_count ' \ "COUNT(sh.id) AS total_count " \
'FROM (SELECT * ' \ "FROM (SELECT * " \
' FROM session_history ' \ " FROM session_history " \
' WHERE session_history.stopped >= %s %s ' \ " WHERE session_history.stopped >= %s %s " \
' GROUP BY %s) AS sh ' \ " GROUP BY %s) AS sh " \
'JOIN session_history_metadata AS shm ON shm.id = sh.id ' \ "JOIN session_history_metadata AS shm ON shm.id = sh.id " \
'GROUP BY sh.platform ' \ "GROUP BY sh.platform " \
'ORDER BY total_count DESC, sh.platform ASC ' \ "ORDER BY total_count DESC, sh.platform ASC " \
'LIMIT 10' % (timestamp, user_cond, group_by) "LIMIT 10" % (timestamp, user_cond, group_by)
result = monitor_db.select(query) result = monitor_db.select(query)
else: else:
query = 'SELECT sh.platform, ' \ query = "SELECT sh.platform, " \
'SUM(CASE WHEN sh.media_type = "episode" AND shm.live = 0 ' \ "SUM(CASE WHEN sh.media_type = 'episode' AND shm.live = 0 " \
' THEN sh.d ELSE 0 END) AS tv_count, ' \ " THEN sh.d ELSE 0 END) AS tv_count, " \
'SUM(CASE WHEN sh.media_type = "movie" AND shm.live = 0 ' \ "SUM(CASE WHEN sh.media_type = 'movie' AND shm.live = 0 " \
' THEN sh.d ELSE 0 END) AS movie_count, ' \ " THEN sh.d ELSE 0 END) AS movie_count, " \
'SUM(CASE WHEN sh.media_type = "track" AND shm.live = 0 ' \ "SUM(CASE WHEN sh.media_type = 'track' AND shm.live = 0 " \
' THEN sh.d ELSE 0 END) AS music_count, ' \ " THEN sh.d ELSE 0 END) AS music_count, " \
'SUM(CASE WHEN shm.live = 1 ' \ "SUM(CASE WHEN shm.live = 1 " \
' THEN sh.d ELSE 0 END) AS live_count, ' \ " THEN sh.d ELSE 0 END) AS live_count, " \
'SUM(sh.d) AS total_duration ' \ "SUM(sh.d) AS total_duration " \
'FROM (SELECT *, ' \ "FROM (SELECT *, " \
' SUM(CASE WHEN stopped > 0 THEN (stopped - started) - ' \ " SUM(CASE WHEN stopped > 0 THEN (stopped - started) - " \
' (CASE WHEN paused_counter IS NULL THEN 0 ELSE paused_counter END) ELSE 0 END) ' \ " (CASE WHEN paused_counter IS NULL THEN 0 ELSE paused_counter END) ELSE 0 END) " \
' AS d ' \ " AS d " \
' FROM session_history ' \ " FROM session_history " \
' WHERE session_history.stopped >= %s %s' \ " WHERE session_history.stopped >= %s %s" \
' GROUP BY %s) AS sh ' \ " GROUP BY %s) AS sh " \
'JOIN session_history_metadata AS shm ON shm.id = sh.id ' \ "JOIN session_history_metadata AS shm ON shm.id = sh.id " \
'GROUP BY sh.platform ' \ "GROUP BY sh.platform " \
'ORDER BY total_duration DESC ' \ "ORDER BY total_duration DESC " \
'LIMIT 10' % (timestamp, user_cond, group_by) "LIMIT 10" % (timestamp, user_cond, group_by)
result = monitor_db.select(query) result = monitor_db.select(query)
except Exception as e: except Exception as e:
@ -666,50 +666,50 @@ class Graphs(object):
try: try:
if y_axis == 'plays': if y_axis == 'plays':
query = 'SELECT u.user_id, u.username, ' \ query = "SELECT u.user_id, u.username, " \
'(CASE WHEN u.friendly_name IS NULL OR TRIM(u.friendly_name) = "" ' \ "(CASE WHEN u.friendly_name IS NULL OR TRIM(u.friendly_name) = '' " \
' THEN u.username ELSE u.friendly_name END) AS friendly_name,' \ " THEN u.username ELSE u.friendly_name END) AS friendly_name," \
'SUM(CASE WHEN sh.media_type = "episode" AND shm.live = 0 THEN 1 ELSE 0 END) AS tv_count, ' \ "SUM(CASE WHEN sh.media_type = 'episode' AND shm.live = 0 THEN 1 ELSE 0 END) AS tv_count, " \
'SUM(CASE WHEN sh.media_type = "movie" AND shm.live = 0 THEN 1 ELSE 0 END) AS movie_count, ' \ "SUM(CASE WHEN sh.media_type = 'movie' AND shm.live = 0 THEN 1 ELSE 0 END) AS movie_count, " \
'SUM(CASE WHEN sh.media_type = "track" AND shm.live = 0 THEN 1 ELSE 0 END) AS music_count, ' \ "SUM(CASE WHEN sh.media_type = 'track' AND shm.live = 0 THEN 1 ELSE 0 END) AS music_count, " \
'SUM(shm.live) AS live_count, ' \ "SUM(shm.live) AS live_count, " \
'COUNT(sh.id) AS total_count ' \ "COUNT(sh.id) AS total_count " \
'FROM (SELECT * ' \ "FROM (SELECT * " \
' FROM session_history ' \ " FROM session_history " \
' WHERE session_history.stopped >= %s %s ' \ " WHERE session_history.stopped >= %s %s " \
' GROUP BY %s) AS sh ' \ " GROUP BY %s) AS sh " \
'JOIN session_history_metadata AS shm ON shm.id = sh.id ' \ "JOIN session_history_metadata AS shm ON shm.id = sh.id " \
'JOIN users AS u ON u.user_id = sh.user_id ' \ "JOIN users AS u ON u.user_id = sh.user_id " \
'GROUP BY sh.user_id ' \ "GROUP BY sh.user_id " \
'ORDER BY total_count DESC ' \ "ORDER BY total_count DESC " \
'LIMIT 10' % (timestamp, user_cond, group_by) "LIMIT 10" % (timestamp, user_cond, group_by)
result = monitor_db.select(query) result = monitor_db.select(query)
else: else:
query = 'SELECT u.user_id, u.username, ' \ query = "SELECT u.user_id, u.username, " \
'(CASE WHEN u.friendly_name IS NULL OR TRIM(u.friendly_name) = "" ' \ "(CASE WHEN u.friendly_name IS NULL OR TRIM(u.friendly_name) = '' " \
' THEN u.username ELSE u.friendly_name END) AS friendly_name,' \ " THEN u.username ELSE u.friendly_name END) AS friendly_name," \
'SUM(CASE WHEN sh.media_type = "episode" AND shm.live = 0 ' \ "SUM(CASE WHEN sh.media_type = 'episode' AND shm.live = 0 " \
' THEN sh.d ELSE 0 END) AS tv_count, ' \ " THEN sh.d ELSE 0 END) AS tv_count, " \
'SUM(CASE WHEN sh.media_type = "movie" AND shm.live = 0 ' \ "SUM(CASE WHEN sh.media_type = 'movie' AND shm.live = 0 " \
' THEN sh.d ELSE 0 END) AS movie_count, ' \ " THEN sh.d ELSE 0 END) AS movie_count, " \
'SUM(CASE WHEN sh.media_type = "track" AND shm.live = 0 ' \ "SUM(CASE WHEN sh.media_type = 'track' AND shm.live = 0 " \
' THEN sh.d ELSE 0 END) AS music_count, ' \ " THEN sh.d ELSE 0 END) AS music_count, " \
'SUM(CASE WHEN shm.live = 1 ' \ "SUM(CASE WHEN shm.live = 1 " \
' THEN sh.d ELSE 0 END) AS live_count, ' \ " THEN sh.d ELSE 0 END) AS live_count, " \
'SUM(sh.d) AS total_duration ' \ "SUM(sh.d) AS total_duration " \
'FROM (SELECT *, ' \ "FROM (SELECT *, " \
' SUM(CASE WHEN stopped > 0 THEN (stopped - started) - ' \ " SUM(CASE WHEN stopped > 0 THEN (stopped - started) - " \
' (CASE WHEN paused_counter IS NULL THEN 0 ELSE paused_counter END) ELSE 0 END) ' \ " (CASE WHEN paused_counter IS NULL THEN 0 ELSE paused_counter END) ELSE 0 END) " \
' AS d ' \ " AS d " \
' FROM session_history ' \ " FROM session_history " \
' WHERE session_history.stopped >= %s %s' \ " WHERE session_history.stopped >= %s %s" \
' GROUP BY %s) AS sh ' \ " GROUP BY %s) AS sh " \
'JOIN session_history_metadata AS shm ON shm.id = sh.id ' \ "JOIN session_history_metadata AS shm ON shm.id = sh.id " \
'JOIN users AS u ON u.user_id = sh.user_id ' \ "JOIN users AS u ON u.user_id = sh.user_id " \
'GROUP BY sh.user_id ' \ "GROUP BY sh.user_id " \
'ORDER BY total_duration DESC ' \ "ORDER BY total_duration DESC " \
'LIMIT 10' % (timestamp, user_cond, group_by) "LIMIT 10" % (timestamp, user_cond, group_by)
result = monitor_db.select(query) result = monitor_db.select(query)
except Exception as e: except Exception as e:
@ -776,36 +776,36 @@ class Graphs(object):
try: try:
if y_axis == 'plays': if y_axis == 'plays':
query = 'SELECT sh.date_played, ' \ query = "SELECT sh.date_played, " \
'SUM(CASE WHEN shmi.transcode_decision = "direct play" THEN 1 ELSE 0 END) AS dp_count, ' \ "SUM(CASE WHEN shmi.transcode_decision = 'direct play' THEN 1 ELSE 0 END) AS dp_count, " \
'SUM(CASE WHEN shmi.transcode_decision = "copy" THEN 1 ELSE 0 END) AS ds_count, ' \ "SUM(CASE WHEN shmi.transcode_decision = 'copy' THEN 1 ELSE 0 END) AS ds_count, " \
'SUM(CASE WHEN shmi.transcode_decision = "transcode" THEN 1 ELSE 0 END) AS tc_count ' \ "SUM(CASE WHEN shmi.transcode_decision = 'transcode' THEN 1 ELSE 0 END) AS tc_count " \
'FROM (SELECT *, ' \ "FROM (SELECT *, " \
' date(started, "unixepoch", "localtime") AS date_played ' \ " date(started, 'unixepoch', 'localtime') AS date_played " \
' FROM session_history ' \ " FROM session_history " \
' WHERE session_history.stopped >= %s %s ' \ " WHERE session_history.stopped >= %s %s " \
' GROUP BY date_played, %s) AS sh ' \ " GROUP BY date_played, %s) AS sh " \
'JOIN session_history_media_info AS shmi ON shmi.id = sh.id ' \ "JOIN session_history_media_info AS shmi ON shmi.id = sh.id " \
'GROUP BY sh.date_played ' \ "GROUP BY sh.date_played " \
'ORDER BY sh.started' % (timestamp, user_cond, group_by) "ORDER BY sh.started" % (timestamp, user_cond, group_by)
result = monitor_db.select(query) result = monitor_db.select(query)
else: else:
query = 'SELECT sh.date_played, ' \ query = "SELECT sh.date_played, " \
'SUM(CASE WHEN shmi.transcode_decision = "direct play" THEN sh.d ELSE 0 END) AS dp_count, ' \ "SUM(CASE WHEN shmi.transcode_decision = 'direct play' THEN sh.d ELSE 0 END) AS dp_count, " \
'SUM(CASE WHEN shmi.transcode_decision = "copy" THEN sh.d ELSE 0 END) AS ds_count, ' \ "SUM(CASE WHEN shmi.transcode_decision = 'copy' THEN sh.d ELSE 0 END) AS ds_count, " \
'SUM(CASE WHEN shmi.transcode_decision = "transcode" THEN sh.d ELSE 0 END) AS tc_count ' \ "SUM(CASE WHEN shmi.transcode_decision = 'transcode' THEN sh.d ELSE 0 END) AS tc_count " \
'FROM (SELECT *, ' \ "FROM (SELECT *, " \
' date(started, "unixepoch", "localtime") AS date_played,' \ " date(started, 'unixepoch', 'localtime') AS date_played," \
' SUM(CASE WHEN stopped > 0 THEN (stopped - started) - ' \ " SUM(CASE WHEN stopped > 0 THEN (stopped - started) - " \
' (CASE WHEN paused_counter IS NULL THEN 0 ELSE paused_counter END) ELSE 0 END) ' \ " (CASE WHEN paused_counter IS NULL THEN 0 ELSE paused_counter END) ELSE 0 END) " \
' AS d ' \ " AS d " \
' FROM session_history ' \ " FROM session_history " \
' WHERE session_history.stopped >= %s %s' \ " WHERE session_history.stopped >= %s %s" \
' GROUP BY date_played, %s) AS sh ' \ " GROUP BY date_played, %s) AS sh " \
'JOIN session_history_media_info AS shmi ON shmi.id = sh.id ' \ "JOIN session_history_media_info AS shmi ON shmi.id = sh.id " \
'GROUP BY sh.date_played ' \ "GROUP BY sh.date_played " \
'ORDER BY sh.started' % (timestamp, user_cond, group_by) "ORDER BY sh.started" % (timestamp, user_cond, group_by)
result = monitor_db.select(query) result = monitor_db.select(query)
except Exception as e: except Exception as e:
@ -873,40 +873,40 @@ class Graphs(object):
try: try:
if y_axis == 'plays': if y_axis == 'plays':
query = 'SELECT shmi.video_full_resolution AS resolution, ' \ query = "SELECT shmi.video_full_resolution AS resolution, " \
'SUM(CASE WHEN shmi.transcode_decision = "direct play" THEN 1 ELSE 0 END) AS dp_count, ' \ "SUM(CASE WHEN shmi.transcode_decision = 'direct play' THEN 1 ELSE 0 END) AS dp_count, " \
'SUM(CASE WHEN shmi.transcode_decision = "copy" THEN 1 ELSE 0 END) AS ds_count, ' \ "SUM(CASE WHEN shmi.transcode_decision = 'copy' THEN 1 ELSE 0 END) AS ds_count, " \
'SUM(CASE WHEN shmi.transcode_decision = "transcode" THEN 1 ELSE 0 END) AS tc_count, ' \ "SUM(CASE WHEN shmi.transcode_decision = 'transcode' THEN 1 ELSE 0 END) AS tc_count, " \
'COUNT(sh.id) AS total_count ' \ "COUNT(sh.id) AS total_count " \
'FROM (SELECT * ' \ "FROM (SELECT * " \
' FROM session_history ' \ " FROM session_history " \
' WHERE session_history.stopped >= %s ' \ " WHERE session_history.stopped >= %s " \
' AND session_history.media_type IN ("movie", "episode") %s ' \ " AND session_history.media_type IN ('movie', 'episode') %s " \
' GROUP BY %s) AS sh ' \ " GROUP BY %s) AS sh " \
'JOIN session_history_media_info AS shmi ON shmi.id = sh.id ' \ "JOIN session_history_media_info AS shmi ON shmi.id = sh.id " \
'GROUP BY resolution ' \ "GROUP BY resolution " \
'ORDER BY total_count DESC ' \ "ORDER BY total_count DESC " \
'LIMIT 10' % (timestamp, user_cond, group_by) "LIMIT 10" % (timestamp, user_cond, group_by)
result = monitor_db.select(query) result = monitor_db.select(query)
else: else:
query = 'SELECT shmi.video_full_resolution AS resolution,' \ query = "SELECT shmi.video_full_resolution AS resolution," \
'SUM(CASE WHEN shmi.transcode_decision = "direct play" THEN sh.d ELSE 0 END) AS dp_count, ' \ "SUM(CASE WHEN shmi.transcode_decision = 'direct play' THEN sh.d ELSE 0 END) AS dp_count, " \
'SUM(CASE WHEN shmi.transcode_decision = "copy" THEN sh.d ELSE 0 END) AS ds_count, ' \ "SUM(CASE WHEN shmi.transcode_decision = 'copy' THEN sh.d ELSE 0 END) AS ds_count, " \
'SUM(CASE WHEN shmi.transcode_decision = "transcode" THEN sh.d ELSE 0 END) AS tc_count, ' \ "SUM(CASE WHEN shmi.transcode_decision = 'transcode' THEN sh.d ELSE 0 END) AS tc_count, " \
'SUM(sh.d) AS total_duration ' \ "SUM(sh.d) AS total_duration " \
'FROM (SELECT *, ' \ "FROM (SELECT *, " \
' SUM(CASE WHEN stopped > 0 THEN (stopped - started) - ' \ " SUM(CASE WHEN stopped > 0 THEN (stopped - started) - " \
' (CASE WHEN paused_counter IS NULL THEN 0 ELSE paused_counter END) ELSE 0 END) ' \ " (CASE WHEN paused_counter IS NULL THEN 0 ELSE paused_counter END) ELSE 0 END) " \
' AS d ' \ " AS d " \
' FROM session_history ' \ " FROM session_history " \
' WHERE session_history.stopped >= %s ' \ " WHERE session_history.stopped >= %s " \
' AND session_history.media_type IN ("movie", "episode") %s ' \ " AND session_history.media_type IN ('movie', 'episode') %s " \
' GROUP BY %s) AS sh ' \ " GROUP BY %s) AS sh " \
'JOIN session_history_media_info AS shmi ON shmi.id = sh.id ' \ "JOIN session_history_media_info AS shmi ON shmi.id = sh.id " \
'GROUP BY resolution ' \ "GROUP BY resolution " \
'ORDER BY total_duration DESC ' \ "ORDER BY total_duration DESC " \
'LIMIT 10' % (timestamp, user_cond, group_by) "LIMIT 10" % (timestamp, user_cond, group_by)
result = monitor_db.select(query) result = monitor_db.select(query)
except Exception as e: except Exception as e:
@ -954,66 +954,66 @@ class Graphs(object):
try: try:
if y_axis == 'plays': if y_axis == 'plays':
query = 'SELECT ' \ query = "SELECT " \
'(CASE WHEN shmi.stream_video_full_resolution IS NULL THEN ' \ "(CASE WHEN shmi.stream_video_full_resolution IS NULL THEN " \
' (CASE WHEN shmi.video_decision = "transcode" THEN ' \ " (CASE WHEN shmi.video_decision = 'transcode' THEN " \
' (CASE ' \ " (CASE " \
' WHEN shmi.transcode_height <= 360 THEN "SD" ' \ " WHEN shmi.transcode_height <= 360 THEN 'SD' " \
' WHEN shmi.transcode_height <= 480 THEN "480" ' \ " WHEN shmi.transcode_height <= 480 THEN '480' " \
' WHEN shmi.transcode_height <= 576 THEN "576" ' \ " WHEN shmi.transcode_height <= 576 THEN '576' " \
' WHEN shmi.transcode_height <= 720 THEN "720" ' \ " WHEN shmi.transcode_height <= 720 THEN '720' " \
' WHEN shmi.transcode_height <= 1080 THEN "1080" ' \ " WHEN shmi.transcode_height <= 1080 THEN '1080' " \
' WHEN shmi.transcode_height <= 1440 THEN "QHD" ' \ " WHEN shmi.transcode_height <= 1440 THEN 'QHD' " \
' WHEN shmi.transcode_height <= 2160 THEN "4k" ' \ " WHEN shmi.transcode_height <= 2160 THEN '4k' " \
' ELSE "unknown" END)' \ " ELSE 'unknown' END)" \
' ELSE shmi.video_full_resolution END) ' \ " ELSE shmi.video_full_resolution END) " \
' ELSE shmi.stream_video_full_resolution END) AS resolution, ' \ " ELSE shmi.stream_video_full_resolution END) AS resolution, " \
'SUM(CASE WHEN shmi.transcode_decision = "direct play" THEN 1 ELSE 0 END) AS dp_count, ' \ "SUM(CASE WHEN shmi.transcode_decision = 'direct play' THEN 1 ELSE 0 END) AS dp_count, " \
'SUM(CASE WHEN shmi.transcode_decision = "copy" THEN 1 ELSE 0 END) AS ds_count, ' \ "SUM(CASE WHEN shmi.transcode_decision = 'copy' THEN 1 ELSE 0 END) AS ds_count, " \
'SUM(CASE WHEN shmi.transcode_decision = "transcode" THEN 1 ELSE 0 END) AS tc_count, ' \ "SUM(CASE WHEN shmi.transcode_decision = 'transcode' THEN 1 ELSE 0 END) AS tc_count, " \
'COUNT(sh.id) AS total_count ' \ "COUNT(sh.id) AS total_count " \
'FROM (SELECT * ' \ "FROM (SELECT * " \
' FROM session_history ' \ " FROM session_history " \
' WHERE session_history.stopped >= %s ' \ " WHERE session_history.stopped >= %s " \
' AND session_history.media_type IN ("movie", "episode") %s ' \ " AND session_history.media_type IN ('movie', 'episode') %s " \
' GROUP BY %s) AS sh ' \ " GROUP BY %s) AS sh " \
'JOIN session_history_media_info AS shmi ON shmi.id = sh.id ' \ "JOIN session_history_media_info AS shmi ON shmi.id = sh.id " \
'GROUP BY resolution ' \ "GROUP BY resolution " \
'ORDER BY total_count DESC ' \ "ORDER BY total_count DESC " \
'LIMIT 10' % (timestamp, user_cond, group_by) "LIMIT 10" % (timestamp, user_cond, group_by)
result = monitor_db.select(query) result = monitor_db.select(query)
else: else:
query = 'SELECT ' \ query = "SELECT " \
'(CASE WHEN shmi.stream_video_full_resolution IS NULL THEN ' \ "(CASE WHEN shmi.stream_video_full_resolution IS NULL THEN " \
' (CASE WHEN shmi.video_decision = "transcode" THEN ' \ " (CASE WHEN shmi.video_decision = 'transcode' THEN " \
' (CASE ' \ " (CASE " \
' WHEN shmi.transcode_height <= 360 THEN "SD" ' \ " WHEN shmi.transcode_height <= 360 THEN 'SD' " \
' WHEN shmi.transcode_height <= 480 THEN "480" ' \ " WHEN shmi.transcode_height <= 480 THEN '480' " \
' WHEN shmi.transcode_height <= 576 THEN "576" ' \ " WHEN shmi.transcode_height <= 576 THEN '576' " \
' WHEN shmi.transcode_height <= 720 THEN "720" ' \ " WHEN shmi.transcode_height <= 720 THEN '720' " \
' WHEN shmi.transcode_height <= 1080 THEN "1080" ' \ " WHEN shmi.transcode_height <= 1080 THEN '1080' " \
' WHEN shmi.transcode_height <= 1440 THEN "QHD" ' \ " WHEN shmi.transcode_height <= 1440 THEN 'QHD' " \
' WHEN shmi.transcode_height <= 2160 THEN "4k" ' \ " WHEN shmi.transcode_height <= 2160 THEN '4k' " \
' ELSE "unknown" END)' \ " ELSE 'unknown' END)" \
' ELSE shmi.video_full_resolution END) ' \ " ELSE shmi.video_full_resolution END) " \
' ELSE shmi.stream_video_full_resolution END) AS resolution, ' \ " ELSE shmi.stream_video_full_resolution END) AS resolution, " \
'SUM(CASE WHEN shmi.transcode_decision = "direct play" THEN sh.d ELSE 0 END) AS dp_count, ' \ "SUM(CASE WHEN shmi.transcode_decision = 'direct play' THEN sh.d ELSE 0 END) AS dp_count, " \
'SUM(CASE WHEN shmi.transcode_decision = "copy" THEN sh.d ELSE 0 END) AS ds_count, ' \ "SUM(CASE WHEN shmi.transcode_decision = 'copy' THEN sh.d ELSE 0 END) AS ds_count, " \
'SUM(CASE WHEN shmi.transcode_decision = "transcode" THEN sh.d ELSE 0 END) AS tc_count, ' \ "SUM(CASE WHEN shmi.transcode_decision = 'transcode' THEN sh.d ELSE 0 END) AS tc_count, " \
'SUM(sh.d) AS total_duration ' \ "SUM(sh.d) AS total_duration " \
'FROM (SELECT *, ' \ "FROM (SELECT *, " \
' SUM(CASE WHEN stopped > 0 THEN (stopped - started) - ' \ " SUM(CASE WHEN stopped > 0 THEN (stopped - started) - " \
' (CASE WHEN paused_counter IS NULL THEN 0 ELSE paused_counter END) ELSE 0 END) ' \ " (CASE WHEN paused_counter IS NULL THEN 0 ELSE paused_counter END) ELSE 0 END) " \
' AS d ' \ " AS d " \
' FROM session_history ' \ " FROM session_history " \
' WHERE session_history.stopped >= %s ' \ " WHERE session_history.stopped >= %s " \
' AND session_history.media_type IN ("movie", "episode") %s ' \ " AND session_history.media_type IN ('movie', 'episode') %s " \
' GROUP BY %s) AS sh ' \ " GROUP BY %s) AS sh " \
'JOIN session_history_media_info AS shmi ON shmi.id = sh.id ' \ "JOIN session_history_media_info AS shmi ON shmi.id = sh.id " \
'GROUP BY resolution ' \ "GROUP BY resolution " \
'ORDER BY total_duration DESC ' \ "ORDER BY total_duration DESC " \
'LIMIT 10' % (timestamp, user_cond, group_by) "LIMIT 10" % (timestamp, user_cond, group_by)
result = monitor_db.select(query) result = monitor_db.select(query)
except Exception as e: except Exception as e:
@ -1061,38 +1061,38 @@ class Graphs(object):
try: try:
if y_axis == 'plays': if y_axis == 'plays':
query = 'SELECT sh.platform, ' \ query = "SELECT sh.platform, " \
'SUM(CASE WHEN shmi.transcode_decision = "direct play" THEN 1 ELSE 0 END) AS dp_count, ' \ "SUM(CASE WHEN shmi.transcode_decision = 'direct play' THEN 1 ELSE 0 END) AS dp_count, " \
'SUM(CASE WHEN shmi.transcode_decision = "copy" THEN 1 ELSE 0 END) AS ds_count, ' \ "SUM(CASE WHEN shmi.transcode_decision = 'copy' THEN 1 ELSE 0 END) AS ds_count, " \
'SUM(CASE WHEN shmi.transcode_decision = "transcode" THEN 1 ELSE 0 END) AS tc_count, ' \ "SUM(CASE WHEN shmi.transcode_decision = 'transcode' THEN 1 ELSE 0 END) AS tc_count, " \
'COUNT(sh.id) AS total_count ' \ "COUNT(sh.id) AS total_count " \
'FROM (SELECT * ' \ "FROM (SELECT * " \
' FROM session_history ' \ " FROM session_history " \
' WHERE session_history.stopped >= %s %s ' \ " WHERE session_history.stopped >= %s %s " \
' GROUP BY %s) AS sh ' \ " GROUP BY %s) AS sh " \
'JOIN session_history_media_info AS shmi ON shmi.id = sh.id ' \ "JOIN session_history_media_info AS shmi ON shmi.id = sh.id " \
'GROUP BY sh.platform ' \ "GROUP BY sh.platform " \
'ORDER BY total_count DESC ' \ "ORDER BY total_count DESC " \
'LIMIT 10' % (timestamp, user_cond, group_by) "LIMIT 10" % (timestamp, user_cond, group_by)
result = monitor_db.select(query) result = monitor_db.select(query)
else: else:
query = 'SELECT sh.platform, ' \ query = "SELECT sh.platform, " \
'SUM(CASE WHEN shmi.transcode_decision = "direct play" THEN sh.d ELSE 0 END) AS dp_count, ' \ "SUM(CASE WHEN shmi.transcode_decision = 'direct play' THEN sh.d ELSE 0 END) AS dp_count, " \
'SUM(CASE WHEN shmi.transcode_decision = "copy" THEN sh.d ELSE 0 END) AS ds_count, ' \ "SUM(CASE WHEN shmi.transcode_decision = 'copy' THEN sh.d ELSE 0 END) AS ds_count, " \
'SUM(CASE WHEN shmi.transcode_decision = "transcode" THEN sh.d ELSE 0 END) AS tc_count, ' \ "SUM(CASE WHEN shmi.transcode_decision = 'transcode' THEN sh.d ELSE 0 END) AS tc_count, " \
'SUM(sh.d) AS total_duration ' \ "SUM(sh.d) AS total_duration " \
'FROM (SELECT *, ' \ "FROM (SELECT *, " \
' SUM(CASE WHEN stopped > 0 THEN (stopped - started) - ' \ " SUM(CASE WHEN stopped > 0 THEN (stopped - started) - " \
' (CASE WHEN paused_counter IS NULL THEN 0 ELSE paused_counter END) ELSE 0 END) ' \ " (CASE WHEN paused_counter IS NULL THEN 0 ELSE paused_counter END) ELSE 0 END) " \
' AS d ' \ " AS d " \
' FROM session_history ' \ " FROM session_history " \
' WHERE session_history.stopped >= %s %s ' \ " WHERE session_history.stopped >= %s %s " \
' GROUP BY %s) AS sh ' \ " GROUP BY %s) AS sh " \
'JOIN session_history_media_info AS shmi ON shmi.id = sh.id ' \ "JOIN session_history_media_info AS shmi ON shmi.id = sh.id " \
'GROUP BY sh.platform ' \ "GROUP BY sh.platform " \
'ORDER BY total_duration DESC ' \ "ORDER BY total_duration DESC " \
'LIMIT 10' % (timestamp, user_cond, group_by) "LIMIT 10" % (timestamp, user_cond, group_by)
result = monitor_db.select(query) result = monitor_db.select(query)
except Exception as e: except Exception as e:
@ -1141,44 +1141,44 @@ class Graphs(object):
try: try:
if y_axis == 'plays': if y_axis == 'plays':
query = 'SELECT u.user_id, u.username, ' \ query = "SELECT u.user_id, u.username, " \
'(CASE WHEN u.friendly_name IS NULL OR TRIM(u.friendly_name) = "" ' \ "(CASE WHEN u.friendly_name IS NULL OR TRIM(u.friendly_name) = '' " \
' THEN u.username ELSE u.friendly_name END) AS friendly_name,' \ " THEN u.username ELSE u.friendly_name END) AS friendly_name," \
'SUM(CASE WHEN shmi.transcode_decision = "direct play" THEN 1 ELSE 0 END) AS dp_count, ' \ "SUM(CASE WHEN shmi.transcode_decision = 'direct play' THEN 1 ELSE 0 END) AS dp_count, " \
'SUM(CASE WHEN shmi.transcode_decision = "copy" THEN 1 ELSE 0 END) AS ds_count, ' \ "SUM(CASE WHEN shmi.transcode_decision = 'copy' THEN 1 ELSE 0 END) AS ds_count, " \
'SUM(CASE WHEN shmi.transcode_decision = "transcode" THEN 1 ELSE 0 END) AS tc_count, ' \ "SUM(CASE WHEN shmi.transcode_decision = 'transcode' THEN 1 ELSE 0 END) AS tc_count, " \
'COUNT(sh.id) AS total_count ' \ "COUNT(sh.id) AS total_count " \
'FROM (SELECT * ' \ "FROM (SELECT * " \
' FROM session_history ' \ " FROM session_history " \
' WHERE session_history.stopped >= %s %s ' \ " WHERE session_history.stopped >= %s %s " \
' GROUP BY %s) AS sh ' \ " GROUP BY %s) AS sh " \
'JOIN session_history_media_info AS shmi ON shmi.id = sh.id ' \ "JOIN session_history_media_info AS shmi ON shmi.id = sh.id " \
'JOIN users AS u ON u.user_id = sh.user_id ' \ "JOIN users AS u ON u.user_id = sh.user_id " \
'GROUP BY u.user_id ' \ "GROUP BY u.user_id " \
'ORDER BY total_count DESC ' \ "ORDER BY total_count DESC " \
'LIMIT 10' % (timestamp, user_cond, group_by) "LIMIT 10" % (timestamp, user_cond, group_by)
result = monitor_db.select(query) result = monitor_db.select(query)
else: else:
query = 'SELECT u.user_id, u.username, ' \ query = "SELECT u.user_id, u.username, " \
'(CASE WHEN u.friendly_name IS NULL OR TRIM(u.friendly_name) = "" ' \ "(CASE WHEN u.friendly_name IS NULL OR TRIM(u.friendly_name) = '' " \
' THEN u.username ELSE u.friendly_name END) AS friendly_name,' \ " THEN u.username ELSE u.friendly_name END) AS friendly_name," \
'SUM(CASE WHEN shmi.transcode_decision = "direct play" THEN sh.d ELSE 0 END) AS dp_count, ' \ "SUM(CASE WHEN shmi.transcode_decision = 'direct play' THEN sh.d ELSE 0 END) AS dp_count, " \
'SUM(CASE WHEN shmi.transcode_decision = "copy" THEN sh.d ELSE 0 END) AS ds_count, ' \ "SUM(CASE WHEN shmi.transcode_decision = 'copy' THEN sh.d ELSE 0 END) AS ds_count, " \
'SUM(CASE WHEN shmi.transcode_decision = "transcode" THEN sh.d ELSE 0 END) AS tc_count, ' \ "SUM(CASE WHEN shmi.transcode_decision = 'transcode' THEN sh.d ELSE 0 END) AS tc_count, " \
'SUM(sh.d) AS total_duration ' \ "SUM(sh.d) AS total_duration " \
'FROM (SELECT *, ' \ "FROM (SELECT *, " \
' SUM(CASE WHEN stopped > 0 THEN (stopped - started) - ' \ " SUM(CASE WHEN stopped > 0 THEN (stopped - started) - " \
' (CASE WHEN paused_counter IS NULL THEN 0 ELSE paused_counter END) ELSE 0 END) ' \ " (CASE WHEN paused_counter IS NULL THEN 0 ELSE paused_counter END) ELSE 0 END) " \
' AS d ' \ " AS d " \
' FROM session_history ' \ " FROM session_history " \
' WHERE session_history.stopped >= %s %s ' \ " WHERE session_history.stopped >= %s %s " \
' GROUP BY %s) AS sh ' \ " GROUP BY %s) AS sh " \
'JOIN session_history_media_info AS shmi ON shmi.id = sh.id ' \ "JOIN session_history_media_info AS shmi ON shmi.id = sh.id " \
'JOIN users AS u ON u.user_id = sh.user_id ' \ "JOIN users AS u ON u.user_id = sh.user_id " \
'GROUP BY u.user_id ' \ "GROUP BY u.user_id " \
'ORDER BY total_duration DESC ' \ "ORDER BY total_duration DESC " \
'LIMIT 10' % (timestamp, user_cond, group_by) "LIMIT 10" % (timestamp, user_cond, group_by)
result = monitor_db.select(query) result = monitor_db.select(query)
except Exception as e: except Exception as e:

View file

@ -95,8 +95,8 @@ def refresh_libraries():
add_live_tv_library(refresh=True) add_live_tv_library(refresh=True)
query = 'UPDATE library_sections SET is_active = 0 WHERE server_id != ? OR ' \ query = "UPDATE library_sections SET is_active = 0 WHERE server_id != ? OR " \
'section_id NOT IN ({})'.format(', '.join(['?'] * len(section_ids))) "section_id NOT IN ({})".format(", ".join(["?"] * len(section_ids)))
monitor_db.action(query=query, args=[plexpy.CONFIG.PMS_IDENTIFIER] + section_ids) monitor_db.action(query=query, args=[plexpy.CONFIG.PMS_IDENTIFIER] + section_ids)
new_keys = plexpy.CONFIG.HOME_LIBRARY_CARDS + new_keys new_keys = plexpy.CONFIG.HOME_LIBRARY_CARDS + new_keys
@ -112,8 +112,8 @@ def refresh_libraries():
def add_live_tv_library(refresh=False): def add_live_tv_library(refresh=False):
monitor_db = database.MonitorDatabase() monitor_db = database.MonitorDatabase()
result = monitor_db.select_single('SELECT * FROM library_sections ' result = monitor_db.select_single("SELECT * FROM library_sections "
'WHERE section_id = ? and server_id = ?', "WHERE section_id = ? and server_id = ?",
[common.LIVE_TV_SECTION_ID, plexpy.CONFIG.PMS_IDENTIFIER]) [common.LIVE_TV_SECTION_ID, plexpy.CONFIG.PMS_IDENTIFIER])
if result and not refresh or not result and refresh: if result and not refresh or not result and refresh:
@ -138,7 +138,7 @@ def add_live_tv_library(refresh=False):
def has_library_type(section_type): def has_library_type(section_type):
monitor_db = database.MonitorDatabase() monitor_db = database.MonitorDatabase()
query = 'SELECT * FROM library_sections WHERE section_type = ? AND deleted_section = 0' query = "SELECT * FROM library_sections WHERE section_type = ? AND deleted_section = 0"
args = [section_type] args = [section_type]
result = monitor_db.select_single(query=query, args=args) result = monitor_db.select_single(query=query, args=args)
return bool(result) return bool(result)
@ -328,44 +328,44 @@ class Libraries(object):
group_by = 'session_history.reference_id' if grouping else 'session_history.id' group_by = 'session_history.reference_id' if grouping else 'session_history.id'
columns = ['library_sections.id AS row_id', columns = ["library_sections.id AS row_id",
'library_sections.server_id', "library_sections.server_id",
'library_sections.section_id', "library_sections.section_id",
'library_sections.section_name', "library_sections.section_name",
'library_sections.section_type', "library_sections.section_type",
'library_sections.count', "library_sections.count",
'library_sections.parent_count', "library_sections.parent_count",
'library_sections.child_count', "library_sections.child_count",
'library_sections.thumb AS library_thumb', "library_sections.thumb AS library_thumb",
'library_sections.custom_thumb_url AS custom_thumb', "library_sections.custom_thumb_url AS custom_thumb",
'library_sections.art AS library_art', "library_sections.art AS library_art",
'library_sections.custom_art_url AS custom_art', "library_sections.custom_art_url AS custom_art",
'COUNT(DISTINCT %s) AS plays' % group_by, "COUNT(DISTINCT %s) AS plays" % group_by,
'SUM(CASE WHEN session_history.stopped > 0 THEN (session_history.stopped - session_history.started) \ "SUM(CASE WHEN session_history.stopped > 0 THEN (session_history.stopped - session_history.started) \
ELSE 0 END) - SUM(CASE WHEN session_history.paused_counter IS NULL THEN 0 ELSE \ ELSE 0 END) - SUM(CASE WHEN session_history.paused_counter IS NULL THEN 0 ELSE \
session_history.paused_counter END) AS duration', session_history.paused_counter END) AS duration",
'MAX(session_history.started) AS last_accessed', "MAX(session_history.started) AS last_accessed",
'MAX(session_history.id) AS history_row_id', "MAX(session_history.id) AS history_row_id",
'session_history_metadata.full_title AS last_played', "session_history_metadata.full_title AS last_played",
'session_history.rating_key', "session_history.rating_key",
'session_history_metadata.media_type', "session_history_metadata.media_type",
'session_history_metadata.thumb', "session_history_metadata.thumb",
'session_history_metadata.parent_thumb', "session_history_metadata.parent_thumb",
'session_history_metadata.grandparent_thumb', "session_history_metadata.grandparent_thumb",
'session_history_metadata.parent_title', "session_history_metadata.parent_title",
'session_history_metadata.year', "session_history_metadata.year",
'session_history_metadata.media_index', "session_history_metadata.media_index",
'session_history_metadata.parent_media_index', "session_history_metadata.parent_media_index",
'session_history_metadata.content_rating', "session_history_metadata.content_rating",
'session_history_metadata.labels', "session_history_metadata.labels",
'session_history_metadata.live', "session_history_metadata.live",
'session_history_metadata.added_at', "session_history_metadata.added_at",
'session_history_metadata.originally_available_at', "session_history_metadata.originally_available_at",
'session_history_metadata.guid', "session_history_metadata.guid",
'library_sections.do_notify', "library_sections.do_notify",
'library_sections.do_notify_created', "library_sections.do_notify_created",
'library_sections.keep_history', "library_sections.keep_history",
'library_sections.is_active' "library_sections.is_active"
] ]
try: try:
query = data_tables.ssp_query(table_name='library_sections', query = data_tables.ssp_query(table_name='library_sections',
@ -499,11 +499,11 @@ class Libraries(object):
group_by = 'rating_key' group_by = 'rating_key'
try: try:
query = 'SELECT MAX(started) AS last_played, COUNT(DISTINCT %s) AS play_count, ' \ query = "SELECT MAX(started) AS last_played, COUNT(DISTINCT %s) AS play_count, " \
'rating_key, parent_rating_key, grandparent_rating_key ' \ "rating_key, parent_rating_key, grandparent_rating_key " \
'FROM session_history ' \ "FROM session_history " \
'WHERE section_id = ? ' \ "WHERE section_id = ? " \
'GROUP BY %s ' % (count_by, group_by) "GROUP BY %s " % (count_by, group_by)
result = monitor_db.select(query, args=[section_id]) result = monitor_db.select(query, args=[section_id])
except Exception as e: except Exception as e:
logger.warn("Tautulli Libraries :: Unable to execute database query for get_datatables_media_info2: %s." % e) logger.warn("Tautulli Libraries :: Unable to execute database query for get_datatables_media_info2: %s." % e)
@ -838,27 +838,27 @@ class Libraries(object):
last_accessed = 'NULL' last_accessed = 'NULL'
join = '' join = ''
if include_last_accessed: if include_last_accessed:
last_accessed = 'MAX(session_history.started)' last_accessed = "MAX(session_history.started)"
join = 'LEFT OUTER JOIN session_history ON library_sections.section_id = session_history.section_id ' \ join = "LEFT OUTER JOIN session_history ON library_sections.section_id = session_history.section_id " \
monitor_db = database.MonitorDatabase() monitor_db = database.MonitorDatabase()
try: try:
if str(section_id).isdigit(): if str(section_id).isdigit():
where = 'library_sections.section_id = ?' where = "library_sections.section_id = ?"
args = [section_id] args = [section_id]
else: else:
raise Exception('Missing section_id') raise Exception('Missing section_id')
query = 'SELECT library_sections.id AS row_id, server_id, library_sections.section_id, ' \ query = "SELECT library_sections.id AS row_id, server_id, library_sections.section_id, " \
'section_name, section_type, ' \ "section_name, section_type, " \
'count, parent_count, child_count, ' \ "count, parent_count, child_count, " \
'library_sections.thumb AS library_thumb, custom_thumb_url AS custom_thumb, ' \ "library_sections.thumb AS library_thumb, custom_thumb_url AS custom_thumb, " \
'library_sections.art AS library_art, ' \ "library_sections.art AS library_art, " \
'custom_art_url AS custom_art, is_active, ' \ "custom_art_url AS custom_art, is_active, " \
'do_notify, do_notify_created, keep_history, deleted_section, %s AS last_accessed ' \ "do_notify, do_notify_created, keep_history, deleted_section, %s AS last_accessed " \
'FROM library_sections %s ' \ "FROM library_sections %s " \
'WHERE %s AND server_id = ? ' % (last_accessed, join, where) "WHERE %s AND server_id = ? " % (last_accessed, join, where)
result = monitor_db.select(query, args=args + [server_id]) result = monitor_db.select(query, args=args + [server_id])
except Exception as e: except Exception as e:
logger.warn("Tautulli Libraries :: Unable to execute database query for get_library_details: %s." % e) logger.warn("Tautulli Libraries :: Unable to execute database query for get_library_details: %s." % e)
@ -924,24 +924,24 @@ class Libraries(object):
try: try:
if days > 0: if days > 0:
if str(section_id).isdigit(): if str(section_id).isdigit():
query = 'SELECT (SUM(stopped - started) - ' \ query = "SELECT (SUM(stopped - started) - " \
'SUM(CASE WHEN paused_counter IS NULL THEN 0 ELSE paused_counter END)) AS total_time, ' \ "SUM(CASE WHEN paused_counter IS NULL THEN 0 ELSE paused_counter END)) AS total_time, " \
'COUNT(DISTINCT %s) AS total_plays ' \ "COUNT(DISTINCT %s) AS total_plays " \
'FROM session_history ' \ "FROM session_history " \
'JOIN session_history_metadata ON session_history_metadata.id = session_history.id ' \ "JOIN session_history_metadata ON session_history_metadata.id = session_history.id " \
'WHERE stopped >= %s ' \ "WHERE stopped >= %s " \
'AND section_id = ?' % (group_by, timestamp_query) "AND section_id = ?" % (group_by, timestamp_query)
result = monitor_db.select(query, args=[section_id]) result = monitor_db.select(query, args=[section_id])
else: else:
result = [] result = []
else: else:
if str(section_id).isdigit(): if str(section_id).isdigit():
query = 'SELECT (SUM(stopped - started) - ' \ query = "SELECT (SUM(stopped - started) - " \
'SUM(CASE WHEN paused_counter IS NULL THEN 0 ELSE paused_counter END)) AS total_time, ' \ "SUM(CASE WHEN paused_counter IS NULL THEN 0 ELSE paused_counter END)) AS total_time, " \
'COUNT(DISTINCT %s) AS total_plays ' \ "COUNT(DISTINCT %s) AS total_plays " \
'FROM session_history ' \ "FROM session_history " \
'JOIN session_history_metadata ON session_history_metadata.id = session_history.id ' \ "JOIN session_history_metadata ON session_history_metadata.id = session_history.id " \
'WHERE section_id = ?' % group_by "WHERE section_id = ?" % group_by
result = monitor_db.select(query, args=[section_id]) result = monitor_db.select(query, args=[section_id])
else: else:
result = [] result = []
@ -981,17 +981,17 @@ class Libraries(object):
try: try:
if str(section_id).isdigit(): if str(section_id).isdigit():
query = 'SELECT (CASE WHEN users.friendly_name IS NULL OR TRIM(users.friendly_name) = "" ' \ query = "SELECT (CASE WHEN users.friendly_name IS NULL OR TRIM(users.friendly_name) = '' " \
'THEN users.username ELSE users.friendly_name END) AS friendly_name, ' \ "THEN users.username ELSE users.friendly_name END) AS friendly_name, " \
'users.user_id, users.username, users.thumb, users.custom_avatar_url AS custom_thumb, ' \ "users.user_id, users.username, users.thumb, users.custom_avatar_url AS custom_thumb, " \
'COUNT(DISTINCT %s) AS total_plays, (SUM(stopped - started) - ' \ "COUNT(DISTINCT %s) AS total_plays, (SUM(stopped - started) - " \
'SUM(CASE WHEN paused_counter IS NULL THEN 0 ELSE paused_counter END)) AS total_time ' \ "SUM(CASE WHEN paused_counter IS NULL THEN 0 ELSE paused_counter END)) AS total_time " \
'FROM session_history ' \ "FROM session_history " \
'JOIN session_history_metadata ON session_history_metadata.id = session_history.id ' \ "JOIN session_history_metadata ON session_history_metadata.id = session_history.id " \
'JOIN users ON users.user_id = session_history.user_id ' \ "JOIN users ON users.user_id = session_history.user_id " \
'WHERE section_id = ? ' \ "WHERE section_id = ? " \
'GROUP BY users.user_id ' \ "GROUP BY users.user_id " \
'ORDER BY total_plays DESC, total_time DESC' % group_by "ORDER BY total_plays DESC, total_time DESC" % group_by
result = monitor_db.select(query, args=[section_id]) result = monitor_db.select(query, args=[section_id])
else: else:
result = [] result = []
@ -1030,16 +1030,16 @@ class Libraries(object):
try: try:
if str(section_id).isdigit(): if str(section_id).isdigit():
query = 'SELECT session_history.id, session_history.media_type, guid, ' \ query = "SELECT session_history.id, session_history.media_type, guid, " \
'session_history.rating_key, session_history.parent_rating_key, session_history.grandparent_rating_key, ' \ "session_history.rating_key, session_history.parent_rating_key, session_history.grandparent_rating_key, " \
'title, parent_title, grandparent_title, original_title, ' \ "title, parent_title, grandparent_title, original_title, " \
'thumb, parent_thumb, grandparent_thumb, media_index, parent_media_index, ' \ "thumb, parent_thumb, grandparent_thumb, media_index, parent_media_index, " \
'year, originally_available_at, added_at, live, started, user, content_rating, labels, section_id ' \ "year, originally_available_at, added_at, live, started, user, content_rating, labels, section_id " \
'FROM session_history_metadata ' \ "FROM session_history_metadata " \
'JOIN session_history ON session_history_metadata.id = session_history.id ' \ "JOIN session_history ON session_history_metadata.id = session_history.id " \
'WHERE section_id = ? ' \ "WHERE section_id = ? " \
'GROUP BY session_history.rating_key ' \ "GROUP BY session_history.rating_key " \
'ORDER BY MAX(started) DESC LIMIT ?' "ORDER BY MAX(started) DESC LIMIT ?"
result = monitor_db.select(query, args=[section_id, limit]) result = monitor_db.select(query, args=[section_id, limit])
else: else:
result = [] result = []
@ -1085,8 +1085,8 @@ class Libraries(object):
monitor_db = database.MonitorDatabase() monitor_db = database.MonitorDatabase()
try: try:
query = 'SELECT section_id, section_name, section_type, agent ' \ query = "SELECT section_id, section_name, section_type, agent " \
'FROM library_sections WHERE deleted_section = 0' "FROM library_sections WHERE deleted_section = 0"
result = monitor_db.select(query=query) result = monitor_db.select(query=query)
except Exception as e: except Exception as e:
logger.warn("Tautulli Libraries :: Unable to execute database query for get_sections: %s." % e) logger.warn("Tautulli Libraries :: Unable to execute database query for get_sections: %s." % e)
@ -1110,8 +1110,8 @@ class Libraries(object):
row_ids = list(map(helpers.cast_to_int, row_ids.split(','))) row_ids = list(map(helpers.cast_to_int, row_ids.split(',')))
# Get the section_ids corresponding to the row_ids # Get the section_ids corresponding to the row_ids
result = monitor_db.select('SELECT server_id, section_id FROM library_sections ' result = monitor_db.select("SELECT server_id, section_id FROM library_sections "
'WHERE id IN ({})'.format(','.join(['?'] * len(row_ids))), row_ids) "WHERE id IN ({})".format(",".join(["?"] * len(row_ids))), row_ids)
success = [] success = []
for library in result: for library in result:
@ -1135,9 +1135,9 @@ class Libraries(object):
logger.info("Tautulli Libraries :: Deleting library with server_id %s and section_id %s from database." logger.info("Tautulli Libraries :: Deleting library with server_id %s and section_id %s from database."
% (server_id, section_id)) % (server_id, section_id))
try: try:
monitor_db.action('UPDATE library_sections ' monitor_db.action("UPDATE library_sections "
'SET deleted_section = 1, keep_history = 0, do_notify = 0, do_notify_created = 0 ' "SET deleted_section = 1, keep_history = 0, do_notify = 0, do_notify_created = 0 "
'WHERE server_id = ? AND section_id = ?', [server_id, section_id]) "WHERE server_id = ? AND section_id = ?", [server_id, section_id])
return delete_success return delete_success
except Exception as e: except Exception as e:
logger.warn("Tautulli Libraries :: Unable to execute database query for delete: %s." % e) logger.warn("Tautulli Libraries :: Unable to execute database query for delete: %s." % e)
@ -1150,26 +1150,26 @@ class Libraries(object):
try: try:
if section_id and section_id.isdigit(): if section_id and section_id.isdigit():
query = 'SELECT * FROM library_sections WHERE section_id = ?' query = "SELECT * FROM library_sections WHERE section_id = ?"
result = monitor_db.select(query=query, args=[section_id]) result = monitor_db.select(query=query, args=[section_id])
if result: if result:
logger.info("Tautulli Libraries :: Re-adding library with id %s to database." % section_id) logger.info("Tautulli Libraries :: Re-adding library with id %s to database." % section_id)
monitor_db.action('UPDATE library_sections ' monitor_db.action("UPDATE library_sections "
'SET deleted_section = 0, keep_history = 1, do_notify = 1, do_notify_created = 1 ' "SET deleted_section = 0, keep_history = 1, do_notify = 1, do_notify_created = 1 "
'WHERE section_id = ?', "WHERE section_id = ?",
[section_id]) [section_id])
return True return True
else: else:
return False return False
elif section_name: elif section_name:
query = 'SELECT * FROM library_sections WHERE section_name = ?' query = "SELECT * FROM library_sections WHERE section_name = ?"
result = monitor_db.select(query=query, args=[section_name]) result = monitor_db.select(query=query, args=[section_name])
if result: if result:
logger.info("Tautulli Libraries :: Re-adding library with name %s to database." % section_name) logger.info("Tautulli Libraries :: Re-adding library with name %s to database." % section_name)
monitor_db.action('UPDATE library_sections ' monitor_db.action("UPDATE library_sections "
'SET deleted_section = 0, keep_history = 1, do_notify = 1, do_notify_created = 1 ' "SET deleted_section = 0, keep_history = 1, do_notify = 1, do_notify_created = 1 "
'WHERE section_name = ?', "WHERE section_name = ?",
[section_name]) [section_name])
return True return True
else: else:
@ -1203,7 +1203,7 @@ class Libraries(object):
try: try:
logger.debug("Tautulli Libraries :: Deleting libraries where server_id does not match %s." % server_id) logger.debug("Tautulli Libraries :: Deleting libraries where server_id does not match %s." % server_id)
monitor_db.action('DELETE FROM library_sections WHERE server_id != ?', [server_id]) monitor_db.action("DELETE FROM library_sections WHERE server_id != ?", [server_id])
return 'Deleted duplicate libraries from the database.' return 'Deleted duplicate libraries from the database.'
except Exception as e: except Exception as e:

View file

@ -67,17 +67,17 @@ def get_mobile_devices(device_id=None, device_token=None):
args = [] args = []
if device_id or device_token: if device_id or device_token:
where = 'WHERE ' where = "WHERE "
if device_id: if device_id:
where_id += 'device_id = ?' where_id += "device_id = ?"
args.append(device_id) args.append(device_id)
if device_token: if device_token:
where_token = 'device_token = ?' where_token = "device_token = ?"
args.append(device_token) args.append(device_token)
where += ' AND '.join([w for w in [where_id, where_token] if w]) where += " AND ".join([w for w in [where_id, where_token] if w])
db = database.MonitorDatabase() db = database.MonitorDatabase()
result = db.select('SELECT * FROM mobile_devices %s' % where, args=args) result = db.select("SELECT * FROM mobile_devices %s" % where, args=args)
return result return result
@ -128,7 +128,7 @@ def get_mobile_device_config(mobile_device_id=None):
return None return None
db = database.MonitorDatabase() db = database.MonitorDatabase()
result = db.select_single('SELECT * FROM mobile_devices WHERE id = ?', result = db.select_single("SELECT * FROM mobile_devices WHERE id = ?",
args=[mobile_device_id]) args=[mobile_device_id])
if result['onesignal_id'] == _ONESIGNAL_DISABLED: if result['onesignal_id'] == _ONESIGNAL_DISABLED:
@ -163,11 +163,11 @@ def delete_mobile_device(mobile_device_id=None, device_id=None):
if mobile_device_id: if mobile_device_id:
logger.debug("Tautulli MobileApp :: Deleting mobile_device_id %s from the database." % mobile_device_id) logger.debug("Tautulli MobileApp :: Deleting mobile_device_id %s from the database." % mobile_device_id)
result = db.action('DELETE FROM mobile_devices WHERE id = ?', args=[mobile_device_id]) result = db.action("DELETE FROM mobile_devices WHERE id = ?", args=[mobile_device_id])
return True return True
elif device_id: elif device_id:
logger.debug("Tautulli MobileApp :: Deleting device_id %s from the database." % device_id) logger.debug("Tautulli MobileApp :: Deleting device_id %s from the database." % device_id)
result = db.action('DELETE FROM mobile_devices WHERE device_id = ?', args=[device_id]) result = db.action("DELETE FROM mobile_devices WHERE device_id = ?", args=[device_id])
return True return True
else: else:
return False return False
@ -179,9 +179,9 @@ def set_official(device_id, onesignal_id):
platform = 'android' if official > 0 else None platform = 'android' if official > 0 else None
try: try:
result = db.action('UPDATE mobile_devices ' result = db.action("UPDATE mobile_devices "
'SET official = ?, platform = coalesce(platform, ?) ' "SET official = ?, platform = coalesce(platform, ?) "
'WHERE device_id = ?', "WHERE device_id = ?",
args=[official, platform, device_id]) args=[official, platform, device_id])
except Exception as e: except Exception as e:
logger.warn("Tautulli MobileApp :: Failed to set official flag for device: %s." % e) logger.warn("Tautulli MobileApp :: Failed to set official flag for device: %s." % e)
@ -193,7 +193,7 @@ def set_last_seen(device_token=None):
last_seen = helpers.timestamp() last_seen = helpers.timestamp()
try: try:
result = db.action('UPDATE mobile_devices SET last_seen = ? WHERE device_token = ?', result = db.action("UPDATE mobile_devices SET last_seen = ? WHERE device_token = ?",
args=[last_seen, device_token]) args=[last_seen, device_token])
except Exception as e: except Exception as e:
logger.warn("Tautulli MobileApp :: Failed to set last_seen time for device: %s." % e) logger.warn("Tautulli MobileApp :: Failed to set last_seen time for device: %s." % e)

View file

@ -181,9 +181,9 @@ def set_notify_success(newsletter_log_id):
def get_last_newsletter_email_msg_id(newsletter_id, notify_action): def get_last_newsletter_email_msg_id(newsletter_id, notify_action):
db = database.MonitorDatabase() db = database.MonitorDatabase()
result = db.select_single('SELECT email_msg_id FROM newsletter_log ' result = db.select_single("SELECT email_msg_id FROM newsletter_log "
'WHERE newsletter_id = ? AND notify_action = ? AND success = 1 ' "WHERE newsletter_id = ? AND notify_action = ? AND success = 1 "
'ORDER BY timestamp DESC LIMIT 1', [newsletter_id, notify_action]) "ORDER BY timestamp DESC LIMIT 1", [newsletter_id, notify_action])
if result: if result:
return result['email_msg_id'] return result['email_msg_id']
@ -193,13 +193,13 @@ def get_newsletter(newsletter_uuid=None, newsletter_id_name=None):
db = database.MonitorDatabase() db = database.MonitorDatabase()
if newsletter_uuid: if newsletter_uuid:
result = db.select_single('SELECT start_date, end_date, uuid, filename FROM newsletter_log ' result = db.select_single("SELECT start_date, end_date, uuid, filename FROM newsletter_log "
'WHERE uuid = ?', [newsletter_uuid]) "WHERE uuid = ?", [newsletter_uuid])
elif newsletter_id_name: elif newsletter_id_name:
result = db.select_single('SELECT start_date, end_date, uuid, filename FROM newsletter_log ' result = db.select_single("SELECT start_date, end_date, uuid, filename FROM newsletter_log "
'JOIN newsletters ON newsletters.id = newsletter_log.newsletter_id ' "JOIN newsletters ON newsletters.id = newsletter_log.newsletter_id "
'WHERE id_name = ? AND notify_action != "test" ' "WHERE id_name = ? AND notify_action != 'test' "
'ORDER BY timestamp DESC LIMIT 1', [newsletter_id_name]) "ORDER BY timestamp DESC LIMIT 1", [newsletter_id_name])
else: else:
result = None result = None

View file

@ -117,15 +117,15 @@ def get_newsletters(newsletter_id=None):
args = [] args = []
if newsletter_id: if newsletter_id:
where = 'WHERE ' where = "WHERE "
if newsletter_id: if newsletter_id:
where_id += 'id = ?' where_id += "id = ?"
args.append(newsletter_id) args.append(newsletter_id)
where += ' AND '.join([w for w in [where_id] if w]) where += " AND ".join([w for w in [where_id] if w])
db = database.MonitorDatabase() db = database.MonitorDatabase()
result = db.select('SELECT id, agent_id, agent_name, agent_label, ' result = db.select("SELECT id, agent_id, agent_name, agent_label, "
'friendly_name, cron, active FROM newsletters %s' % where, args=args) "friendly_name, cron, active FROM newsletters %s" % where, args=args)
return result return result
@ -136,7 +136,7 @@ def delete_newsletter(newsletter_id=None):
if str(newsletter_id).isdigit(): if str(newsletter_id).isdigit():
logger.debug("Tautulli Newsletters :: Deleting newsletter_id %s from the database." logger.debug("Tautulli Newsletters :: Deleting newsletter_id %s from the database."
% newsletter_id) % newsletter_id)
result = db.action('DELETE FROM newsletters WHERE id = ?', args=[newsletter_id]) result = db.action("DELETE FROM newsletters WHERE id = ?", args=[newsletter_id])
return True return True
else: else:
return False return False
@ -151,7 +151,7 @@ def get_newsletter_config(newsletter_id=None, mask_passwords=False):
return None return None
db = database.MonitorDatabase() db = database.MonitorDatabase()
result = db.select_single('SELECT * FROM newsletters WHERE id = ?', args=[newsletter_id]) result = db.select_single("SELECT * FROM newsletters WHERE id = ?", args=[newsletter_id])
if not result: if not result:
return None return None
@ -309,7 +309,7 @@ def send_newsletter(newsletter_id=None, subject=None, body=None, message=None, n
def blacklist_logger(): def blacklist_logger():
db = database.MonitorDatabase() db = database.MonitorDatabase()
notifiers = db.select('SELECT newsletter_config, email_config FROM newsletters') notifiers = db.select("SELECT newsletter_config, email_config FROM newsletters")
for n in notifiers: for n in notifiers:
config = json.loads(n['newsletter_config'] or '{}') config = json.loads(n['newsletter_config'] or '{}')
@ -346,7 +346,7 @@ def generate_newsletter_uuid():
while not uuid or uuid_exists: while not uuid or uuid_exists:
uuid = plexpy.generate_uuid()[:8] uuid = plexpy.generate_uuid()[:8]
result = db.select_single( result = db.select_single(
'SELECT EXISTS(SELECT uuid FROM newsletter_log WHERE uuid = ?) as uuid_exists', [uuid]) "SELECT EXISTS(SELECT uuid FROM newsletter_log WHERE uuid = ?) as uuid_exists", [uuid])
uuid_exists = result['uuid_exists'] uuid_exists = result['uuid_exists']
return uuid return uuid

View file

@ -443,12 +443,12 @@ def notify(notifier_id=None, notify_action=None, stream_data=None, timeline_data
def get_notify_state(session): def get_notify_state(session):
monitor_db = database.MonitorDatabase() monitor_db = database.MonitorDatabase()
result = monitor_db.select('SELECT timestamp, notify_action, notifier_id ' result = monitor_db.select("SELECT timestamp, notify_action, notifier_id "
'FROM notify_log ' "FROM notify_log "
'WHERE session_key = ? ' "WHERE session_key = ? "
'AND rating_key = ? ' "AND rating_key = ? "
'AND user_id = ? ' "AND user_id = ? "
'ORDER BY id DESC', "ORDER BY id DESC",
args=[session['session_key'], session['rating_key'], session['user_id']]) args=[session['session_key'], session['rating_key'], session['user_id']])
notify_states = [] notify_states = []
for item in result: for item in result:
@ -467,16 +467,16 @@ def get_notify_state_enabled(session, notify_action, notified=True):
timestamp_where = 'AND timestamp IS NULL' timestamp_where = 'AND timestamp IS NULL'
monitor_db = database.MonitorDatabase() monitor_db = database.MonitorDatabase()
result = monitor_db.select('SELECT id AS notifier_id, timestamp ' result = monitor_db.select("SELECT id AS notifier_id, timestamp "
'FROM notifiers ' "FROM notifiers "
'LEFT OUTER JOIN (' "LEFT OUTER JOIN ("
'SELECT timestamp, notifier_id ' "SELECT timestamp, notifier_id "
'FROM notify_log ' "FROM notify_log "
'WHERE session_key = ? ' "WHERE session_key = ? "
'AND rating_key = ? ' "AND rating_key = ? "
'AND user_id = ? ' "AND user_id = ? "
'AND notify_action = ?) AS t ON notifiers.id = t.notifier_id ' "AND notify_action = ?) AS t ON notifiers.id = t.notifier_id "
'WHERE %s = 1 %s' % (notify_action, timestamp_where), "WHERE %s = 1 %s" % (notify_action, timestamp_where),
args=[session['session_key'], session['rating_key'], session['user_id'], notify_action]) args=[session['session_key'], session['rating_key'], session['user_id'], notify_action])
return result return result
@ -528,8 +528,8 @@ def set_notify_success(notification_id):
def check_nofity_tag(notify_action, tag): def check_nofity_tag(notify_action, tag):
monitor_db = database.MonitorDatabase() monitor_db = database.MonitorDatabase()
result = monitor_db.select_single('SELECT * FROM notify_log ' result = monitor_db.select_single("SELECT * FROM notify_log "
'WHERE notify_action = ? AND tag = ?', "WHERE notify_action = ? AND tag = ?",
[notify_action, tag]) [notify_action, tag])
return bool(result) return bool(result)
@ -1631,7 +1631,7 @@ def set_hash_image_info(img=None, rating_key=None, width=750, height=1000,
def get_hash_image_info(img_hash=None): def get_hash_image_info(img_hash=None):
db = database.MonitorDatabase() db = database.MonitorDatabase()
query = 'SELECT * FROM image_hash_lookup WHERE img_hash = ?' query = "SELECT * FROM image_hash_lookup WHERE img_hash = ?"
result = db.select_single(query, args=[img_hash]) result = db.select_single(query, args=[img_hash])
return result return result
@ -1640,8 +1640,8 @@ def lookup_tvmaze_by_id(rating_key=None, thetvdb_id=None, imdb_id=None, title=No
db = database.MonitorDatabase() db = database.MonitorDatabase()
try: try:
query = 'SELECT imdb_id, tvmaze_id, tvmaze_url FROM tvmaze_lookup ' \ query = "SELECT imdb_id, tvmaze_id, tvmaze_url FROM tvmaze_lookup " \
'WHERE rating_key = ?' "WHERE rating_key = ?"
tvmaze_info = db.select_single(query, args=[rating_key]) tvmaze_info = db.select_single(query, args=[rating_key])
except Exception as e: except Exception as e:
logger.warn("Tautulli NotificationHandler :: Unable to execute database query for lookup_tvmaze_by_tvdb_id: %s." % e) logger.warn("Tautulli NotificationHandler :: Unable to execute database query for lookup_tvmaze_by_tvdb_id: %s." % e)
@ -1700,8 +1700,8 @@ def lookup_themoviedb_by_id(rating_key=None, thetvdb_id=None, imdb_id=None, titl
db = database.MonitorDatabase() db = database.MonitorDatabase()
try: try:
query = 'SELECT thetvdb_id, imdb_id, themoviedb_id, themoviedb_url FROM themoviedb_lookup ' \ query = "SELECT thetvdb_id, imdb_id, themoviedb_id, themoviedb_url FROM themoviedb_lookup " \
'WHERE rating_key = ?' "WHERE rating_key = ?"
themoviedb_info = db.select_single(query, args=[rating_key]) themoviedb_info = db.select_single(query, args=[rating_key])
except Exception as e: except Exception as e:
logger.warn("Tautulli NotificationHandler :: Unable to execute database query for lookup_themoviedb_by_imdb_id: %s." % e) logger.warn("Tautulli NotificationHandler :: Unable to execute database query for lookup_themoviedb_by_imdb_id: %s." % e)
@ -1778,8 +1778,8 @@ def get_themoviedb_info(rating_key=None, media_type=None, themoviedb_id=None):
db = database.MonitorDatabase() db = database.MonitorDatabase()
try: try:
query = 'SELECT themoviedb_json FROM themoviedb_lookup ' \ query = "SELECT themoviedb_json FROM themoviedb_lookup " \
'WHERE rating_key = ?' "WHERE rating_key = ?"
result = db.select_single(query, args=[rating_key]) result = db.select_single(query, args=[rating_key])
except Exception as e: except Exception as e:
logger.warn("Tautulli NotificationHandler :: Unable to execute database query for get_themoviedb_info: %s." % e) logger.warn("Tautulli NotificationHandler :: Unable to execute database query for get_themoviedb_info: %s." % e)
@ -1829,8 +1829,8 @@ def lookup_musicbrainz_info(musicbrainz_type=None, rating_key=None, artist=None,
db = database.MonitorDatabase() db = database.MonitorDatabase()
try: try:
query = 'SELECT musicbrainz_id, musicbrainz_url, musicbrainz_type FROM musicbrainz_lookup ' \ query = "SELECT musicbrainz_id, musicbrainz_url, musicbrainz_type FROM musicbrainz_lookup " \
'WHERE rating_key = ?' "WHERE rating_key = ?"
musicbrainz_info = db.select_single(query, args=[rating_key]) musicbrainz_info = db.select_single(query, args=[rating_key])
except Exception as e: except Exception as e:
logger.warn("Tautulli NotificationHandler :: Unable to execute database query for lookup_musicbrainz: %s." % e) logger.warn("Tautulli NotificationHandler :: Unable to execute database query for lookup_musicbrainz: %s." % e)

View file

@ -507,7 +507,7 @@ def get_notifiers(notifier_id=None, notify_action=None):
where += ' AND '.join([w for w in [where_id, where_action] if w]) where += ' AND '.join([w for w in [where_id, where_action] if w])
db = database.MonitorDatabase() db = database.MonitorDatabase()
result = db.select('SELECT id, agent_id, agent_name, agent_label, friendly_name, %s FROM notifiers %s' result = db.select("SELECT id, agent_id, agent_name, agent_label, friendly_name, %s FROM notifiers %s"
% (', '.join(notify_actions), where), args=args) % (', '.join(notify_actions), where), args=args)
for item in result: for item in result:
@ -522,7 +522,7 @@ def delete_notifier(notifier_id=None):
if str(notifier_id).isdigit(): if str(notifier_id).isdigit():
logger.debug("Tautulli Notifiers :: Deleting notifier_id %s from the database." logger.debug("Tautulli Notifiers :: Deleting notifier_id %s from the database."
% notifier_id) % notifier_id)
result = db.action('DELETE FROM notifiers WHERE id = ?', args=[notifier_id]) result = db.action("DELETE FROM notifiers WHERE id = ?", args=[notifier_id])
return True return True
else: else:
return False return False
@ -537,7 +537,7 @@ def get_notifier_config(notifier_id=None, mask_passwords=False):
return None return None
db = database.MonitorDatabase() db = database.MonitorDatabase()
result = db.select_single('SELECT * FROM notifiers WHERE id = ?', args=[notifier_id]) result = db.select_single("SELECT * FROM notifiers WHERE id = ?", args=[notifier_id])
if not result: if not result:
return None return None
@ -3866,8 +3866,8 @@ class TAUTULLIREMOTEAPP(Notifier):
db = database.MonitorDatabase() db = database.MonitorDatabase()
try: try:
query = 'SELECT * FROM mobile_devices WHERE official = 1 ' \ query = "SELECT * FROM mobile_devices WHERE official = 1 " \
'AND onesignal_id IS NOT NULL AND onesignal_id != ""' "AND onesignal_id IS NOT NULL AND onesignal_id != ''"
return db.select(query=query) return db.select(query=query)
except Exception as e: except Exception as e:
logger.warn("Tautulli Notifiers :: Unable to retrieve Tautulli Remote app devices list: %s." % e) logger.warn("Tautulli Notifiers :: Unable to retrieve Tautulli Remote app devices list: %s." % e)
@ -4472,8 +4472,8 @@ def check_browser_enabled():
def get_browser_notifications(): def get_browser_notifications():
db = database.MonitorDatabase() db = database.MonitorDatabase()
result = db.select('SELECT notifier_id, subject_text, body_text FROM notify_log ' result = db.select("SELECT notifier_id, subject_text, body_text FROM notify_log "
'WHERE agent_id = 17 AND timestamp >= ? ', "WHERE agent_id = 17 AND timestamp >= ? ",
args=[time.time() - 5]) args=[time.time() - 5])
notifications = [] notifications = []

View file

@ -304,27 +304,27 @@ def import_from_plexivity(database_file=None, table_name=None, import_ignore_int
logger.debug("Tautulli Importer :: Unable to refresh the users list. Aborting import.") logger.debug("Tautulli Importer :: Unable to refresh the users list. Aborting import.")
return None return None
query = 'SELECT id AS id, ' \ query = "SELECT id AS id, " \
'time AS started, ' \ "time AS started, " \
'stopped, ' \ "stopped, " \
'null AS user_id, ' \ "null AS user_id, " \
'user, ' \ "user, " \
'ip_address, ' \ "ip_address, " \
'paused_counter, ' \ "paused_counter, " \
'platform AS player, ' \ "platform AS player, " \
'null AS platform, ' \ "null AS platform, " \
'null as machine_id, ' \ "null as machine_id, " \
'null AS media_type, ' \ "null AS media_type, " \
'null AS view_offset, ' \ "null AS view_offset, " \
'xml, ' \ "xml, " \
'rating as content_rating,' \ "rating as content_rating," \
'summary,' \ "summary," \
'title AS full_title,' \ "title AS full_title," \
'(case when orig_title_ep = "n/a" then orig_title else ' \ "(case when orig_title_ep = 'n/a' then orig_title else " \
'orig_title_ep end) as title,' \ "orig_title_ep end) as title," \
'(case when orig_title_ep != "n/a" then orig_title else ' \ "(case when orig_title_ep != 'n/a' then orig_title else " \
'null end) as grandparent_title ' \ "null end) as grandparent_title " \
'FROM ' + table_name + ' ORDER BY id' "FROM " + table_name + " ORDER BY id"
result = connection.execute(query) result = connection.execute(query)
@ -456,9 +456,9 @@ def import_users():
logger.debug("Tautulli Importer :: Importing Plexivity Users...") logger.debug("Tautulli Importer :: Importing Plexivity Users...")
monitor_db = database.MonitorDatabase() monitor_db = database.MonitorDatabase()
query = 'INSERT OR IGNORE INTO users (user_id, username) ' \ query = "INSERT OR IGNORE INTO users (user_id, username) " \
'SELECT user_id, user ' \ "SELECT user_id, user " \
'FROM session_history WHERE user_id != 1 GROUP BY user_id' "FROM session_history WHERE user_id != 1 GROUP BY user_id"
try: try:
monitor_db.action(query) monitor_db.action(query)

View file

@ -295,29 +295,29 @@ def import_from_plexwatch(database_file=None, table_name=None, import_ignore_int
logger.debug("Tautulli Importer :: Unable to refresh the users list. Aborting import.") logger.debug("Tautulli Importer :: Unable to refresh the users list. Aborting import.")
return None return None
query = 'SELECT time AS started, ' \ query = "SELECT time AS started, " \
'stopped, ' \ "stopped, " \
'cast(ratingKey as text) AS rating_key, ' \ "cast(ratingKey as text) AS rating_key, " \
'null AS user_id, ' \ "null AS user_id, " \
'user, ' \ "user, " \
'ip_address, ' \ "ip_address, " \
'paused_counter, ' \ "paused_counter, " \
'platform AS player, ' \ "platform AS player, " \
'null AS platform, ' \ "null AS platform, " \
'null as machine_id, ' \ "null as machine_id, " \
'parentRatingKey as parent_rating_key, ' \ "parentRatingKey as parent_rating_key, " \
'grandparentRatingKey as grandparent_rating_key, ' \ "grandparentRatingKey as grandparent_rating_key, " \
'null AS media_type, ' \ "null AS media_type, " \
'null AS view_offset, ' \ "null AS view_offset, " \
'xml, ' \ "xml, " \
'rating as content_rating,' \ "rating as content_rating," \
'summary,' \ "summary," \
'title AS full_title,' \ "title AS full_title," \
'(case when orig_title_ep = "" then orig_title else ' \ "(case when orig_title_ep = '' then orig_title else " \
'orig_title_ep end) as title,' \ "orig_title_ep end) as title," \
'(case when orig_title_ep != "" then orig_title else ' \ "(case when orig_title_ep != '' then orig_title else " \
'null end) as grandparent_title ' \ "null end) as grandparent_title " \
'FROM ' + table_name + ' ORDER BY id' "FROM " + table_name + " ORDER BY id"
result = connection.execute(query) result = connection.execute(query)
@ -450,9 +450,9 @@ def import_users():
logger.debug("Tautulli Importer :: Importing PlexWatch Users...") logger.debug("Tautulli Importer :: Importing PlexWatch Users...")
monitor_db = database.MonitorDatabase() monitor_db = database.MonitorDatabase()
query = 'INSERT OR IGNORE INTO users (user_id, username) ' \ query = "INSERT OR IGNORE INTO users (user_id, username) " \
'SELECT user_id, user ' \ "SELECT user_id, user " \
'FROM session_history WHERE user_id != 1 GROUP BY user_id' "FROM session_history WHERE user_id != 1 GROUP BY user_id"
try: try:
monitor_db.action(query) monitor_db.action(query)

View file

@ -75,8 +75,8 @@ def refresh_users():
# Check if we've set a custom avatar if so don't overwrite it. # Check if we've set a custom avatar if so don't overwrite it.
if keys_dict['user_id']: if keys_dict['user_id']:
avatar_urls = monitor_db.select('SELECT thumb, custom_avatar_url ' avatar_urls = monitor_db.select("SELECT thumb, custom_avatar_url "
'FROM users WHERE user_id = ?', "FROM users WHERE user_id = ?",
[keys_dict['user_id']]) [keys_dict['user_id']])
if avatar_urls: if avatar_urls:
if not avatar_urls[0]['custom_avatar_url'] or \ if not avatar_urls[0]['custom_avatar_url'] or \
@ -98,7 +98,7 @@ def refresh_users():
if result == 'insert': if result == 'insert':
new_users.append(item['username']) new_users.append(item['username'])
query = 'UPDATE users SET is_active = 0 WHERE user_id NOT IN ({})'.format(', '.join(['?'] * len(user_ids))) query = "UPDATE users SET is_active = 0 WHERE user_id NOT IN ({})".format(", ".join(["?"] * len(user_ids)))
monitor_db.action(query=query, args=user_ids) monitor_db.action(query=query, args=user_ids)
# Add new users to loger username filter # Add new users to loger username filter
@ -137,43 +137,43 @@ class Users(object):
group_by = 'session_history.reference_id' if grouping else 'session_history.id' group_by = 'session_history.reference_id' if grouping else 'session_history.id'
columns = ['users.id AS row_id', columns = ["users.id AS row_id",
'users.user_id', "users.user_id",
'users.username', "users.username",
'(CASE WHEN users.friendly_name IS NULL OR TRIM(users.friendly_name) = "" \ "(CASE WHEN users.friendly_name IS NULL OR TRIM(users.friendly_name) = '' \
THEN users.username ELSE users.friendly_name END) AS friendly_name', THEN users.username ELSE users.friendly_name END) AS friendly_name",
'users.title', "users.title",
'users.email', "users.email",
'users.thumb AS user_thumb', "users.thumb AS user_thumb",
'users.custom_avatar_url AS custom_thumb', "users.custom_avatar_url AS custom_thumb",
'COUNT(DISTINCT %s) AS plays' % group_by, "COUNT(DISTINCT %s) AS plays" % group_by,
'SUM(CASE WHEN session_history.stopped > 0 THEN (session_history.stopped - session_history.started) \ "SUM(CASE WHEN session_history.stopped > 0 THEN (session_history.stopped - session_history.started) \
ELSE 0 END) - SUM(CASE WHEN session_history.paused_counter IS NULL THEN 0 ELSE \ ELSE 0 END) - SUM(CASE WHEN session_history.paused_counter IS NULL THEN 0 ELSE \
session_history.paused_counter END) AS duration', session_history.paused_counter END) AS duration",
'MAX(session_history.started) AS last_seen', "MAX(session_history.started) AS last_seen",
'MAX(session_history.id) AS history_row_id', "MAX(session_history.id) AS history_row_id",
'session_history_metadata.full_title AS last_played', "session_history_metadata.full_title AS last_played",
'session_history.ip_address', "session_history.ip_address",
'session_history.platform', "session_history.platform",
'session_history.player', "session_history.player",
'session_history.rating_key', "session_history.rating_key",
'session_history_metadata.media_type', "session_history_metadata.media_type",
'session_history_metadata.thumb', "session_history_metadata.thumb",
'session_history_metadata.parent_thumb', "session_history_metadata.parent_thumb",
'session_history_metadata.grandparent_thumb', "session_history_metadata.grandparent_thumb",
'session_history_metadata.parent_title', "session_history_metadata.parent_title",
'session_history_metadata.year', "session_history_metadata.year",
'session_history_metadata.media_index', "session_history_metadata.media_index",
'session_history_metadata.parent_media_index', "session_history_metadata.parent_media_index",
'session_history_metadata.live', "session_history_metadata.live",
'session_history_metadata.added_at', "session_history_metadata.added_at",
'session_history_metadata.originally_available_at', "session_history_metadata.originally_available_at",
'session_history_metadata.guid', "session_history_metadata.guid",
'session_history_media_info.transcode_decision', "session_history_media_info.transcode_decision",
'users.do_notify AS do_notify', "users.do_notify AS do_notify",
'users.keep_history AS keep_history', "users.keep_history AS keep_history",
'users.allow_guest AS allow_guest', "users.allow_guest AS allow_guest",
'users.is_active AS is_active' "users.is_active AS is_active"
] ]
try: try:
query = data_tables.ssp_query(table_name='users', query = data_tables.ssp_query(table_name='users',
@ -270,32 +270,32 @@ class Users(object):
custom_where = ['users.user_id', user_id] custom_where = ['users.user_id', user_id]
columns = ['session_history.id AS history_row_id', columns = ["session_history.id AS history_row_id",
'MIN(session_history.started) AS first_seen', "MIN(session_history.started) AS first_seen",
'MAX(session_history.started) AS last_seen', "MAX(session_history.started) AS last_seen",
'session_history.ip_address', "session_history.ip_address",
'COUNT(session_history.id) AS play_count', "COUNT(session_history.id) AS play_count",
'session_history.platform', "session_history.platform",
'session_history.player', "session_history.player",
'session_history.rating_key', "session_history.rating_key",
'session_history_metadata.full_title AS last_played', "session_history_metadata.full_title AS last_played",
'session_history_metadata.thumb', "session_history_metadata.thumb",
'session_history_metadata.parent_thumb', "session_history_metadata.parent_thumb",
'session_history_metadata.grandparent_thumb', "session_history_metadata.grandparent_thumb",
'session_history_metadata.media_type', "session_history_metadata.media_type",
'session_history_metadata.parent_title', "session_history_metadata.parent_title",
'session_history_metadata.year', "session_history_metadata.year",
'session_history_metadata.media_index', "session_history_metadata.media_index",
'session_history_metadata.parent_media_index', "session_history_metadata.parent_media_index",
'session_history_metadata.live', "session_history_metadata.live",
'session_history_metadata.added_at', "session_history_metadata.added_at",
'session_history_metadata.originally_available_at', "session_history_metadata.originally_available_at",
'session_history_metadata.guid', "session_history_metadata.guid",
'session_history_media_info.transcode_decision', "session_history_media_info.transcode_decision",
'session_history.user', "session_history.user",
'session_history.user_id as custom_user_id', "session_history.user_id as custom_user_id",
'(CASE WHEN users.friendly_name IS NULL OR TRIM(users.friendly_name) = "" \ "(CASE WHEN users.friendly_name IS NULL OR TRIM(users.friendly_name) = '' \
THEN users.username ELSE users.friendly_name END) AS friendly_name' THEN users.username ELSE users.friendly_name END) AS friendly_name"
] ]
try: try:
@ -436,31 +436,31 @@ class Users(object):
last_seen = 'NULL' last_seen = 'NULL'
join = '' join = ''
if include_last_seen: if include_last_seen:
last_seen = 'MAX(session_history.started)' last_seen = "MAX(session_history.started)"
join = 'LEFT OUTER JOIN session_history ON users.user_id = session_history.user_id' join = "LEFT OUTER JOIN session_history ON users.user_id = session_history.user_id"
monitor_db = database.MonitorDatabase() monitor_db = database.MonitorDatabase()
try: try:
if str(user_id).isdigit(): if str(user_id).isdigit():
where = 'users.user_id = ?' where = "users.user_id = ?"
args = [user_id] args = [user_id]
elif user: elif user:
where = 'users.username = ?' where = "users.username = ?"
args = [user] args = [user]
elif email: elif email:
where = 'users.email = ?' where = "users.email = ?"
args = [email] args = [email]
else: else:
raise Exception('Missing user_id, username, or email') raise Exception("Missing user_id, username, or email")
query = 'SELECT users.id AS row_id, users.user_id, username, friendly_name, ' \ query = "SELECT users.id AS row_id, users.user_id, username, friendly_name, " \
'thumb AS user_thumb, custom_avatar_url AS custom_thumb, ' \ "thumb AS user_thumb, custom_avatar_url AS custom_thumb, " \
'email, is_active, is_admin, is_home_user, is_allow_sync, is_restricted, ' \ "email, is_active, is_admin, is_home_user, is_allow_sync, is_restricted, " \
'do_notify, keep_history, deleted_user, ' \ "do_notify, keep_history, deleted_user, " \
'allow_guest, shared_libraries, %s AS last_seen ' \ "allow_guest, shared_libraries, %s AS last_seen " \
'FROM users %s ' \ "FROM users %s " \
'WHERE %s COLLATE NOCASE' % (last_seen, join, where) "WHERE %s COLLATE NOCASE" % (last_seen, join, where)
result = monitor_db.select(query, args=args) result = monitor_db.select(query, args=args)
except Exception as e: except Exception as e:
logger.warn("Tautulli Users :: Unable to execute database query for get_user_details: %s." % e) logger.warn("Tautulli Users :: Unable to execute database query for get_user_details: %s." % e)
@ -531,22 +531,22 @@ class Users(object):
try: try:
if days > 0: if days > 0:
if str(user_id).isdigit(): if str(user_id).isdigit():
query = 'SELECT (SUM(stopped - started) - ' \ query = "SELECT (SUM(stopped - started) - " \
' SUM(CASE WHEN paused_counter IS NULL THEN 0 ELSE paused_counter END)) AS total_time, ' \ " SUM(CASE WHEN paused_counter IS NULL THEN 0 ELSE paused_counter END)) AS total_time, " \
'COUNT(DISTINCT %s) AS total_plays ' \ "COUNT(DISTINCT %s) AS total_plays " \
'FROM session_history ' \ "FROM session_history " \
'WHERE stopped >= %s ' \ "WHERE stopped >= %s " \
'AND user_id = ? ' % (group_by, timestamp_query) "AND user_id = ? " % (group_by, timestamp_query)
result = monitor_db.select(query, args=[user_id]) result = monitor_db.select(query, args=[user_id])
else: else:
result = [] result = []
else: else:
if str(user_id).isdigit(): if str(user_id).isdigit():
query = 'SELECT (SUM(stopped - started) - ' \ query = "SELECT (SUM(stopped - started) - " \
' SUM(CASE WHEN paused_counter IS NULL THEN 0 ELSE paused_counter END)) AS total_time, ' \ " SUM(CASE WHEN paused_counter IS NULL THEN 0 ELSE paused_counter END)) AS total_time, " \
'COUNT(DISTINCT %s) AS total_plays ' \ "COUNT(DISTINCT %s) AS total_plays " \
'FROM session_history ' \ "FROM session_history " \
'WHERE user_id = ? ' % group_by "WHERE user_id = ? " % group_by
result = monitor_db.select(query, args=[user_id]) result = monitor_db.select(query, args=[user_id])
else: else:
result = [] result = []
@ -587,13 +587,13 @@ class Users(object):
try: try:
if str(user_id).isdigit(): if str(user_id).isdigit():
query = 'SELECT player, COUNT(DISTINCT %s) as total_plays, (SUM(stopped - started) - ' \ query = "SELECT player, COUNT(DISTINCT %s) as total_plays, (SUM(stopped - started) - " \
'SUM(CASE WHEN paused_counter IS NULL THEN 0 ELSE paused_counter END)) AS total_time, ' \ "SUM(CASE WHEN paused_counter IS NULL THEN 0 ELSE paused_counter END)) AS total_time, " \
'platform ' \ "platform " \
'FROM session_history ' \ "FROM session_history " \
'WHERE user_id = ? ' \ "WHERE user_id = ? " \
'GROUP BY player ' \ "GROUP BY player " \
'ORDER BY total_plays DESC, total_time DESC' % group_by "ORDER BY total_plays DESC, total_time DESC" % group_by
result = monitor_db.select(query, args=[user_id]) result = monitor_db.select(query, args=[user_id])
else: else:
result = [] result = []
@ -630,17 +630,17 @@ class Users(object):
try: try:
if str(user_id).isdigit(): if str(user_id).isdigit():
query = 'SELECT session_history.id, session_history.media_type, guid, ' \ query = "SELECT session_history.id, session_history.media_type, guid, " \
'session_history.rating_key, session_history.parent_rating_key, session_history.grandparent_rating_key, ' \ "session_history.rating_key, session_history.parent_rating_key, session_history.grandparent_rating_key, " \
'title, parent_title, grandparent_title, original_title, ' \ "title, parent_title, grandparent_title, original_title, " \
'thumb, parent_thumb, grandparent_thumb, media_index, parent_media_index, ' \ "thumb, parent_thumb, grandparent_thumb, media_index, parent_media_index, " \
'year, originally_available_at, added_at, live, started, user ' \ "year, originally_available_at, added_at, live, started, user " \
'FROM session_history_metadata ' \ "FROM session_history_metadata " \
'JOIN session_history ON session_history_metadata.id = session_history.id ' \ "JOIN session_history ON session_history_metadata.id = session_history.id " \
'WHERE user_id = ? ' \ "WHERE user_id = ? " \
'GROUP BY (CASE WHEN session_history.media_type = "track" THEN session_history.parent_rating_key ' \ "GROUP BY (CASE WHEN session_history.media_type = 'track' THEN session_history.parent_rating_key " \
' ELSE session_history.rating_key END) ' \ " ELSE session_history.rating_key END) " \
'ORDER BY MAX(started) DESC LIMIT ?' "ORDER BY MAX(started) DESC LIMIT ?"
result = monitor_db.select(query, args=[user_id, limit]) result = monitor_db.select(query, args=[user_id, limit])
else: else:
result = [] result = []
@ -683,11 +683,11 @@ class Users(object):
monitor_db = database.MonitorDatabase() monitor_db = database.MonitorDatabase()
try: try:
query = 'SELECT id AS row_id, user_id, username, friendly_name, thumb, custom_avatar_url, email, ' \ query = "SELECT id AS row_id, user_id, username, friendly_name, thumb, custom_avatar_url, email, " \
'is_active, is_admin, is_home_user, is_allow_sync, is_restricted, ' \ "is_active, is_admin, is_home_user, is_allow_sync, is_restricted, " \
'do_notify, keep_history, allow_guest, shared_libraries, ' \ "do_notify, keep_history, allow_guest, shared_libraries, " \
'filter_all, filter_movies, filter_tv, filter_music, filter_photos ' \ "filter_all, filter_movies, filter_tv, filter_music, filter_photos " \
'FROM users WHERE deleted_user = 0' "FROM users WHERE deleted_user = 0"
result = monitor_db.select(query=query) result = monitor_db.select(query=query)
except Exception as e: except Exception as e:
logger.warn("Tautulli Users :: Unable to execute database query for get_users: %s." % e) logger.warn("Tautulli Users :: Unable to execute database query for get_users: %s." % e)
@ -729,8 +729,8 @@ class Users(object):
row_ids = list(map(helpers.cast_to_int, row_ids.split(','))) row_ids = list(map(helpers.cast_to_int, row_ids.split(',')))
# Get the user_ids corresponding to the row_ids # Get the user_ids corresponding to the row_ids
result = monitor_db.select('SELECT user_id FROM users ' result = monitor_db.select("SELECT user_id FROM users "
'WHERE id IN ({})'.format(','.join(['?'] * len(row_ids))), row_ids) "WHERE id IN ({})".format(",".join(["?"] * len(row_ids))), row_ids)
success = [] success = []
for user in result: for user in result:
@ -747,9 +747,9 @@ class Users(object):
logger.info("Tautulli Users :: Deleting user with user_id %s from database." logger.info("Tautulli Users :: Deleting user with user_id %s from database."
% user_id) % user_id)
try: try:
monitor_db.action('UPDATE users ' monitor_db.action("UPDATE users "
'SET deleted_user = 1, keep_history = 0, do_notify = 0 ' "SET deleted_user = 1, keep_history = 0, do_notify = 0 "
'WHERE user_id = ?', [user_id]) "WHERE user_id = ?", [user_id])
return delete_success return delete_success
except Exception as e: except Exception as e:
logger.warn("Tautulli Users :: Unable to execute database query for delete: %s." % e) logger.warn("Tautulli Users :: Unable to execute database query for delete: %s." % e)
@ -762,25 +762,25 @@ class Users(object):
try: try:
if user_id and str(user_id).isdigit(): if user_id and str(user_id).isdigit():
query = 'SELECT * FROM users WHERE user_id = ?' query = "SELECT * FROM users WHERE user_id = ?"
result = monitor_db.select(query=query, args=[user_id]) result = monitor_db.select(query=query, args=[user_id])
if result: if result:
logger.info("Tautulli Users :: Re-adding user with id %s to database." % user_id) logger.info("Tautulli Users :: Re-adding user with id %s to database." % user_id)
monitor_db.action('UPDATE users ' monitor_db.action("UPDATE users "
'SET deleted_user = 0, keep_history = 1, do_notify = 1 ' "SET deleted_user = 0, keep_history = 1, do_notify = 1 "
'WHERE user_id = ?', [user_id]) "WHERE user_id = ?", [user_id])
return True return True
else: else:
return False return False
elif username: elif username:
query = 'SELECT * FROM users WHERE username = ?' query = "SELECT * FROM users WHERE username = ?"
result = monitor_db.select(query=query, args=[username]) result = monitor_db.select(query=query, args=[username])
if result: if result:
logger.info("Tautulli Users :: Re-adding user with username %s to database." % username) logger.info("Tautulli Users :: Re-adding user with username %s to database." % username)
monitor_db.action('UPDATE users ' monitor_db.action("UPDATE users "
'SET deleted_user = 0, keep_history = 1, do_notify = 1 ' "SET deleted_user = 0, keep_history = 1, do_notify = 1 "
'WHERE username = ?', [username]) "WHERE username = ?", [username])
return True return True
else: else:
return False return False
@ -793,7 +793,7 @@ class Users(object):
if user: if user:
try: try:
monitor_db = database.MonitorDatabase() monitor_db = database.MonitorDatabase()
query = 'SELECT user_id FROM users WHERE username = ?' query = "SELECT user_id FROM users WHERE username = ?"
result = monitor_db.select_single(query, args=[user]) result = monitor_db.select_single(query, args=[user])
if result: if result:
return result['user_id'] return result['user_id']
@ -809,14 +809,14 @@ class Users(object):
user_cond = '' user_cond = ''
if session.get_session_user_id(): if session.get_session_user_id():
user_cond = 'AND user_id = %s ' % session.get_session_user_id() user_cond = "AND user_id = %s " % session.get_session_user_id()
try: try:
query = 'SELECT user_id, ' \ query = "SELECT user_id, " \
'(CASE WHEN users.friendly_name IS NULL OR TRIM(users.friendly_name) = "" \ "(CASE WHEN users.friendly_name IS NULL OR TRIM(users.friendly_name) = '' \
THEN users.username ELSE users.friendly_name END) AS friendly_name ' \ THEN users.username ELSE users.friendly_name END) AS friendly_name " \
'FROM users ' \ "FROM users " \
'WHERE deleted_user = 0 %s' % user_cond "WHERE deleted_user = 0 %s" % user_cond
result = monitor_db.select(query) result = monitor_db.select(query)
except Exception as e: except Exception as e:
@ -835,8 +835,8 @@ class Users(object):
if user_id: if user_id:
try: try:
monitor_db = database.MonitorDatabase() monitor_db = database.MonitorDatabase()
query = 'SELECT allow_guest, user_token, server_token FROM users ' \ query = "SELECT allow_guest, user_token, server_token FROM users " \
'WHERE user_id = ? AND deleted_user = 0' "WHERE user_id = ? AND deleted_user = 0"
result = monitor_db.select_single(query, args=[user_id]) result = monitor_db.select_single(query, args=[user_id])
if result: if result:
tokens = {'allow_guest': result['allow_guest'], tokens = {'allow_guest': result['allow_guest'],
@ -857,8 +857,8 @@ class Users(object):
try: try:
monitor_db = database.MonitorDatabase() monitor_db = database.MonitorDatabase()
query = 'SELECT filter_all, filter_movies, filter_tv, filter_music, filter_photos FROM users ' \ query = "SELECT filter_all, filter_movies, filter_tv, filter_music, filter_photos FROM users " \
'WHERE user_id = ?' "WHERE user_id = ?"
result = monitor_db.select_single(query, args=[user_id]) result = monitor_db.select_single(query, args=[user_id])
except Exception as e: except Exception as e:
logger.warn("Tautulli Users :: Unable to execute database query for get_filters: %s." % e) logger.warn("Tautulli Users :: Unable to execute database query for get_filters: %s." % e)
@ -907,8 +907,8 @@ class Users(object):
def get_user_login(self, jwt_token): def get_user_login(self, jwt_token):
monitor_db = database.MonitorDatabase() monitor_db = database.MonitorDatabase()
result = monitor_db.select_single('SELECT * FROM user_login ' result = monitor_db.select_single("SELECT * FROM user_login "
'WHERE jwt_token = ?', "WHERE jwt_token = ?",
[jwt_token]) [jwt_token])
return result return result
@ -918,8 +918,8 @@ class Users(object):
if jwt_token: if jwt_token:
logger.debug("Tautulli Users :: Clearing user JWT token.") logger.debug("Tautulli Users :: Clearing user JWT token.")
try: try:
monitor_db.action('UPDATE user_login SET jwt_token = NULL ' monitor_db.action("UPDATE user_login SET jwt_token = NULL "
'WHERE jwt_token = ?', "WHERE jwt_token = ?",
[jwt_token]) [jwt_token])
except Exception as e: except Exception as e:
logger.error("Tautulli Users :: Unable to clear user JWT token: %s.", e) logger.error("Tautulli Users :: Unable to clear user JWT token: %s.", e)
@ -929,8 +929,8 @@ class Users(object):
row_ids = list(map(helpers.cast_to_int, row_ids.split(','))) row_ids = list(map(helpers.cast_to_int, row_ids.split(',')))
logger.debug("Tautulli Users :: Clearing JWT tokens for row_ids %s.", row_ids) logger.debug("Tautulli Users :: Clearing JWT tokens for row_ids %s.", row_ids)
try: try:
monitor_db.action('UPDATE user_login SET jwt_token = NULL ' monitor_db.action("UPDATE user_login SET jwt_token = NULL "
'WHERE id in ({})'.format(','.join(['?'] * len(row_ids))), "WHERE id in ({})".format(",".join(["?"] * len(row_ids))),
row_ids) row_ids)
except Exception as e: except Exception as e:
logger.error("Tautulli Users :: Unable to clear JWT tokens: %s.", e) logger.error("Tautulli Users :: Unable to clear JWT tokens: %s.", e)
@ -954,19 +954,19 @@ class Users(object):
else: else:
custom_where = [['user_login.user_id', user_id]] if user_id else [] custom_where = [['user_login.user_id', user_id]] if user_id else []
columns = ['user_login.id AS row_id', columns = ["user_login.id AS row_id",
'user_login.timestamp', "user_login.timestamp",
'user_login.user_id', "user_login.user_id",
'user_login.user', "user_login.user",
'user_login.user_group', "user_login.user_group",
'user_login.ip_address', "user_login.ip_address",
'user_login.host', "user_login.host",
'user_login.user_agent', "user_login.user_agent",
'user_login.success', "user_login.success",
'user_login.expiry', "user_login.expiry",
'user_login.jwt_token', "user_login.jwt_token",
'(CASE WHEN users.friendly_name IS NULL OR TRIM(users.friendly_name) = "" \ "(CASE WHEN users.friendly_name IS NULL OR TRIM(users.friendly_name) = '' \
THEN users.username ELSE users.friendly_name END) AS friendly_name' THEN users.username ELSE users.friendly_name END) AS friendly_name"
] ]
try: try:

View file

@ -99,7 +99,7 @@ def plex_user_login(token=None, headers=None):
try: try:
logger.debug("Tautulli WebAuth :: Registering token for user '%s' in the database." logger.debug("Tautulli WebAuth :: Registering token for user '%s' in the database."
% user_details['username']) % user_details['username'])
result = monitor_db.action('UPDATE users SET server_token = ? WHERE user_id = ?', result = monitor_db.action("UPDATE users SET server_token = ? WHERE user_id = ?",
[server_token, user_details['user_id']]) [server_token, user_details['user_id']])
if result: if result:
@ -246,12 +246,12 @@ def all_of(*conditions):
def check_rate_limit(ip_address): def check_rate_limit(ip_address):
monitor_db = MonitorDatabase() monitor_db = MonitorDatabase()
result = monitor_db.select('SELECT timestamp, success FROM user_login ' result = monitor_db.select("SELECT timestamp, success FROM user_login "
'WHERE ip_address = ? ' "WHERE ip_address = ? "
'AND timestamp >= ( ' "AND timestamp >= ( "
'SELECT CASE WHEN MAX(timestamp) IS NULL THEN 0 ELSE MAX(timestamp) END ' "SELECT CASE WHEN MAX(timestamp) IS NULL THEN 0 ELSE MAX(timestamp) END "
'FROM user_login WHERE ip_address = ? AND success = 1) ' "FROM user_login WHERE ip_address = ? AND success = 1) "
'ORDER BY timestamp DESC', "ORDER BY timestamp DESC",
[ip_address, ip_address]) [ip_address, ip_address])
try: try: