From bf037f1573ad7f991d5b4d949726b7d5b4ec305c Mon Sep 17 00:00:00 2001 From: morpheus65535 Date: Tue, 3 Aug 2021 16:32:53 -0400 Subject: [PATCH] Added plex webhooks endpoint to API to search for subtitles on media.play and media.resume events. --- bazarr/api.py | 66 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/bazarr/api.py b/bazarr/api.py index ee78227ab..4d9ec796b 100644 --- a/bazarr/api.py +++ b/bazarr/api.py @@ -17,6 +17,8 @@ import hashlib import apprise import gc from peewee import fn, Value +import requests +from bs4 import BeautifulSoup as bso from get_args import args from config import settings, base_url, save_settings, get_settings @@ -2064,6 +2066,68 @@ class BrowseRadarrFS(Resource): return jsonify(data) +class WebHooksPlex(Resource): + @authenticate + def post(self): + json_webhook = request.form.get('payload') + parsed_json_webhook = json.loads(json_webhook) + + event = parsed_json_webhook['event'] + if event not in ['media.play', 'media.resume']: + return '', 204 + + media_type = parsed_json_webhook['Metadata']['type'] + + if media_type == 'episode': + season = parsed_json_webhook['Metadata']['parentIndex'] + episode = parsed_json_webhook['Metadata']['index'] + else: + season = episode = None + + ids = [] + for item in parsed_json_webhook['Metadata']['Guid']: + splitted_id = item['id'].split('://') + if len(splitted_id) == 2: + ids.append({splitted_id[0]: splitted_id[1]}) + if not ids: + return '', 404 + + if media_type == 'episode': + try: + episode_imdb_id = [x['imdb'] for x in ids if 'imdb' in x][0] + r = requests.get('https://imdb.com/title/{}'.format(episode_imdb_id), + headers={"User-Agent": os.environ["SZ_USER_AGENT"]}) + soup = bso(r.content, "html.parser") + series_imdb_id = soup.find('a', {'class': re.compile(r'SeriesParentLink__ParentTextLink')})['href'].split('/')[2] + except: + return '', 404 + else: + sonarrEpisodeId = TableEpisodes.select(TableEpisodes.sonarrEpisodeId) \ + .join(TableShows, on=(TableEpisodes.sonarrSeriesId == TableShows.sonarrSeriesId)) \ + .where(TableShows.imdbId == series_imdb_id, + TableEpisodes.season == season, + TableEpisodes.episode == episode) \ + .dicts() \ + .get() + + if sonarrEpisodeId: + episode_download_subtitles(no=sonarrEpisodeId['sonarrEpisodeId']) + else: + try: + movie_imdb_id = [x['imdb'] for x in ids if 'imdb' in x][0] + except: + return '', 404 + else: + radarrId = TableMovies.select(TableMovies.radarrId)\ + .where(TableMovies.imdbId == movie_imdb_id)\ + .dicts()\ + .get() + if radarrId: + movies_download_subtitles(no=radarrId['radarrId']) + + return '', 200 + + api.add_resource(Badges, '/badges') api.add_resource(Providers, '/providers') @@ -2105,3 +2169,5 @@ api.add_resource(HistoryStats, '/history/stats') api.add_resource(BrowseBazarrFS, '/files') api.add_resource(BrowseSonarrFS, '/files/sonarr') api.add_resource(BrowseRadarrFS, '/files/radarr') + +api.add_resource(WebHooksPlex, '/webhooks/plex')