def webhook_sonarr(): try: if request.json['eventType'] == 'Test': aprint('Received TEST webhook', 'WEBHOOK.MAIN') return HTTPResponse(status=200) if not request.json: error = { 'error': 'Request JSON not correct', 'code': 10, } return HTTPResponse(status=500, body=error) webhook_request = request.json episodes = webhook_request['episodes'] except: error = { 'error': 'Request JSON not correct', 'code': 10, } return HTTPResponse(status=500, body=error) for episode in episodes: episode_data = { 'SERIES': webhook_request['series']['title'], 'SEASON': str(episode['seasonNumber']).zfill(2), 'EPISODE': str(episode['episodeNumber']).zfill(2), 'TITLE': episode['title'], 'QUALITY': episode.get('quality', 'Unknown') } msg = '{SERIES} - {SEASON}x{EPISODE} - {TITLE} | {QUALITY}'.format( SERIES=episode_data['SERIES'], SEASON=episode_data['SEASON'], EPISODE=episode_data['EPISODE'], TITLE=episode_data['TITLE'], QUALITY=episode_data['QUALITY']) new_show = Show(series=episode_data['SERIES'], season=episode_data['SEASON'], episode=episode_data['EPISODE'], title=episode_data['TITLE'], quality=episode_data['QUALITY'], timestamp=datetime.datetime.now(current_tz)) new_show.save() aprint(msg, 'WEBHOOK.TV') return HTTPResponse(status=200)
def webhook_radarr(): try: if request.json['eventType'] == 'Test': aprint('Received TEST webhook', 'WEBHOOK.MAIN') return HTTPResponse(status=200) if not request.json: error = { 'error': 'Request JSON not correct', 'code': 10, } return HTTPResponse(status=500, body=error) webhook_request = request.json movie = webhook_request['remoteMovie'] except: error = { 'error': 'Request JSON not correct', 'code': 10, } return HTTPResponse(status=500, body=error) movie_data = { 'TITLE': movie['title'], 'YEAR': movie['year'], 'QUALITY': webhook_request['movieFile']['quality'] if 'movieFile' in webhook_request else 'Unknown', 'IMDB': movie['imdbId'] } msg = '{TITLE} ({YEAR}) | {QUALITY}'.format(TITLE=movie_data['TITLE'], YEAR=movie_data['YEAR'], QUALITY=movie_data['QUALITY']) new_movie = Movie(title=movie_data['TITLE'], year=movie_data['YEAR'], quality=movie_data['QUALITY'], imdb=movie_data['IMDB'], timestamp=datetime.datetime.now(current_tz)) new_movie.save() aprint(msg, 'WEBHOOK.MOVIE') return HTTPResponse(status=200)
def webhook_lidarr(): try: if request.json['eventType'] == 'Test': aprint('Received TEST webhook', 'WEBHOOK.MAIN') return HTTPResponse(status=200) if not request.json: error = { 'error': 'Request JSON not correct', 'code': 10, } return HTTPResponse(status=500, body=error) # pprint.pprint(request.json) webhook_request = request.json artist = webhook_request['artist']['name'] tracks = webhook_request['tracks'] except Exception as e: error = { 'error': 'Request JSON not correct', 'code': 10, 'stack_trace': str(e) } return HTTPResponse(status=500, body=error) for track in tracks: track_data = { 'ARTIST': artist, 'TITLE': track['title'], 'TRACK_NUMBER': track['trackNumber'], 'QUALITY': track['quality'] } msg = '{ARTIST} - {TITLE} ({TRACK_NUMBER}) | {QUALITY}'.format( ARTIST=track_data['ARTIST'], TITLE=track_data['TITLE'], TRACK_NUMBER=track_data['TRACK_NUMBER'], QUALITY=track_data['QUALITY']) new_track = Track(artist=track_data['ARTIST'], title=track_data['TITLE'], tracknumber=track_data['TRACK_NUMBER'], quality=track_data['QUALITY'], timestamp=datetime.datetime.now(current_tz)) new_track.save() aprint(msg, 'WEBHOOK.MUSIC') return HTTPResponse(status=200)
def send_tg_message(): aprint('Preparing the notification for Telegram...', 'NOTIFICATOR') tv_n, tv_msg = create_shows_msg() mo_n, mo_msg = create_movies_msg() tk_n, tk_msg = create_tracks_msg() msg = tv_msg + mo_msg + tk_msg if msg == '': return quiet = False if len(msg) < 1: aprint('Nothing to notify') return if len(msg) > 4000: msg = CONFIG['custom_too_long_message'].format(N_TV=tv_n, N_MOVIE=mo_n, N_TRACK=tk_n) hour = int(datetime.datetime.now(current_tz).hour) if hour >= int(CONFIG['start_quiet']) or hour <= int(CONFIG['end_quiet']): quiet = True msg = CONFIG['custom_quiet_mode_message'] + '\n\n' + msg TG_URL = 'https://api.telegram.org/bot{BOT_TOKEN}/sendMessage?chat_id={TG_CHAT_ID}&disable_web_page_preview=true&parse_mode=Markdown{QUIET}&text={MSG}' TG_URL = TG_URL.format(BOT_TOKEN=CONFIG['telegram_bot_token'], TG_CHAT_ID=CONFIG['telegram_chat_id'], QUIET='&disable_notification=true' if quiet else '', MSG=urllib.parse.quote_plus(msg)) aprint( 'Sending notification to Telegram - No. of TV Series: {} - No. of Movies: {} - No. of Tracks: {}' .format(tv_n, mo_n, tk_n), 'NOTIFICATOR') requests.get(TG_URL)
def db_init(): tables = db.get_tables() if 'movie' not in tables: aprint('`Movie` table not found in db, adding...', 'WEBHOOK.MAIN') db.create_tables([Movie]) if 'show' not in tables: aprint('`Show` table not found in db, adding...', 'WEBHOOK.MAIN') db.create_tables([Show]) if 'track' not in tables: aprint('`Track` table not found in db, adding...', 'WEBHOOK.MAIN') db.create_tables([Track])
def send_messages(): if CONFIG['telegram_bot_token']: aprint('Telegram is enabled.', 'NOTIFICATOR') send_tg_message() if CONFIG['discord_webhook']: aprint('Discord is enabled.', 'NOTIFICATOR') send_discord_message() try: db_cleanup() except: aprint( 'There was an error cleaning the database. Please contact support.', 'NOTIFICATOR')
def send_discord_message(): aprint('Preparing the notification for Discord...', 'NOTIFICATOR') tv_n, tv_msg = create_shows_msg() mo_n, mo_msg = create_movies_msg() tk_n, tk_msg = create_tracks_msg() msg = tv_msg + mo_msg + tk_msg if msg == '': return if len(msg) < 1: aprint('Nothing to notify') return if len(msg) > 2000: msg = CONFIG['custom_too_long_message'].format(N_TV=tv_n, N_MOVIE=mo_n, N_TRACK=tk_n) DISCORD_URL = CONFIG['discord_webhook'] if 'slack' not in DISCORD_URL: DISCORD_URL = DISCORD_URL + '/slack' cond = {'text': msg} aprint( 'Sending notification to Discord - No. of TV Series: {} - No. of Movies: {} - No. of Tracks: {}' .format(tv_n, mo_n, tk_n), 'NOTIFICATOR') requests.post(DISCORD_URL, data=cond)
def db_cleanup(): # Movie cleanup aprint('Cleaning up movies...', 'NOTIFICATOR') movies = Movie.select().order_by(Movie.title) n_movies = len(movies) for movie in movies: deletion = Movie.delete().where(Movie.imdb == movie.imdb, Movie.quality == movie.quality) deletion.execute() aprint('Deleted {} movies.'.format(n_movies), 'NOTIFICATOR') # TV cleanup aprint('Cleaning up tv shows...', 'NOTIFICATOR') episodes = Show.select().order_by(Show.series).order_by( Show.season).order_by(Show.episode) n_episodes = len(episodes) for episode in episodes: deletion = Show.delete().where(Show.series == episode.series, Show.season == episode.season, Show.episode == episode.episode) deletion.execute() aprint('Deleted {} episodes.'.format(n_episodes), 'NOTIFICATOR') # Tracks cleanup aprint('Cleaning up tracks...', 'NOTIFICATOR') tracks = Track.select().order_by(Track.artist).order_by(Track.tracknumber) n_tracks = len(tracks) for track in tracks: deletion = Track.delete().where(Track.artist == track.artist, Track.title == track.title, Track.tracknumber == track.tracknumber, Track.quality == track.quality) deletion.execute() aprint('Deleted {} tracks.'.format(n_tracks), 'NOTIFICATOR')
from utils import aprint, DATA_PATH config_file = Path(DATA_PATH + '/config.yml') def get_datetime(datetime_str): return datetime.datetime.strptime(datetime_str, '%Y-%m-%d %H:%M:%S.%f%z') def get_hours_min(datetime_obj): return datetime_obj.strftime('%H:%M') while True: if not config_file.is_file(): aprint('Waiting 5 seconds for config file generation', 'NOTIFICATOR') time.sleep(500) break with open(DATA_PATH + '/config.yml', 'r') as opened: CONFIG = yaml.load(opened, Loader=yaml.SafeLoader) aprint('Starting Informrr notificator...', 'NOTIFICATOR') current_tz = timezone(CONFIG['timezone']) def create_shows_msg(): msg = '*Shows*\n\n{SHOWS}\n\n\n' episodes = Show.select().order_by(Show.series).order_by( Show.season).order_by(Show.episode)
msg = '{ARTIST} - {TITLE} ({TRACK_NUMBER}) | {QUALITY}'.format( ARTIST=track_data['ARTIST'], TITLE=track_data['TITLE'], TRACK_NUMBER=track_data['TRACK_NUMBER'], QUALITY=track_data['QUALITY']) new_track = Track(artist=track_data['ARTIST'], title=track_data['TITLE'], tracknumber=track_data['TRACK_NUMBER'], quality=track_data['QUALITY'], timestamp=datetime.datetime.now(current_tz)) new_track.save() aprint(msg, 'WEBHOOK.MUSIC') return HTTPResponse(status=200) app.install(CorsPlugin(origins=['*'])) if __name__ == '__main__': aprint('Starting Informrr server on port 5445...', 'WEBHOOK.MAIN') aprint( 'Listening on endpoint /{KEY}/sonarr'.format(KEY=CONFIG['safe_key']), 'WEBHOOK.MAIN') aprint( 'Listening on endpoint /{KEY}/radarr'.format(KEY=CONFIG['safe_key']), 'WEBHOOK.MAIN') aprint( 'Listening on endpoint /{KEY}/lidarr'.format(KEY=CONFIG['safe_key']), 'WEBHOOK.MAIN') from waitress import serve serve(app, listen='*:5445', _quiet=True)