Skip to content

Instantly share code, notes, and snippets.

@tobiasglen
Last active August 4, 2021 02:08
Show Gist options
  • Select an option

  • Save tobiasglen/888fbca35e17f6c603c90d7e480dc383 to your computer and use it in GitHub Desktop.

Select an option

Save tobiasglen/888fbca35e17f6c603c90d7e480dc383 to your computer and use it in GitHub Desktop.
Edit Emby 4K library items to include (4K) in the title | e.g. --> TV Show Title (4K)
import sys
import json
import logging
import requests
import argparse
from rich.progress import track
emby_base_url = 'https://emby.domain.com'
emby_api_key = 'fill_me_out'
emby_user_id = 'fill_me_out'
emby_4k_library_parent_id = 'fill_me_out'
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--dry', action='store_true', help="Print planned Emby title changes without actually changing anything")
parser.add_argument('-n', '--num', nargs=1, help="Specify how many items to update in Emby library (don't pass arg if you want to update all items)")
args = parser.parse_args()
# Set up logger
logging.basicConfig(filename='4k_title_fixed.log', level=logging.INFO, format='%(asctime)s | %(message)s')
headers = {
'accept': '*/*',
'Content-Type': 'application/json'
}
# Get a list of all TV Shows under the 4K tv library
all_items_in_library = requests.get(f'{emby_base_url}/emby/Items?ParentId={emby_4k_library_parent_id}&api_key={emby_api_key}').json()
total_item_count = 0
need_title_fix = {}
for content_title in all_items_in_library["Items"]:
total_item_count += 1 # update this var with the total number of items so we can calculate a percentage of items fixed
if not str(content_title["Name"]).endswith('(4K)'):
# If the title does not end with (4K) then we run the following code
content_emby_id = content_title['Id']
content_fixed_title = f'{str(content_title["Name"])} (4K)'
# Update the dict with Emby item ID & 'fixed' title we want
need_title_fix[content_emby_id] = content_fixed_title
# If the total num of results is 0 or the items need fixing is 0 we can exit here
if not bool(total_item_count) or not bool(len(need_title_fix)):
logging.info(msg='No items to update, Exiting now')
sys.exit('No items to update, Exiting now')
# Calculate percentage of items in library that would be updated
percentage_need_fix = len(need_title_fix) / total_item_count * 100
# Only if the --dry arg was passed we run the following code
if args.dry:
print(f"\n{'-' * 10} Fixed Titles {'-' * 10}")
# Loop through dict & show user what titles need to be updated
for idx, fixed_title in enumerate(need_title_fix.values()):
idx += 1 # (To start count from 1)
print(f'{idx}. {fixed_title}')
# Print some numbers after for loop completes
print(f'\nNumber of items in library: {total_item_count}')
print(f'{round(percentage_need_fix, 1)}% of the library would be updated\n')
sys.exit('To apply these changes to Emby, run the script again without the --dry arg')
# Only if the --dry arg wasn't passed then we log the changes to a .log file & update the item in Emby
for idx, (content_id, fixed_title) in enumerate(track(need_title_fix.items(), description='Fixing...')):
# If the user specified a limit of items to fix we check for that here
if args.num and int(args.num[0]) == idx:
logging.info(msg=f'User specified limit: {args.num[0]} was reached')
sys.exit(f'Quiting after reaching user specified limit: {args.num[0]} items')
# Get the metadata of the entire show/movie (we need to post the entire thing back after updating the title)
need_title_fix_request = requests.get(f"{emby_base_url}/emby/users/{emby_user_id}/items/{content_id}?api_key={emby_api_key}")
need_title_fix_response = need_title_fix_request.json()
# Make the changes (append (4K) to the existing title)
need_title_fix_response["Name"] = fixed_title
post_user_settings_payload = json.dumps(need_title_fix_response)
logging.info(msg=f'Fixed title: {fixed_title}')
# POST the entire thing back
update_title = requests.post(f"{emby_base_url}/emby/Items/{content_id}?api_key={emby_api_key}", data=post_user_settings_payload, headers=headers)
if not update_title.ok:
logging.error(msg=f'Emby response code not "ok": {update_title.status_code}')
logging.info(msg=f'Appended "(4K)" to {len(need_title_fix)} item{"s"[:len(need_title_fix) ^ 1]}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment