diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/archive/create_wait_kill_all.py b/archive/create_wait_kill_all.py deleted file mode 100644 index c1a5a46..0000000 --- a/archive/create_wait_kill_all.py +++ /dev/null @@ -1,187 +0,0 @@ -''' -fetch function from https://gist.github.com/Hellowlol/ee47b6534410b1880e19 -PlexPy > Settings > Notification Agents > Scripts > Bell icon: - [X] Notify on pause - -PlexPy > Settings > Notification Agents > Scripts > Gear icon: - Playback Pause: create_wait_kill_all.py - -PlexPy > Settings > Notifications > Script > Script Arguments: - {session_key} - - -create_wait_kill_all.py creates a new file with the session_id (sub_script) as it's name. -PlexPy will timeout create_wait_kill_all.py after 30 seconds (default) but sub_script.py will continue. -sub_script will check if the stream's session_id is still pause or if playing as restarted. -If playback is restarted then sub_script will stop and delete itself. -If stream remains paused then it will be killed and sub_script will stop and delete itself. - -Set TIMEOUT to max time before killing stream -Set INTERVAL to how often you want to check the stream status -''' - -import os -import platform -import subprocess -import sys -from uuid import getnode -import unicodedata - -import requests - -## EDIT THESE SETTINGS ## - -PLEX_HOST = '' -PLEX_PORT = 32400 -PLEX_SSL = '' # s or '' -PLEX_TOKEN = '' -PLEXPY_APIKEY = 'xxxxxxx' # Your PlexPy API key -PLEXPY_URL = 'http://localhost:8181/' # Your PlexPy URL - -TIMEOUT = 120 -INTERVAL = 20 - -REASON = 'Because....' -ignore_lst = ('test') - - -class Activity(object): - def __init__(self, data=None): - d = data or {} - self.video_decision = d['video_decision'] - self.state = d['state'] - self.session_key = d['session_key'] - - -def get_get_activity(): - # Get the user IP list from PlexPy - payload = {'apikey': PLEXPY_APIKEY, - 'cmd': 'get_activity'} - - try: - r = requests.get(PLEXPY_URL.rstrip('/') + '/api/v2', params=payload) - response = r.json() - res_data = response['response']['data']['sessions'] - return [Activity(data=d) for d in res_data] - - except Exception as e: - sys.stderr.write("PlexPy API 'get_get_activity' request failed: {0}.".format(e)) - - -def fetch(path, t='GET'): - url = 'http{}://{}:{}/'.format(PLEX_SSL, PLEX_HOST, PLEX_PORT) - - headers = {'X-Plex-Token': PLEX_TOKEN, - 'Accept': 'application/json', - 'X-Plex-Provides': 'controller', - 'X-Plex-Platform': platform.uname()[0], - 'X-Plex-Platform-Version': platform.uname()[2], - 'X-Plex-Product': 'Plexpy script', - 'X-Plex-Version': '0.9.5', - 'X-Plex-Device': platform.platform(), - 'X-Plex-Client-Identifier': str(hex(getnode())) - } - - try: - if t == 'GET': - r = requests.get(url + path, headers=headers, verify=False) - elif t == 'POST': - r = requests.post(url + path, headers=headers, verify=False) - elif t == 'DELETE': - r = requests.delete(url + path, headers=headers, verify=False) - - if r and len(r.content): # incase it dont return anything - return r.json() - else: - return r.content - - except Exception as e: - print e - - -def kill_stream(sessionId, message, xtime, ntime, user, title, sessionKey): - headers = {'X-Plex-Token': PLEX_TOKEN} - params = {'sessionId': sessionId, - 'reason': message} - - activity = get_get_activity() - - for a in activity: - if a.session_key == sessionKey: - if a.state == 'paused' and xtime == ntime: - sys.stdout.write("Killing {user}'s paused stream of {title}".format(user=user, title=title)) - requests.get('http{}://{}:{}/status/sessions/terminate'.format(PLEX_SSL, PLEX_HOST, PLEX_PORT), - headers=headers, params=params) - return ntime - elif a.state in ('playing', 'buffering'): - sys.stdout.write("{user}'s stream of {title} is now {state}".format(user=user, title=title, - state=a.state)) - return None - else: - return xtime - - -def find_sessionID(response): - - sessions = [] - for video in response['MediaContainer']['Video']: - if video['sessionKey'] == sys.argv[1]: - sess_id = video['Session']['id'] - user = video['User']['title'] - sess_key = video['sessionKey'] - title = (video['grandparentTitle'] + ' - ' if video['type'] == 'episode' else '') + video['title'] - title = unicodedata.normalize('NFKD', title).encode('ascii','ignore') - sessions.append((sess_id, user, title, sess_key)) - else: - pass - - for session in sessions: - if session[1] not in ignore_lst: - return session - else: - print("{}'s stream of {} is ignored.".format(session[1], session[2])) - return None - - -if __name__ == '__main__': - - startupinfo = None - if os.name == 'nt': - startupinfo = subprocess.STARTUPINFO() - startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW - - response = fetch('status/sessions') - fileDir = fileDir = os.path.dirname(os.path.realpath(__file__)) - - try: - if find_sessionID(response): - stream_info = find_sessionID(response) - file_name = "{}.py".format(stream_info[0]) - full_path = os.path.join(fileDir, file_name) - file = 'from time import sleep\n' \ - 'import sys, os\n' \ - 'from {script} import kill_stream \n' \ - 'message = "{REASON}"\n' \ - 'sessionID = os.path.basename(sys.argv[0])[:-3]\n' \ - 'x = 0\n' \ - 'n = {ntime}\n' \ - 'try:\n' \ - ' while x < n and x is not None:\n' \ - ' sleep({xtime})\n' \ - ' x += kill_stream(sessionID, message, {xtime}, n, "{user}", "{title}", "{sess_key}")\n' \ - ' kill_stream(sessionID, message, {ntime}, n, "{user}", "{title}", "{sess_key}")\n' \ - ' os.remove(sys.argv[0])\n' \ - 'except TypeError as e:\n' \ - ' os.remove(sys.argv[0])'.format(script=os.path.basename(__file__)[:-3], - ntime=TIMEOUT, xtime=INTERVAL, REASON=REASON, - user=stream_info[1], title=stream_info[2], sess_key=stream_info[3]) - - with open(full_path, "w+") as output: - output.write(file) - - subprocess.Popen([sys.executable, full_path], startupinfo=startupinfo) - exit(0) - - except TypeError as e: - print(e) - pass diff --git a/archive/create_wait_kill_trans.py b/archive/create_wait_kill_trans.py deleted file mode 100644 index 75ac9a0..0000000 --- a/archive/create_wait_kill_trans.py +++ /dev/null @@ -1,172 +0,0 @@ -''' -fetch function from https://gist.github.com/Hellowlol/ee47b6534410b1880e19 -PlexPy > Settings > Notification Agents > Scripts > Bell icon: - [X] Notify on pause - -PlexPy > Settings > Notification Agents > Scripts > Gear icon: - Playback Pause: create_wait_kill_trans.py - -PlexPy > Settings > Notifications > Script > Script Arguments: - {session_key} - - -create_wait_kill_trans.py creates a new file with the session_id (sub_script) as it's name. -PlexPy will timeout create_wait_kill_trans.py after 30 seconds (default) but sub_script.py will continue. -sub_script will check if the transcoding and stream's session_id is still pause or if playing as restarted. -If playback is restarted then sub_script will stop and delete itself. -If stream remains paused then it will be killed and sub_script will stop and delete itself. - -Set TIMEOUT to max time before killing stream -Set INTERVAL to how often you want to check the stream status -''' - -import os -import platform -import subprocess -import sys -from uuid import getnode -import unicodedata - -import requests - -## EDIT THESE SETTINGS ## - -PLEX_HOST = '' -PLEX_PORT = 32400 -PLEX_SSL = '' # s or '' -PLEX_TOKEN = 'xxxxx' - -TIMEOUT = 30 -INTERVAL = 10 - -REASON = 'Because....' -ignore_lst = ('test') - - -def fetch(path, t='GET'): - url = 'http{}://{}:{}/'.format(PLEX_SSL, PLEX_HOST, PLEX_PORT) - - headers = {'X-Plex-Token': PLEX_TOKEN, - 'Accept': 'application/json', - 'X-Plex-Provides': 'controller', - 'X-Plex-Platform': platform.uname()[0], - 'X-Plex-Platform-Version': platform.uname()[2], - 'X-Plex-Product': 'Plexpy script', - 'X-Plex-Version': '0.9.5', - 'X-Plex-Device': platform.platform(), - 'X-Plex-Client-Identifier': str(hex(getnode())) - } - - try: - if t == 'GET': - r = requests.get(url + path, headers=headers, verify=False) - elif t == 'POST': - r = requests.post(url + path, headers=headers, verify=False) - elif t == 'DELETE': - r = requests.delete(url + path, headers=headers, verify=False) - - if r and len(r.content): # incase it dont return anything - return r.json() - else: - return r.content - - except Exception as e: - print e - - -def kill_stream(sessionId, message, xtime, ntime, user, title, sessionKey): - headers = {'X-Plex-Token': PLEX_TOKEN} - params = {'sessionId': sessionId, - 'reason': message} - - response = fetch('status/sessions') - - if response['MediaContainer']['Video']: - for video in response['MediaContainer']['Video']: - part = video['Media'][0]['Part'][0] - if video['sessionKey'] == sessionKey: - if xtime == ntime and video['Player']['state'] == 'paused' and part['decision'] == 'transcode': - sys.stdout.write("Killing {user}'s paused stream of {title}".format(user=user, title=title)) - requests.get('http{}://{}:{}/status/sessions/terminate'.format(PLEX_SSL, PLEX_HOST, PLEX_PORT), - headers=headers, params=params) - return ntime - elif video['Player']['state'] in ('playing', 'buffering'): - sys.stdout.write("{user}'s stream of {title} is now {state}". - format(user=user, title=title, state=video['Player']['state'])) - return None - else: - return xtime - else: - return None - - -def find_sessionID(response): - - sessions = [] - for video in response['MediaContainer']['Video']: - part = video['Media'][0]['Part'][0] - if video['sessionKey'] == sys.argv[1] and video['Player']['state'] == 'paused' \ - and part['decision'] == 'transcode': - sess_id = video['Session']['id'] - user = video['User']['title'] - sess_key = video['sessionKey'] - title = (video['grandparentTitle'] + ' - ' if video['type'] == 'episode' else '') + video['title'] - title = unicodedata.normalize('NFKD', title).encode('ascii', 'ignore').translate(None,"'") - sessions.append((sess_id, user, title, sess_key)) - - else: - pass - - print(sessions) - for session in sessions: - if session[1] not in ignore_lst: - return session - else: - print("{}'s stream of {} is ignored.".format(session[1], session[2])) - return None - - -if __name__ == '__main__': - - startupinfo = None - if os.name == 'nt': - startupinfo = subprocess.STARTUPINFO() - startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW - - response = fetch('status/sessions') - - fileDir = os.path.dirname(os.path.realpath(__file__)) - - try: - if find_sessionID(response): - stream_info = find_sessionID(response) - file_name = "{}.py".format(stream_info[0]) - full_path = os.path.join(fileDir, file_name) - file = "from time import sleep\n" \ - "import sys, os\n" \ - "from {script} import kill_stream \n" \ - "message = '{REASON}'\n" \ - "sessionID = os.path.basename(sys.argv[0])[:-3]\n" \ - "x = 0\n" \ - "n = {ntime}\n" \ - "try:\n" \ - " while x < n and x is not None:\n" \ - " sleep({xtime})\n" \ - " x += kill_stream(sessionID, message, {xtime}, n, '{user}', '{title}', '{sess_key}')\n" \ - " kill_stream(sessionID, message, {ntime}, n, '{user}', '{title}', '{sess_key}')\n" \ - " os.remove(sys.argv[0])\n" \ - "except TypeError as e:\n" \ - " os.remove(sys.argv[0])".format(script=os.path.basename(__file__)[:-3], - ntime=TIMEOUT, xtime=INTERVAL, REASON=REASON, - user=stream_info[1], title=stream_info[2], - sess_key=stream_info[3]) - - with open(full_path, "w+") as output: - output.write(file) - - subprocess.Popen([sys.executable, full_path], startupinfo=startupinfo) - exit(0) - - except TypeError as e: - print(e) - pass diff --git a/archive/notify_geomail.py b/archive/notify_geomail.py deleted file mode 100644 index 758b112..0000000 --- a/archive/notify_geomail.py +++ /dev/null @@ -1,198 +0,0 @@ -# 1. Install the requests module for python. -# pip install requests -# 2. Add script arguments in PlexPy. The following script arguments are available by default. More can be added below. -# -ip {ip_address} -us {user} -med {media_type} -tt {title} -pf {platform} -pl {player} -da {datestamp} -ti {timestamp} - -import argparse -import requests -import sys - - -## EDIT THESE SETTINGS ## - -PLEXPY_APIKEY = 'XXXXX' # Your PlexPy API key -PLEXPY_URL = 'http://localhost:8181/' # Your PlexPy URL -AGENT_ID = 10 # The notification agent ID for PlexPy -# 10 Email -# 15 Scripts -# 17 Browser - -# Replace LAN IP addresses that start with the LAN_SUBNET with a WAN IP address -# to retrieve geolocation data. Leave REPLACEMENT_WAN_IP blank for no replacement. -LAN_SUBNET = ('192.168') -REPLACEMENT_WAN_IP = '' - -# The notification subject and body -# - Use "{p.argument}" for script arguments -# - Use "{g.value}" for geolocation data -# - Use "{u.value}" for user data -SUBJECT_TEXT = "PlexPy Notification" -BODY_TEXT = """\ - - - -

Hi!
-
Poster unavailable {p.user} has watched {p.media_type}:{p.title}
-
On {p.platform}[{p.player}] in {g.city}, {g.country}.
-
At {p.timestamp} on {p.datestamp}.
-
IP address: {p.ip_address}
-
User email is: {u.email}
-
TEst area Data:{uip.data}
-

- - -""" - -## CODE BELOW ## - -##Geo Space## -class GeoData(object): - def __init__(self, data=None): - data = data or {} - self.continent = data.get('continent', 'N/A') - self.country = data.get('country', 'N/A') - self.region = data.get('region', 'N/A') - self.city = data.get('city', 'N/A') - self.postal_code = data.get('postal_code', 'N/A') - self.timezone = data.get('timezone', 'N/A') - self.latitude = data.get('latitude', 'N/A') - self.longitude = data.get('longitude', 'N/A') - self.accuracy = data.get('accuracy', 'N/A') - -##USER Space## -class UserEmail(object): - def __init__(self, data=None): - data = data or {} - self.email = data.get('email', 'N/A') - self.user_id = data.get('user_id', 'N/A') - self.user_thumb = data.get('user_thumb', 'N/A') - -##API Space## -def get_geoip_info(ip_address=''): - # Get the geo IP lookup from PlexPy - payload = {'apikey': PLEXPY_APIKEY, - 'cmd': 'get_geoip_lookup', - 'ip_address': ip_address} - - try: - r = requests.get(PLEXPY_URL.rstrip('/') + '/api/v2', params=payload) - response = r.json() - - if response['response']['result'] == 'success': - data = response['response']['data'] - if data.get('error'): - raise Exception(data['error']) - else: - sys.stdout.write("Successfully retrieved geolocation data.") - return GeoData(data=data) - else: - raise Exception(response['response']['message']) - except Exception as e: - sys.stderr.write("PlexPy API 'get_geoip_lookup' request failed: {0}.".format(e)) - return GeoData() - - -def get_user_email(user_id=''): - # Get the user email from PlexPy - payload = {'apikey': PLEXPY_APIKEY, - 'cmd': 'get_user', - 'user_id': user_id} - - try: - r = requests.get(PLEXPY_URL.rstrip('/') + '/api/v2', params=payload) - response = r.json() - - if response['response']['result'] == 'success': - data = response['response']['data'] - if data.get('error'): - raise Exception(data['error']) - else: - sys.stdout.write("Successfully retrieved user email data.") - return UserEmail(data=data) - else: - raise Exception(response['response']['message']) - except Exception as e: - sys.stderr.write("PlexPy API 'get_user' request failed: {0}.".format(e)) - return UserEmail() - -def send_notification(arguments=None, geodata=None, useremail=None, user_address=None): - # Format notification text - try: - subject = SUBJECT_TEXT.format(p=arguments, g=geodata, u=useremail) - body = BODY_TEXT.format(p=arguments, g=geodata, u=useremail) - except LookupError as e: - sys.stderr.write("Unable to substitute '{0}' in the notification subject or body".format(e)) - return None - # Send the notification through PlexPy - payload = {'apikey': PLEXPY_APIKEY, - 'cmd': 'notify', - 'agent_id': AGENT_ID, - 'subject': subject, - 'body': body} - - try: - r = requests.post(PLEXPY_URL.rstrip('/') + '/api/v2', params=payload) - response = r.json() - - if response['response']['result'] == 'success': - sys.stdout.write("Successfully sent PlexPy notification.") - else: - raise Exception(response['response']['message']) - except Exception as e: - sys.stderr.write("PlexPy API 'notify' request failed: {0}.".format(e)) - return None - -if __name__ == '__main__': - # Parse arguments from PlexPy - parser = argparse.ArgumentParser() - - parser.add_argument('-ip', '--ip_address', action='store', default='', - help='The IP address of the stream') - parser.add_argument('-us', '--user', action='store', default='', - help='Username of the person watching the stream') - parser.add_argument('-uid', '--user_id', action='store', default='', - help='User_ID of the person watching the stream') - parser.add_argument('-med', '--media_type', action='store', default='', - help='The media type of the stream') - parser.add_argument('-tt', '--title', action='store', default='', - help='The title of the media') - parser.add_argument('-pf', '--platform', action='store', default='', - help='The platform of the stream') - parser.add_argument('-pl', '--player', action='store', default='', - help='The player of the stream') - parser.add_argument('-da', '--datestamp', action='store', default='', - help='The date of the stream') - parser.add_argument('-ti', '--timestamp', action='store', default='', - help='The time of the stream') - parser.add_argument('-sn', '--show_name', action='store', default='', - help='The name of the TV show') - parser.add_argument('-ena', '--episode_name', action='store', default='', - help='The name of the episode') - parser.add_argument('-ssn', '--season_num', action='store', default='', - help='The season number of the TV show') - parser.add_argument('-enu', '--episode_num', action='store', default='', - help='The episode number of the TV show') - parser.add_argument('-srv', '--plex_server', action='store', default='', - help='The name of the Plex server') - parser.add_argument('-pos', '--poster', action='store', default='', - help='The poster url') - parser.add_argument('-sum', '--summary', action='store', default='', - help='The summary of the TV show') - parser.add_argument('-lbn', '--library_name', action='store', default='', - help='The name of the TV show') - - p = parser.parse_args() - - # Check to make sure there is an IP address before proceeding - if p.ip_address: - if p.ip_address.startswith(LAN_SUBNET) and REPLACEMENT_WAN_IP: - ip_address = REPLACEMENT_WAN_IP - else: - ip_address = p.ip_address - - g = get_geoip_info(ip_address=ip_address) - u = get_user_email(user_id=p.user_id) - send_notification(arguments=p, geodata=g, useremail=u) - - else: - sys.stdout.write("No IP address passed from PlexPy.")