Skip to content

Commit 2be0e37

Browse files
committed
Massive style cleanup
Adds a basic `setup.cfg` file with configurations for flake8 and pylama, fixes some basic issues with essentially every file including: * Many, many, whitespace line cleanups * Several unused variables and imports * Missing coding and shabang lines * Minor style fixes to more closely align with PEP8 * Turn `print` into function calls for Python 2/3 compat * A few minor bugs * Things like using an undefined `i` in `stream_limiter_ban_email.py`
1 parent ca5f4fb commit 2be0e37

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

57 files changed

+807
-610
lines changed

fun/playlist_manager.py

Lines changed: 62 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
14
"""
25
Description: Create and share playlists based on Most Popular TV/Movies from Tautulli
36
and Aired this day in history.
@@ -43,7 +46,7 @@
4346
4447
Example:
4548
Use with cron or task to schedule runs
46-
49+
4750
Create Aired Today Playlist from Movies and TV Shows libraries for admin user
4851
python playlist_manager.py --jbop historyToday --libraries Movies "TV Shows" --action add
4952
@@ -61,29 +64,29 @@
6164
6265
Create 10 Most Popular Movies (60 days) Playlist and share to users bob and Black Twin
6366
python playlist_manager.py --jbop popularMovies --action add --users bob "Black Twin" --days 60 --top 10
64-
67+
6568
Show 5 Most Popular TV Shows (30 days) Playlist
6669
python playlist_manager.py --jbop popularTv --action show
67-
70+
6871
Show all users current playlists
6972
python playlist_manager.py --action show --allUsers
70-
73+
7174
Share existing admin Playlists "My Custom Playlist" and "Another Playlist" with all users
7275
python playlist_manager.py --action share --allUsers --playlists "My Custom Playlist" "Another Playlist"
73-
76+
7477
Search and Filter;
75-
78+
7679
metadata_field_name = title, summary, etc.
77-
80+
7881
--search {metadata_field_name}=value
7982
search through metadata field for existence of value.
80-
83+
8184
--search {metadata_field_name}=value1,value2,*
8285
search through metadata field for existence of values.
8386
*comma separated for AND (value1 AND value2 AND *)
84-
85-
86-
87+
88+
89+
8790
Excluding;
8891
8992
--user becomes excluded if --allUsers is set
@@ -106,14 +109,14 @@
106109
from collections import Counter
107110
from plexapi.server import PlexServer, CONFIG
108111

109-
### EDIT SETTINGS ###
112+
# ### EDIT SETTINGS ###
110113

111114
PLEX_URL = ''
112115
PLEX_TOKEN = ''
113116
TAUTULLI_URL = ''
114117
TAUTULLI_APIKEY = ''
115118

116-
## CODE BELOW ##
119+
# ## CODE BELOW ##
117120

118121
if not PLEX_URL:
119122
PLEX_URL = CONFIG.data['auth'].get('server_baseurl')
@@ -150,6 +153,7 @@
150153
today = datetime.datetime.now().date()
151154
weeknum = datetime.date(today.year, today.month, today.day).isocalendar()[1]
152155

156+
153157
def actions():
154158
"""
155159
add - create new playlist for admin or users
@@ -172,7 +176,7 @@ def selectors():
172176
'custom': '{custom} Playlist',
173177
'random': '{count} Random {libraries} Playlist'
174178
}
175-
179+
176180
return selections
177181

178182

@@ -203,7 +207,7 @@ def exclusions(all_true, select, all_items):
203207
for x in select:
204208
all_items.remove(x)
205209
output = all_items
206-
210+
207211
elif isinstance(all_items, dict):
208212
output = {}
209213
if all_true and not select:
@@ -216,7 +220,7 @@ def exclusions(all_true, select, all_items):
216220
for key, value in all_items.items():
217221
if value not in select:
218222
output[key] = value
219-
223+
220224
return output
221225

222226

@@ -226,7 +230,7 @@ def get_home_stats(time_range, stats_count):
226230
'cmd': 'get_home_stats',
227231
'time_range': time_range,
228232
'stats_count': stats_count,
229-
'stats_type': 0} # stats_type = plays
233+
'stats_type': 0} # stats_type = plays
230234

231235
try:
232236
r = requests.get(TAUTULLI_URL.rstrip('/') + '/api/v2', params=payload)
@@ -269,14 +273,14 @@ def sort_by_dates(video, date_type):
269273
return [[video.ratingKey] + [str(video.originallyAvailableAt)]]
270274

271275
# todo-me return object
272-
except Exception as e:
276+
except Exception:
273277
# print(e)
274278
return
275279

276280

277281
def multi_filter_search(keyword_dict, library, search_eps=None):
278282
"""Allowing for multiple filter or search values
279-
283+
280284
Parameters
281285
----------
282286
keyword_dict: dict
@@ -318,17 +322,18 @@ def multi_filter_search(keyword_dict, library, search_eps=None):
318322
for episode in show.episodes(**{key: values}):
319323
ep_lst += [episode.ratingKey]
320324
multi_lst += ep_lst
321-
325+
322326
else:
323327
multi_lst += [item.ratingKey for item in library.all(**{key: values})]
324328
counts = Counter(multi_lst)
325329
# Use amount of keywords to check that all keywords were found in results
326330
search_lst = [id for id in multi_lst if counts[id] >= keyword_count]
327-
331+
328332
return list(set(search_lst))
329333

334+
330335
def get_content(libraries, jbop, filters=None, search=None, limit=None):
331-
"""Get all movies or episodes from LIBRARY_NAME
336+
"""Get all movies or episodes from LIBRARY_NAME.
332337
333338
Parameters
334339
----------
@@ -342,6 +347,7 @@ def get_content(libraries, jbop, filters=None, search=None, limit=None):
342347
list
343348
Sorted list of Movie and episodes that
344349
aired on today's date.
350+
345351
"""
346352
child_lst = []
347353
filter_lst = []
@@ -378,7 +384,7 @@ def get_content(libraries, jbop, filters=None, search=None, limit=None):
378384
child_lst += filter_lst
379385
if keywords and filters:
380386
child_lst += list(set(filter_lst) & set(search_lst))
381-
387+
382388
elif library_type == 'show':
383389
# Decisions to stack filter and search
384390
if keywords:
@@ -402,17 +408,17 @@ def get_content(libraries, jbop, filters=None, search=None, limit=None):
402408
for episode in show.episodes():
403409
filter_lst += [episode.ratingKey]
404410
child_lst += filter_lst
405-
411+
406412
if keywords and filters:
407413
child_lst += list(set(filter_lst) & set(search_lst))
408414
else:
409415
pass
410416
# Keep only results found from both search and filters
411417
if keywords and filters:
412418
child_lst = list(set(i for i in child_lst if child_lst.count(i) > 1))
413-
419+
414420
play_lst = child_lst
415-
421+
416422
else:
417423
for library in libraries.keys():
418424
plex_library = plex.library.sectionByID(library)
@@ -440,7 +446,7 @@ def get_content(libraries, jbop, filters=None, search=None, limit=None):
440446
# Sort by original air date, oldest first
441447
# todo-me move sorting and add more sorting options
442448
aired_lst = sorted(child_lst, key=operator.itemgetter(1))
443-
449+
444450
# Remove date used for sorting
445451
play_lst = [x[0] for x in aired_lst]
446452
else:
@@ -474,7 +480,7 @@ def build_playlist(jbop, libraries=None, days=None, top=None, filters=None, sear
474480
for stat in home_stats:
475481
if stat['stat_id'] in ['popular_tv', 'popular_movies']:
476482
keys_list += [x['rating_key'] for x in stat['rows'] if
477-
str(x['section_id']) in libraries.keys()]
483+
str(x['section_id']) in libraries.keys()]
478484
else:
479485
try:
480486
keys_list = get_content(libraries, jbop, filters, search, limit)
@@ -525,11 +531,12 @@ def show_playlist(playlist_title, playlist_keys):
525531
title = unicodedata.normalize('NFKD', title).encode('ascii', 'ignore').translate(None, "'")
526532
playlist_list.append(title)
527533

528-
print(u"Contents of Playlist {title}:\n{playlist}".format(title=playlist_title,
529-
playlist=', '.join(playlist_list)))
534+
print(u"Contents of Playlist {title}:\n{playlist}".format(
535+
title=playlist_title,
536+
playlist=', '.join(playlist_list)))
530537
exit()
531-
532-
538+
539+
533540
def create_playlist(playlist_title, playlist_keys, server, user):
534541
"""
535542
Parameters
@@ -552,13 +559,13 @@ def create_playlist(playlist_title, playlist_keys, server, user):
552559
playlist_list.append(episode)
553560
else:
554561
playlist_list.append(plex_obj)
555-
except Exception as e:
562+
except Exception:
556563
try:
557564
obj = plex.fetchItem(key)
558565
print("{} may not have permission to this title: {}".format(user, obj.title))
559566
# print("Error: {}".format(e))
560567
pass
561-
except Exception as e:
568+
except Exception:
562569
print('Rating Key: {}, may have been deleted or moved.'.format(key))
563570
# print("Error: {}".format(e))
564571

@@ -578,7 +585,7 @@ def delete_playlist(playlist_dict, title):
578585
"""
579586
server = playlist_dict['server']
580587
user = playlist_dict['user']
581-
588+
582589
try:
583590
# todo-me this needs improvement
584591
for playlist in server.playlists():
@@ -595,14 +602,14 @@ def delete_playlist(playlist_dict, title):
595602
print("...Deleted Playlist: {playlist.title} for '{user}'."
596603
.format(playlist=playlist, user=user))
597604

598-
except:
605+
except Exception:
599606
# print("Playlist not found on '{user}' account".format(user=user))
600607
pass
601608

602609

603610
def create_title(jbop, libraries, days, filters, search, limit):
604611
"""
605-
612+
606613
Parameters
607614
----------
608615
jbop: str
@@ -672,9 +679,9 @@ def create_title(jbop, libraries, days, filters, search, limit):
672679

673680

674681
if __name__ == "__main__":
675-
676-
parser = argparse.ArgumentParser(description="Create, share, and clean Playlists for users.",
677-
formatter_class = argparse.RawTextHelpFormatter)
682+
parser = argparse.ArgumentParser(
683+
description="Create, share, and clean Playlists for users.",
684+
formatter_class=argparse.RawTextHelpFormatter)
678685
# todo-me use parser grouping instead of choices for action and jbop?
679686
parser.add_argument('--jbop', choices=selectors().keys(), metavar='',
680687
help='Playlist selector.\n'
@@ -715,7 +722,7 @@ def create_title(jbop, libraries, days, filters, search, limit):
715722
parser.add_argument('--search', action='append', type=lambda kv: kv.split("="),
716723
help='Search non-filtered metadata fields for keywords '
717724
'in title, summary, etc.')
718-
725+
719726
opts = parser.parse_args()
720727

721728
title = ''
@@ -739,7 +746,7 @@ def create_title(jbop, libraries, days, filters, search, limit):
739746
# If filter key used more than once than consider filtering values with OR statement
740747
if filter_count > 1:
741748
filters_lst = []
742-
749+
743750
filters = dict(opts.filter)
744751
for k, v in filters.items():
745752
# If comma separated filter then consider filtering values with AND statement
@@ -756,10 +763,10 @@ def create_title(jbop, libraries, days, filters, search, limit):
756763

757764
# Defining libraries
758765
libraries = exclusions(opts.allLibraries, opts.libraries, sections_dict)
759-
766+
760767
# Defining selected playlists
761768
selected_playlists = exclusions(opts.allPlaylists, opts.playlists, playlist_lst)
762-
769+
763770
# Create user server objects
764771
if users:
765772
for user in users:
@@ -776,12 +783,13 @@ def create_title(jbop, libraries, days, filters, search, limit):
776783
'user': user,
777784
'user_selected': user_selected,
778785
'all_playlists': all_playlists})
779-
786+
780787
if opts.self or not users:
781-
playlist_dict['data'].append({'server': plex,
782-
'user': 'admin',
783-
'user_selected': selected_playlists,
784-
'all_playlists': playlist_lst})
788+
playlist_dict['data'].append({
789+
'server': plex,
790+
'user': 'admin',
791+
'user_selected': selected_playlists,
792+
'all_playlists': playlist_lst})
785793

786794
if not opts.jbop and opts.action == 'show':
787795
print("Displaying the user's playlist(s)...")
@@ -790,7 +798,7 @@ def create_title(jbop, libraries, days, filters, search, limit):
790798
playlists = data['all_playlists']
791799
print("{}'s current playlist(s): {}".format(user, ', '.join(playlists)))
792800
exit()
793-
801+
794802
if libraries:
795803
title = create_title(opts.jbop, libraries, opts.days, filters, search, opts.limit)
796804
keys_list = build_playlist(opts.jbop, libraries, opts.days, opts.top, filters, search, opts.limit)
@@ -801,18 +809,18 @@ def create_title(jbop, libraries, days, filters, search, limit):
801809
for data in playlist_dict['data']:
802810
titles = data['user_selected']
803811
delete_playlist(data, titles)
804-
812+
805813
# Check if limit exist and if it's greater than the pulled list of rating keys
806814
if opts.limit and len(keys_list) > int(opts.limit):
807815
if opts.jbop == 'random':
808816
keys_list = random.sample((keys_list), opts.limit)
809817
else:
810818
keys_list = keys_list[:opts.limit]
811-
819+
812820
# Setting custom name if provided
813821
if opts.name:
814822
title = opts.name
815-
823+
816824
if opts.jbop and opts.action == 'show':
817825
show_playlist(title, keys_list)
818826

@@ -823,7 +831,7 @@ def create_title(jbop, libraries, days, filters, search, limit):
823831
print('Creating playlist(s)...')
824832
for data in playlist_dict['data']:
825833
create_playlist(title, keys_list, data['server'], data['user'])
826-
834+
827835
if opts.action == 'add':
828836
print('Creating playlist(s)...')
829837
for data in playlist_dict['data']:

0 commit comments

Comments
 (0)