Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update to make Sonarr source of truth for resolution/file naming #59

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion app/config.yml.template
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@ sonarr:
port: 8989 # sonarr default port
apikey: 12341234
ssl: false
path: "" # Path as defined by library directory for Sonarr
localpath: "/sonarr_root" # Path to Sonarr library as seen by local system
# basedir: '/sonarr' # if you have sonarr running with a basedir set (e.g. behind a proxy)
# version: v4 # if running v4 beta, allows the v3 api endpoints
version: v4 # if running v4 beta or current v3, allows the v3 api endpoints

ytdl:
# For information on format refer to https://github.com/ytdl-org/youtube-dl#format-selection
Expand Down
85 changes: 80 additions & 5 deletions app/sonarr_youtubedl.py
100644 → 100755
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#!/usr/bin/env python3

import requests
import urllib.parse
import yt_dlp
Expand Down Expand Up @@ -88,6 +90,72 @@ def __init__(self):
except Exception:
sys.exit("Error with series config.yml values.")

# Path munging
self.path = ""
self.localpath = "/sonarr_root"

try:
self.path = cfg['sonarr']['path']
self.localpath = cfg['sonarr']['localpath']
except Exception:
pass
# sys.exit("Error with sonarr config.yml values.")

res = self.get_formats()
self.update_formats(res)
logger.debug("Using number Style: %s Folder: %s" % (self.numberStyle,self.seasonFormat))

def update_formats(self,res):
"""Update Sonarr formats to python formats"""
for key in ['seasonFolderFormat', 'numberStyle']:
original = res[key]
if re.search(":",original):
temp = original
temp = temp[temp.find(':'):temp.find('}')]
length = len(temp)-1
rep = ":0"+str(length)+"d"
newval = original.replace(temp,rep)
res[key] = newval
self.seasonFormat = res['seasonFolderFormat']
self.numberStyle = res['numberStyle']

def get_formats(self):
"""Return the naming formats from Sonarr"""
logger.debug('Get formats')
res = self.request_get("{}/{}/config/naming".format(
self.base_url,
self.sonarr_api_version)
)
return res.json()

def get_quality(self, id):
"""Return the Quality Profile from Sonarr"""
logger.debug('Get Quality')
res = self.request_get("{}/{}/qualityprofile/{}".format(
self.base_url,
self.sonarr_api_version,
id)
)
return res.json()

def get_resolution_max_formats(self, quality_ids):
"""Return dictionary of formats based upon max resolution for quality_ids set"""
res_dict = {}
trans_resolution = {480: 640, 720: 1280, 1080: 1920, 2160: 3840}

for id in sorted(quality_ids):
res = self.get_quality(id)
res_max = 0
for qual in res['items']:
if qual['allowed'] == True:
if 'quality' not in qual.keys():
continue
resolution = qual['quality']['resolution']
res_max = max(res_max,resolution)
res_key = trans_resolution[res_max]
res_dict[id] = "bestvideo[width<={}]+bestaudio/best[width<={}]".format(res_key,res_key)
return res_dict

def get_episodes_by_series_id(self, series_id):
"""Returns all episodes for the given series"""
logger.debug('Begin call Sonarr for all episodes for series_id: {}'.format(series_id))
Expand Down Expand Up @@ -224,6 +292,7 @@ def filterseries(self):

def getseriesepisodes(self, series):
needed = []
quality_ids = set()
for ser in series[:]:
episodes = self.get_episodes_by_series_id(ser['id'])
for eps in episodes[:]:
Expand All @@ -244,6 +313,7 @@ def getseriesepisodes(self, series):
replace = ser['sonarr_regex_replace']
eps['title'] = re.sub(match, replace, eps['title'])
needed.append(eps)
quality_ids.add(ser['qualityProfileId'])
continue
if len(episodes) == 0:
logger.info('{0} no episodes needed'.format(ser['title']))
Expand All @@ -259,6 +329,7 @@ def getseriesepisodes(self, series):
ser['title'],
e['title']
))
self.ytdl_quality = self.get_resolution_max_formats(quality_ids)
return needed

def appendcookie(self, ytdlopts, cookies=None):
Expand Down Expand Up @@ -363,15 +434,19 @@ def download(self, series, episodes):
found, dlurl = self.ytsearch(ydleps, url)
if found:
logger.info(" {}: Found - {}:".format(e + 1, eps['title']))
season_dir = self.seasonFormat.format(season=eps['seasonNumber'])
number = self.numberStyle.format(season=eps['seasonNumber'],episode=eps['episodeNumber'])
logger.debug("Profile: %s Using format: %s" % (ser['qualityProfileId'],
self.ytdl_quality[ser['qualityProfileId']]))
ytdl_format_options = {
'format': self.ytdl_format,
'format': self.ytdl_quality[ser['qualityProfileId']],
'quiet': True,
'merge-output-format': 'mp4',
'outtmpl': '/sonarr_root{0}/Season {1}/{2} - S{1}E{3} - {4} WEBDL.%(ext)s'.format(
ser['path'],
eps['seasonNumber'],
'outtmpl': '/{0}/{1}/{2} - {3} - {4} WEBDL.%(ext)s'.format(
ser['path'].replace(self.path,self.localpath),
season_dir,
ser['title'],
eps['episodeNumber'],
number,
eps['title']
),
'progress_hooks': [ytdl_hooks],
Expand Down
8 changes: 4 additions & 4 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
requests==2.28.2
yt-dlp==2023.1.6
pyyaml==6.0
schedule==1.1.0
requests>=2.28.2
yt-dlp>=2023.1.6
pyyaml>=6.0
schedule>=1.1.0