Skip to content

Commit

Permalink
Massive style cleanup
Browse files Browse the repository at this point in the history
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`
  • Loading branch information
Arcanemagus committed Jun 21, 2019
1 parent ca5f4fb commit 2be0e37
Show file tree
Hide file tree
Showing 57 changed files with 807 additions and 610 deletions.
116 changes: 62 additions & 54 deletions fun/playlist_manager.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Description: Create and share playlists based on Most Popular TV/Movies from Tautulli
and Aired this day in history.
Expand Down Expand Up @@ -43,7 +46,7 @@
Example:
Use with cron or task to schedule runs
Create Aired Today Playlist from Movies and TV Shows libraries for admin user
python playlist_manager.py --jbop historyToday --libraries Movies "TV Shows" --action add
Expand All @@ -61,29 +64,29 @@
Create 10 Most Popular Movies (60 days) Playlist and share to users bob and Black Twin
python playlist_manager.py --jbop popularMovies --action add --users bob "Black Twin" --days 60 --top 10
Show 5 Most Popular TV Shows (30 days) Playlist
python playlist_manager.py --jbop popularTv --action show
Show all users current playlists
python playlist_manager.py --action show --allUsers
Share existing admin Playlists "My Custom Playlist" and "Another Playlist" with all users
python playlist_manager.py --action share --allUsers --playlists "My Custom Playlist" "Another Playlist"
Search and Filter;
metadata_field_name = title, summary, etc.
--search {metadata_field_name}=value
search through metadata field for existence of value.
--search {metadata_field_name}=value1,value2,*
search through metadata field for existence of values.
*comma separated for AND (value1 AND value2 AND *)
Excluding;
--user becomes excluded if --allUsers is set
Expand All @@ -106,14 +109,14 @@
from collections import Counter
from plexapi.server import PlexServer, CONFIG

### EDIT SETTINGS ###
# ### EDIT SETTINGS ###

PLEX_URL = ''
PLEX_TOKEN = ''
TAUTULLI_URL = ''
TAUTULLI_APIKEY = ''

## CODE BELOW ##
# ## CODE BELOW ##

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


def actions():
"""
add - create new playlist for admin or users
Expand All @@ -172,7 +176,7 @@ def selectors():
'custom': '{custom} Playlist',
'random': '{count} Random {libraries} Playlist'
}

return selections


Expand Down Expand Up @@ -203,7 +207,7 @@ def exclusions(all_true, select, all_items):
for x in select:
all_items.remove(x)
output = all_items

elif isinstance(all_items, dict):
output = {}
if all_true and not select:
Expand All @@ -216,7 +220,7 @@ def exclusions(all_true, select, all_items):
for key, value in all_items.items():
if value not in select:
output[key] = value

return output


Expand All @@ -226,7 +230,7 @@ def get_home_stats(time_range, stats_count):
'cmd': 'get_home_stats',
'time_range': time_range,
'stats_count': stats_count,
'stats_type': 0} # stats_type = plays
'stats_type': 0} # stats_type = plays

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

# todo-me return object
except Exception as e:
except Exception:
# print(e)
return


def multi_filter_search(keyword_dict, library, search_eps=None):
"""Allowing for multiple filter or search values
Parameters
----------
keyword_dict: dict
Expand Down Expand Up @@ -318,17 +322,18 @@ def multi_filter_search(keyword_dict, library, search_eps=None):
for episode in show.episodes(**{key: values}):
ep_lst += [episode.ratingKey]
multi_lst += ep_lst

else:
multi_lst += [item.ratingKey for item in library.all(**{key: values})]
counts = Counter(multi_lst)
# Use amount of keywords to check that all keywords were found in results
search_lst = [id for id in multi_lst if counts[id] >= keyword_count]

return list(set(search_lst))


def get_content(libraries, jbop, filters=None, search=None, limit=None):
"""Get all movies or episodes from LIBRARY_NAME
"""Get all movies or episodes from LIBRARY_NAME.
Parameters
----------
Expand All @@ -342,6 +347,7 @@ def get_content(libraries, jbop, filters=None, search=None, limit=None):
list
Sorted list of Movie and episodes that
aired on today's date.
"""
child_lst = []
filter_lst = []
Expand Down Expand Up @@ -378,7 +384,7 @@ def get_content(libraries, jbop, filters=None, search=None, limit=None):
child_lst += filter_lst
if keywords and filters:
child_lst += list(set(filter_lst) & set(search_lst))

elif library_type == 'show':
# Decisions to stack filter and search
if keywords:
Expand All @@ -402,17 +408,17 @@ def get_content(libraries, jbop, filters=None, search=None, limit=None):
for episode in show.episodes():
filter_lst += [episode.ratingKey]
child_lst += filter_lst

if keywords and filters:
child_lst += list(set(filter_lst) & set(search_lst))
else:
pass
# Keep only results found from both search and filters
if keywords and filters:
child_lst = list(set(i for i in child_lst if child_lst.count(i) > 1))

play_lst = child_lst

else:
for library in libraries.keys():
plex_library = plex.library.sectionByID(library)
Expand Down Expand Up @@ -440,7 +446,7 @@ def get_content(libraries, jbop, filters=None, search=None, limit=None):
# Sort by original air date, oldest first
# todo-me move sorting and add more sorting options
aired_lst = sorted(child_lst, key=operator.itemgetter(1))

# Remove date used for sorting
play_lst = [x[0] for x in aired_lst]
else:
Expand Down Expand Up @@ -474,7 +480,7 @@ def build_playlist(jbop, libraries=None, days=None, top=None, filters=None, sear
for stat in home_stats:
if stat['stat_id'] in ['popular_tv', 'popular_movies']:
keys_list += [x['rating_key'] for x in stat['rows'] if
str(x['section_id']) in libraries.keys()]
str(x['section_id']) in libraries.keys()]
else:
try:
keys_list = get_content(libraries, jbop, filters, search, limit)
Expand Down Expand Up @@ -525,11 +531,12 @@ def show_playlist(playlist_title, playlist_keys):
title = unicodedata.normalize('NFKD', title).encode('ascii', 'ignore').translate(None, "'")
playlist_list.append(title)

print(u"Contents of Playlist {title}:\n{playlist}".format(title=playlist_title,
playlist=', '.join(playlist_list)))
print(u"Contents of Playlist {title}:\n{playlist}".format(
title=playlist_title,
playlist=', '.join(playlist_list)))
exit()


def create_playlist(playlist_title, playlist_keys, server, user):
"""
Parameters
Expand All @@ -552,13 +559,13 @@ def create_playlist(playlist_title, playlist_keys, server, user):
playlist_list.append(episode)
else:
playlist_list.append(plex_obj)
except Exception as e:
except Exception:
try:
obj = plex.fetchItem(key)
print("{} may not have permission to this title: {}".format(user, obj.title))
# print("Error: {}".format(e))
pass
except Exception as e:
except Exception:
print('Rating Key: {}, may have been deleted or moved.'.format(key))
# print("Error: {}".format(e))

Expand All @@ -578,7 +585,7 @@ def delete_playlist(playlist_dict, title):
"""
server = playlist_dict['server']
user = playlist_dict['user']

try:
# todo-me this needs improvement
for playlist in server.playlists():
Expand All @@ -595,14 +602,14 @@ def delete_playlist(playlist_dict, title):
print("...Deleted Playlist: {playlist.title} for '{user}'."
.format(playlist=playlist, user=user))

except:
except Exception:
# print("Playlist not found on '{user}' account".format(user=user))
pass


def create_title(jbop, libraries, days, filters, search, limit):
"""
Parameters
----------
jbop: str
Expand Down Expand Up @@ -672,9 +679,9 @@ def create_title(jbop, libraries, days, filters, search, limit):


if __name__ == "__main__":

parser = argparse.ArgumentParser(description="Create, share, and clean Playlists for users.",
formatter_class = argparse.RawTextHelpFormatter)
parser = argparse.ArgumentParser(
description="Create, share, and clean Playlists for users.",
formatter_class=argparse.RawTextHelpFormatter)
# todo-me use parser grouping instead of choices for action and jbop?
parser.add_argument('--jbop', choices=selectors().keys(), metavar='',
help='Playlist selector.\n'
Expand Down Expand Up @@ -715,7 +722,7 @@ def create_title(jbop, libraries, days, filters, search, limit):
parser.add_argument('--search', action='append', type=lambda kv: kv.split("="),
help='Search non-filtered metadata fields for keywords '
'in title, summary, etc.')

opts = parser.parse_args()

title = ''
Expand All @@ -739,7 +746,7 @@ def create_title(jbop, libraries, days, filters, search, limit):
# If filter key used more than once than consider filtering values with OR statement
if filter_count > 1:
filters_lst = []

filters = dict(opts.filter)
for k, v in filters.items():
# If comma separated filter then consider filtering values with AND statement
Expand All @@ -756,10 +763,10 @@ def create_title(jbop, libraries, days, filters, search, limit):

# Defining libraries
libraries = exclusions(opts.allLibraries, opts.libraries, sections_dict)

# Defining selected playlists
selected_playlists = exclusions(opts.allPlaylists, opts.playlists, playlist_lst)

# Create user server objects
if users:
for user in users:
Expand All @@ -776,12 +783,13 @@ def create_title(jbop, libraries, days, filters, search, limit):
'user': user,
'user_selected': user_selected,
'all_playlists': all_playlists})

if opts.self or not users:
playlist_dict['data'].append({'server': plex,
'user': 'admin',
'user_selected': selected_playlists,
'all_playlists': playlist_lst})
playlist_dict['data'].append({
'server': plex,
'user': 'admin',
'user_selected': selected_playlists,
'all_playlists': playlist_lst})

if not opts.jbop and opts.action == 'show':
print("Displaying the user's playlist(s)...")
Expand All @@ -790,7 +798,7 @@ def create_title(jbop, libraries, days, filters, search, limit):
playlists = data['all_playlists']
print("{}'s current playlist(s): {}".format(user, ', '.join(playlists)))
exit()

if libraries:
title = create_title(opts.jbop, libraries, opts.days, filters, search, opts.limit)
keys_list = build_playlist(opts.jbop, libraries, opts.days, opts.top, filters, search, opts.limit)
Expand All @@ -801,18 +809,18 @@ def create_title(jbop, libraries, days, filters, search, limit):
for data in playlist_dict['data']:
titles = data['user_selected']
delete_playlist(data, titles)

# Check if limit exist and if it's greater than the pulled list of rating keys
if opts.limit and len(keys_list) > int(opts.limit):
if opts.jbop == 'random':
keys_list = random.sample((keys_list), opts.limit)
else:
keys_list = keys_list[:opts.limit]

# Setting custom name if provided
if opts.name:
title = opts.name

if opts.jbop and opts.action == 'show':
show_playlist(title, keys_list)

Expand All @@ -823,7 +831,7 @@ def create_title(jbop, libraries, days, filters, search, limit):
print('Creating playlist(s)...')
for data in playlist_dict['data']:
create_playlist(title, keys_list, data['server'], data['user'])

if opts.action == 'add':
print('Creating playlist(s)...')
for data in playlist_dict['data']:
Expand Down
Loading

0 comments on commit 2be0e37

Please sign in to comment.