· 6 years ago · Feb 24, 2020, 08:18 PM
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3
4"""
5Find what was added TFRAME ago and not watched using Tautulli.
6"""
7
8import requests
9import sys
10import time
11import os
12
13TFRAME = 2.628e+6 # ~ 2 months in seconds
14TODAY = time.time()
15
16
17# ## EDIT THESE SETTINGS ##
18TAUTULLI_APIKEY = '<myapikey.' # Your Tautulli API key
19TAUTULLI_URL = '<myurl>' # Your Tautulli URL
20LIBRARY_NAMES = ['Movies'] # Name of libraries you want to check.
21
22
23class LIBINFO(object):
24 def __init__(self, data=None):
25 d = data or {}
26 self.added_at = d['added_at']
27 self.parent_rating_key = d['parent_rating_key']
28 self.play_count = d['play_count']
29 self.title = d['title']
30 self.rating_key = d['rating_key']
31 self.media_type = d['media_type']
32
33
34class METAINFO(object):
35 def __init__(self, data=None):
36 d = data or {}
37 self.added_at = d['added_at']
38 self.parent_rating_key = d['parent_rating_key']
39 self.title = d['title']
40 self.rating_key = d['rating_key']
41 self.media_type = d['media_type']
42 self.grandparent_title = d['grandparent_title']
43 media_info = d['media_info'][0]
44 parts = media_info['parts'][0]
45 self.file_size = parts['file_size']
46 self.file = parts['file']
47
48
49def get_new_rating_keys(rating_key, media_type):
50 # Get a list of new rating keys for the PMS of all of the item's parent/children.
51 payload = {'apikey': TAUTULLI_APIKEY,
52 'cmd': 'get_new_rating_keys',
53 'rating_key': rating_key,
54 'media_type': media_type}
55
56 try:
57 r = requests.get(TAUTULLI_URL.rstrip('/') + '/api/v2', params=payload)
58 response = r.json()
59
60 res_data = response['response']['data']
61 show = res_data['0']
62 episode_lst = [episode['rating_key'] for _, season in show['children'].items() for _, episode in
63 season['children'].items()]
64
65 return episode_lst
66
67 except Exception as e:
68 sys.stderr.write("Tautulli API 'get_new_rating_keys' request failed: {0}.".format(e))
69
70
71def get_metadata(rating_key):
72 # Get the metadata for a media item.
73 payload = {'apikey': TAUTULLI_APIKEY,
74 'rating_key': rating_key,
75 'cmd': 'get_metadata',
76 'media_info': True}
77
78 try:
79 r = requests.get(TAUTULLI_URL.rstrip('/') + '/api/v2', params=payload)
80 response = r.json()
81
82 res_data = response['response']['data']
83 return METAINFO(data=res_data)
84
85 except Exception:
86 # sys.stderr.write("Tautulli API 'get_metadata' request failed: {0}.".format(e))
87 pass
88
89
90def get_library_media_info(section_id):
91 # Get the data on the Tautulli media info tables.
92 payload = {'apikey': TAUTULLI_APIKEY,
93 'section_id': section_id,
94 'cmd': 'get_library_media_info',
95 'length': 10000}
96
97 try:
98 r = requests.get(TAUTULLI_URL.rstrip('/') + '/api/v2', params=payload)
99 response = r.json()
100 res_data = response['response']['data']['data']
101 return [LIBINFO(data=d) for d in res_data if d['play_count'] is None and (TODAY - int(d['added_at'])) > TFRAME]
102
103 except Exception as e:
104 sys.stderr.write("Tautulli API 'get_library_media_info' request failed: {0}.".format(e))
105
106
107def get_libraries_table():
108 # Get the data on the Tautulli libraries table.
109 payload = {'apikey': TAUTULLI_APIKEY,
110 'cmd': 'get_libraries_table'}
111
112 try:
113 r = requests.get(TAUTULLI_URL.rstrip('/') + '/api/v2', params=payload)
114 print(r.status_code)
115 response = r.json()
116 print(r.status_code) # this line
117 res_data = response['response']['data']['data']
118 return [d['section_id'] for d in res_data if d['section_name'] in LIBRARY_NAMES]
119
120 except Exception as e:
121 sys.stderr.write("Tautulli API 'get_libraries_table' request failed: {0}.".format(e))
122
123
124def delete_files(tmp_lst):
125 del_file = raw_input('Delete all unwatched files? (yes/no)').lower()
126 if del_file.startswith('y'):
127 for x in tmp_lst:
128 print("Removing {}".format(x))
129 os.remove(x)
130 else:
131 print('Ok. doing nothing.')
132
133
134show_lst = []
135path_lst = []
136print("what is happening!!!!") # here
137
138glt = [lib for lib in get_libraries_table()]
139
140for i in glt:
141 try:
142 gglm = get_library_media_info(i)
143 for x in gglm:
144 try:
145 if x.media_type in ['show', 'episode']:
146 # Need to find TV shows rating_key for episode.
147 show_lst += get_new_rating_keys(x.rating_key, x.media_type)
148 else:
149 # Find movie rating_key.
150 show_lst += [int(x.rating_key)]
151 except Exception as e:
152 print("Rating_key failed: {e}").format(e=e)
153
154 except Exception as e:
155 print("Library media info failed: {e}").format(e=e)
156
157# Remove reverse sort if you want the oldest keys first.
158for i in sorted(show_lst, reverse=True):
159 try:
160 x = get_metadata(str(i))
161 added = time.ctime(float(x.added_at))
162 if x.grandparent_title == '' or x.media_type == 'movie':
163 # Movies
164 print(u"{x.title} ({x.rating_key}) was added {when} and has not been "
165 u"watched. \n File location: {x.file}".format(x=x, when=added))
166 else:
167 # Shows
168 print(u"{x.grandparent_title}: {x.title} ({x.rating_key}) was added {when} and has "
169 u"not been watched. \n File location: {x.file}".format(x=x, when=added))
170 path_lst += [x.file]
171
172 except Exception as e:
173 print("Metadata failed. Likely end of range: {e}").format(e=e)
174
175
176delete_files(path_lst)