diff options
Diffstat (limited to 'app/commands')
-rw-r--r-- | app/commands/movie_show_response_newaccount.py | 72 | ||||
-rw-r--r-- | app/commands/number_response_request.py | 59 | ||||
-rw-r--r-- | app/commands/request.py | 49 | ||||
-rw-r--r-- | app/commands/status.py | 76 |
4 files changed, 256 insertions, 0 deletions
diff --git a/app/commands/movie_show_response_newaccount.py b/app/commands/movie_show_response_newaccount.py new file mode 100644 index 0000000..6922560 --- /dev/null +++ b/app/commands/movie_show_response_newaccount.py @@ -0,0 +1,72 @@ +import datetime +import requests +import random +import string +import sqlite3 + +import initialize_variables +from create_message import create_message + + +def movie_show_response_newaccount(from_number, message): + if from_number not in initialize_variables.temp_new_account_requests.keys(): + create_message(from_number, "There is no current request that you can decide on. It might be that your /newaccount command timed out due since you took too long to response. Please try again. If this issue persists, please contact Parker.") + return + + # If its been 5 minutes since prompt was sent, alert user of timed out request + if (datetime.datetime.now() - initialize_variables.temp_new_account_requests[from_number]).total_seconds() / 60 > 5: + del initialize_variables.temp_new_account_requests[from_number] + create_message(from_number, "You waited too long and therefore your request has timed out.\n\nPlease try again by re-running the /newaccount command. If this issue persists, please contact Parker.") + return + + if message.strip().lower() == "show": + active_time = 24 + + elif message.strip().lower() == "movie": + active_time = 4 + + else: + create_message(from_number, "You did not enter a valid response. Please re-send the /newaccount command and try again. If you believe this is an error, please contact Parker.") + return + + # Otherwise, all checks have been completed + username = ''.join(random.choices(string.ascii_lowercase + string.digits, k=5)) + password = ''.join(random.choices(string.ascii_lowercase + string.digits, k=15)) + + deletion_time = datetime.datetime.now() + datetime.timedelta(hours=active_time) + # Create new Jellyfin account + request_1 = requests.post(f'{initialize_variables.jellyfin_url}/Users/New', headers=initialize_variables.jellyfin_headers, json={'Name': username, 'Password': password}) + if request_1.status_code != 200: + create_message(from_number, "Error creating Jellyfin account. Please try again. If the error persists, contact Parker.") + return + + user_id = request_1.json()['Id'] + # Get account policy and make edits + request_2 = requests.get(f'{initialize_variables.jellyfin_url}/Users/{user_id}', headers=initialize_variables.jellyfin_headers) + if request_2.status_code != 200: + create_message(from_number, "Error creating Jellyfin account. Please try again. If the error persists, contact Parker.") + return + + policy = request_2.json()['Policy'] + policy['SyncPlayAccess'] = 'JoinGroups' + policy['EnableContentDownloading'] = False + policy['InvalidLoginAttemptCount'] = 3 + policy['MaxActiveSessions'] = 1 + # Update user with new policy + request_3 = requests.post(f'{initialize_variables.jellyfin_url}/Users/{user_id}/Policy', headers=initialize_variables.jellyfin_headers, json=policy) + if request_3.status_code != 204: + create_message(from_number, "Error creating Jellyfin account. Please try again. If the error persists, contact Parker.") + return + + # Add information to the database + db = sqlite3.connect(initialize_variables.db_path) + cursor = db.cursor() + cursor.execute(''' + INSERT INTO jellyfin_accounts (user_id, deletion_time) + VALUES(?, ?) + ''', (user_id, deletion_time)) + db.commit() + db.close() + + create_message(from_number, f"Username: {username}\nPassword: {password}\n\nYour account will expire in {active_time} hours.") + return diff --git a/app/commands/number_response_request.py b/app/commands/number_response_request.py new file mode 100644 index 0000000..bb9958c --- /dev/null +++ b/app/commands/number_response_request.py @@ -0,0 +1,59 @@ +import datetime +import requests +import sqlite3 + +import initialize_variables +from create_message import create_message + + +def number_response_request(from_number, message): + if from_number not in initialize_variables.temp_movie_ids.keys(): + create_message(from_number, "There is no current request that you can decide on. It might be that your /request command timed out due since you took too long to response. Please try again. If this issue persists, please contact Parker.") + return + + # If its been 5 minutes since prompt was sent, alert user of timed out request + if (datetime.datetime.now() - initialize_variables.temp_movie_ids[from_number]['time']).total_seconds() / 60 > 5: + del initialize_variables.temp_movie_ids[from_number] + create_message(from_number, "You waited too long and therefore your request has timed out.\n\nPlease try again by re-running the /request command. If this issue persists, please contact Parker.") + return + + # Otherwise, all checks have been completed + create_message(from_number, "Just a moment while I add your movie to the library...") + movie_number = initialize_variables.numbers_responses[message.strip()] + try: + tmdb_id = initialize_variables.temp_movie_ids[from_number]['ids'][movie_number - 1] + except IndexError: + create_message(from_number, "You did not enter a valid number. Please re-send the /request command and try again. If you believe this is an error, please contact Parker.") + del initialize_variables.temp_movie_ids[from_number] + return + + data = requests.get(f'{initialize_variables.radarr_host_url}/api/v3/movie/lookup/tmdb?tmdbId={tmdb_id}', headers=initialize_variables.headers) + + data = data.json() + movie_title = data['title'] + # Change the qualityProfileId, monitored, and rootFolderPath values + data['qualityProfileId'] = initialize_variables.quality_profile_id + data['monitored'] = True + data['rootFolderPath'] = initialize_variables.root_folder_path + # Send data to Radarr API + response = requests.post(f'{initialize_variables.radarr_host_url}/api/v3/movie', headers=initialize_variables.headers, json=data) + data = response.json() + movie_id = data['id'] + # Send message to user alerting them that the movie was added to the library + create_message(from_number, f"🎉 {data['title']} has been added to the library!\n\nTo check up on the status of your movie(s) send /status - please wait at least 5 minutes before running this command in order to get an accurate time.") + + # After everything is completed, send Radarr a request to search indexers for new movie + requests.post(f'{initialize_variables.radarr_host_url}/api/v3/command', headers=initialize_variables.headers, json={'name': 'MoviesSearch', 'movieIds': [int(movie_id)]}) + + # Add the movie_id to the database so that users can check up on the status of their movie + db = sqlite3.connect(initialize_variables.db_path) + cursor = db.cursor() + cursor.execute(''' + INSERT INTO movies(from_number, movie_id, movie_title) + VALUES(?, ?, ?) + ''', (from_number, movie_id, movie_title)) + db.commit() + db.close() + + del initialize_variables.temp_movie_ids[from_number] + return
\ No newline at end of file diff --git a/app/commands/request.py b/app/commands/request.py new file mode 100644 index 0000000..316bd70 --- /dev/null +++ b/app/commands/request.py @@ -0,0 +1,49 @@ +import requests +import datetime + +import initialize_variables +from create_message import create_message + + +def request(from_number, message): + # If the user has already run the /request command, delete the entry + # from the temp_movie_ids dict so that they can run the command again + if from_number in initialize_variables.temp_movie_ids.keys(): + del initialize_variables.temp_movie_ids[from_number] + + # If the user did not include a movie title, alert them to do so + if len(message) <= 9: + create_message(from_number, "Please include the movie title after the /request command.\nEX: /request The Dark Knight") + return + + incoming_message = message.split(' ', 1)[1] + movie_request = incoming_message.replace(' ', '%20') + if movie_request.endswith("%20"): + movie_request = movie_request[:-3] + + # Send a request to the radarr API to get the movie info + response = requests.get(f'{initialize_variables.radarr_host_url}/api/v3/movie/lookup?term={movie_request}', headers=initialize_variables.headers) + + if len(response.json()) == 0: + create_message(from_number, "There were no results for that movie. Please make sure you typed the title correctly.") + return + # If the movie is already added to the library, return a message saying so. + if response.json()[0]['added'] != '0001-01-01T05:51:00Z': + create_message(from_number, "This movie is already added to the server.\n\nIf you believe this is an error, please contact Parker.") + return + + # Add top 3 results to a message + message = "" + for i in range(min(3, len(response.json()))): + message += f"{i+1}. {response.json()[i]['folder']}\n\n" + if from_number not in initialize_variables.temp_movie_ids.keys(): + initialize_variables.temp_movie_ids[from_number] = { + 'ids': [], + 'time': datetime.datetime.now() + } + initialize_variables.temp_movie_ids[from_number]['ids'].append(response.json()[i]['tmdbId']) + + message += "Reply with the number associated with the movie you want to download. EX: 1\n\nIf the movie you want is not on the list, make sure you typed the title exactly as it is spelt, or ask Parker to manually add the movie." + + create_message(from_number, message) + return
\ No newline at end of file diff --git a/app/commands/status.py b/app/commands/status.py new file mode 100644 index 0000000..acf9376 --- /dev/null +++ b/app/commands/status.py @@ -0,0 +1,76 @@ +import datetime +import sqlite3 +import requests +import humanize + +import initialize_variables +from create_message import create_message + + +def status(from_number): + # This returns a list of ALL movies being downloaded, but not all of them were + # requested by the user, so we need to filter out the ones that were not requested + response = requests.get(f'{initialize_variables.radarr_host_url}/api/v3/queue/', headers=initialize_variables.headers) + # Get all the movie_ids that were requested by the user + db = sqlite3.connect(initialize_variables.db_path) + cursor = db.cursor() + cursor.execute(''' + SELECT movie_id, movie_title FROM movies WHERE from_number = ? + ''', (from_number,)) + movie_info = cursor.fetchall() + db.close() + + movies = {} # movie_id: movie_title + for movie in movie_info: + movies[movie[0]] = movie[1] + + if len(movies) == 0: + create_message(from_number, "You have no movies being downloaded at the moment.\n\nIf you previously added a movie, it is likely that it has finished downloading. If you believe this is an error, please contact Parker.") + return + + message = "" + # Loop through the response from the radarr API and filter out the movies that were not requested by the user + for movie in response.json()['records']: + movie_id = str(movie['movieId']) + if movie_id in movies.keys(): + if movie['status'] == 'downloading': + # Humanize the time_left value + try: + time_left = humanize.precisedelta(datetime.datetime.strptime(movie['timeleft'], '%H:%M:%S') - datetime.datetime.strptime('00:00:00', '%H:%M:%S'), minimum_unit='seconds') + except ValueError: + # Sometimes movie downloads take a long time and include days in the time_left value + # This is formated as 1.00:00:00 + time_left = humanize.precisedelta(datetime.datetime.strptime(movie['timeleft'], '%d.%H:%M:%S') - datetime.datetime.strptime('00:00:00', '%H:%M:%S'), minimum_unit='seconds') + except KeyError: + time_left = 'Unknown' + + message += f"📥 {movies[movie_id]} - {time_left}\n" + else: + message += f"{movies[movie_id]} - {str(movie['status']).upper()}\n" + + # If the message is empty, that means the user has no movies being downloaded + # Or, no download was found for the movie they requested + if message == "": + # For all movie IDs within the database + for movie_id in movies.keys(): + response = requests.get(f'{initialize_variables.radarr_host_url}/api/v3/movie/{movie_id}', headers=initialize_variables.headers) + # This means that there is no current download, and no file has been found + # MOST likely means a download just wasn't found, so alert the user + data = response.json() + if data['hasFile'] == False: + message += f"{movies[movie_id]} - NOT FOUND\n\nThis means a download was not found for the movie(s), if this is a brand new movie that is likely the reason. If the movie has already been released on DVD/Blu-Ray, please contact Parker." + + # Send message with info about download to user, otherwise, the user has + # no movies being downloaded at the moment so alert them + if message != "": + create_message(from_number, message) + return + else: + create_message(from_number, "You have no movies being downloaded at the moment.\n\nIf you previously added a movie, it is likely that it has finished downloading. If you believe this is an error, please contact Parker.") + return + + # Otherwise, add another part to the message containing movie data + else: + message += "\n\nIf movies consistently show as 'WARNING' or 'QUEUED' or any other error over multiple hours, please contact Parker." + create_message(from_number, message) + return
\ No newline at end of file |