removed all instances of shadow of outer scope, made explicit from

implicit inheritance, defined a few docstring params, initialized 2 vars
This commit is contained in:
dirtycajunrice 2018-12-19 19:57:30 -06:00
parent 463586ff29
commit f9ce8eae63
2 changed files with 46 additions and 35 deletions

View File

@ -46,11 +46,13 @@ Tautulli > Settings > Notification Agents > New Script > Script Arguments:
import os import os
import sys import sys
import argparse
import json import json
import time import time
import argparse
from datetime import datetime from datetime import datetime
import requests from requests import Session
from requests.adapters import HTTPAdapter
from requests.exceptions import RequestException
TAUTULLI_URL = '' TAUTULLI_URL = ''
@ -109,13 +111,15 @@ def debug_dump_vars():
.rjust(len(TAUTULLI_APIKEY), "x")) .rjust(len(TAUTULLI_APIKEY), "x"))
def get_all_streams(user_id=None): def get_all_streams(tautulli, user_id=None):
"""Get a list of all current streams. """Get a list of all current streams.
Parameters Parameters
---------- ----------
user_id : int user_id : int
The ID of the user to grab sessions for. The ID of the user to grab sessions for.
tautulli : obj
Tautulli object.
Returns Returns
------- -------
objects objects
@ -131,17 +135,17 @@ def get_all_streams(user_id=None):
return streams return streams
def notify(opts, message, kill_type=None, stream=None): def notify(all_opts, message, kill_type=None, stream=None, tautulli=None):
"""Decides which notifier type to use""" """Decides which notifier type to use"""
if opts.notify and opts.richMessage: if all_opts.notify and all_opts.richMessage:
rich_notify(opts.notify, opts.richMessage, opts.richColor, kill_type, rich_notify(all_opts.notify, all_opts.richMessage, all_opts.richColor, kill_type,
opts.serverName, opts.plexUrl, opts.posterUrl, message, stream) all_opts.serverName, all_opts.plexUrl, all_opts.posterUrl, message, stream, tautulli)
elif opts.notify: elif all_opts.notify:
basic_notify(opts.notify, opts.sessionId, opts.username, message) basic_notify(all_opts.notify, all_opts.sessionId, all_opts.username, message, stream, tautulli)
def rich_notify(notifier_id, rich_type, color=None, kill_type=None, server_name=None, def rich_notify(notifier_id, rich_type, color=None, kill_type=None, server_name=None,
plex_url=None, poster_url=None, message=None, stream=None): plex_url=None, poster_url=None, message=None, stream=None, tautulli=None):
"""Decides which rich notifier type to use. Set default values for empty variables """Decides which rich notifier type to use. Set default values for empty variables
Parameters Parameters
@ -150,6 +154,8 @@ def rich_notify(notifier_id, rich_type, color=None, kill_type=None, server_name=
The ID of the user to grab sessions for. The ID of the user to grab sessions for.
rich_type : str rich_type : str
Contains 'discord' or 'slack'. Contains 'discord' or 'slack'.
color : Union[int, str]
Hex string or integer representation of color.
kill_type : str kill_type : str
The kill type used. The kill type used.
server_name : str server_name : str
@ -162,9 +168,13 @@ def rich_notify(notifier_id, rich_type, color=None, kill_type=None, server_name=
Message sent to the client. Message sent to the client.
stream : obj stream : obj
Stream object. Stream object.
tautulli : obj
Tautulli object.
""" """
notification = Notification(notifier_id, SUBJECT_TEXT, BODY_TEXT, tautulli, stream) notification = Notification(notifier_id, SUBJECT_TEXT, BODY_TEXT, tautulli, stream)
# Initialize Variables
title = ''
footer = ''
# Set a default server_name if none is provided # Set a default server_name if none is provided
if server_name is None: if server_name is None:
server_name = 'Plex Server' server_name = 'Plex Server'
@ -207,7 +217,7 @@ def rich_notify(notifier_id, rich_type, color=None, kill_type=None, server_name=
notification.send_slack(title, color, poster_url, plex_url, message, footer) notification.send_slack(title, color, poster_url, plex_url, message, footer)
def basic_notify(notifier_id, session_id, username=None, message=None): def basic_notify(notifier_id, session_id, username=None, message=None, stream=None, tautulli=None):
"""Basic notifier""" """Basic notifier"""
notification = Notification(notifier_id, SUBJECT_TEXT, BODY_TEXT, tautulli, stream) notification = Notification(notifier_id, SUBJECT_TEXT, BODY_TEXT, tautulli, stream)
@ -225,11 +235,11 @@ class Tautulli:
self.apikey = apikey self.apikey = apikey
self.debug = debug self.debug = debug
self.session = requests.Session() self.session = Session()
self.adapters = requests.adapters.HTTPAdapter(max_retries=3, self.adapters = HTTPAdapter(max_retries=3,
pool_connections=1, pool_connections=1,
pool_maxsize=1, pool_maxsize=1,
pool_block=True) pool_block=True)
self.session.mount('http://', self.adapters) self.session.mount('http://', self.adapters)
self.session.mount('https://', self.adapters) self.session.mount('https://', self.adapters)
@ -240,14 +250,14 @@ class Tautulli:
import urllib3 import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
def _call_api(self, cmd, payload, method='GET', debug=None): def _call_api(self, cmd, payload, method='GET'):
payload['cmd'] = cmd payload['cmd'] = cmd
payload['apikey'] = self.apikey payload['apikey'] = self.apikey
try: try:
response = self.session.request(method, self.url + '/api/v2', params=payload) response = self.session.request(method, self.url + '/api/v2', params=payload)
except: except RequestException as e:
print("Tautulli request failed for cmd '{}'. Invalid Tautulli URL?".format(cmd)) print("Tautulli request failed for cmd '{}'. Invalid Tautulli URL? Error: {}".format(cmd, e))
if self.debug: if self.debug:
traceback.print_exc() traceback.print_exc()
return return
@ -303,11 +313,11 @@ class Tautulli:
class Stream: class Stream:
def __init__(self, session_id=None, user_id=None, username=None, tautulli=None, session=None): def __init__(self, session_id=None, user_id=None, username=None, tautulli=None, session=None):
self.state = None
self.session_id = session_id self.session_id = session_id
self.user_id = user_id self.user_id = user_id
self.username = username self.username = username
self.session_exists = False self.session_exists = False
self.tautulli = tautulli self.tautulli = tautulli
if session is not None: if session is not None:
@ -585,32 +595,32 @@ if __name__ == "__main__":
debug_dump_vars() debug_dump_vars()
# Create a Tautulli instance # Create a Tautulli instance
tautulli = Tautulli(TAUTULLI_URL.rstrip('/'), TAUTULLI_APIKEY, VERIFY_SSL, opts.debug) tautulli_server = Tautulli(TAUTULLI_URL.rstrip('/'), TAUTULLI_APIKEY, VERIFY_SSL, opts.debug)
# Create initial Stream object with basic info # Create initial Stream object with basic info
stream = Stream(opts.sessionId, opts.userId, opts.username, tautulli) tautulli_stream = Stream(opts.sessionId, opts.userId, opts.username, tautulli_server)
# Only pull all stream info if using richMessage # Only pull all stream info if using richMessage
if opts.notify and opts.richMessage: if opts.notify and opts.richMessage:
stream.get_all_stream_info() tautulli_stream.get_all_stream_info()
# Set a default message if none is provided # Set a default message if none is provided
if opts.killMessage: if opts.killMessage:
message = ' '.join(opts.killMessage) kill_message = ' '.join(opts.killMessage)
else: else:
message = 'The server owner has ended the stream.' kill_message = 'The server owner has ended the stream.'
if opts.jbop == 'stream': if opts.jbop == 'stream':
stream.terminate(message) tautulli_stream.terminate(kill_message)
notify(opts, message, 'Stream', stream) notify(opts, kill_message, 'Stream', tautulli_stream, tautulli_server)
elif opts.jbop == 'allStreams': elif opts.jbop == 'allStreams':
streams = get_all_streams(opts.userId) all_streams = get_all_streams(tautulli_server, opts.userId)
for stream in streams: for a_stream in all_streams:
tautulli.terminate_session(session_id=stream.session_id, message=message) tautulli_server.terminate_session(session_id=a_stream.session_id, message=kill_message)
notify(opts, message, 'All Streams', stream) notify(opts, kill_message, 'All Streams', a_stream, tautulli_server)
elif opts.jbop == 'paused': elif opts.jbop == 'paused':
killed_stream = stream.terminate_long_pause(message, opts.limit, opts.interval) killed_stream = tautulli_stream.terminate_long_pause(kill_message, opts.limit, opts.interval)
if killed_stream: if killed_stream:
notify(opts, message, 'Paused', stream) notify(opts, kill_message, 'Paused', tautulli_stream, tautulli_server)

View File

@ -4,3 +4,4 @@
#--------------------------------------------------------- #---------------------------------------------------------
requests requests
plexapi plexapi
urllib3