This commit is contained in:
Gregory Salaun 2021-12-15 16:55:14 +01:00
parent 294a8e7edf
commit 8e0cc85a12
2 changed files with 32 additions and 122 deletions

View File

@ -2,9 +2,15 @@ from plexapi.server import PlexServer
from config.config import Config from config.config import Config
from models.movie import UpdatedMovie from models.movie import UpdatedMovie
from tmdbv3api import TMDb, Movie from tmdbv3api import TMDb, Movie
import os
from datetime import datetime as dt from datetime import datetime as dt
import yaml, os, urllib.request import yaml, os, urllib.request, logging
logging.basicConfig(filename='plexAutoCollectionUpdater.log', level=logging.INFO)
logger = logging.getLogger("CollectionUpdater")
ch = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
logger.addHandler(ch)
# Instantiate Tmdb object # Instantiate Tmdb object
tmdb = TMDb() tmdb = TMDb()
@ -17,11 +23,13 @@ token = Config.plexToken
plex = PlexServer(baseurl, token) plex = PlexServer(baseurl, token)
plexMoviesLibrary = plex.library.section('Movies') plexMoviesLibrary = plex.library.section('Movies')
plexMoviesLibrary = plexMoviesLibrary.search()
MoviesList = [] MoviesList = []
print(f":: {dt.now().strftime('%d-%m-%Y %H:%M:%S')} :: CollectionUpdater :: Retrieving Movies from Plex and Updating TMDb information...") logger.info(f"Retrieving {len(plexMoviesLibrary)} Movies from Plex and Updating TMDb information...")
for item in plexMoviesLibrary.search():
for item in plexMoviesLibrary:
movie = UpdatedMovie() movie = UpdatedMovie()
tmdbMovie = Movie() tmdbMovie = Movie()
@ -35,8 +43,9 @@ for item in plexMoviesLibrary.search():
# Search for the movie on TMDb # Search for the movie on TMDb
try: try:
tmdbMovieDetails = tmdbMovie.details(movie_id=movie.TMDbId) tmdbMovieDetails = tmdbMovie.details(movie_id=movie.TMDbId)
logger.debug(f'Getting TMDb details for {movie.PlexTitle}')
except: except:
print(f":: {dt.now().strftime('%d-%m-%Y %H:%M:%S')} :: CollectionUpdater :: Cannot get details of {movie.PlexTitle} from TMDb") logger.warning(f"CollectionUpdater :: Cannot get details of {movie.PlexTitle} from TMDb")
if tmdbMovieDetails['belongs_to_collection']: if tmdbMovieDetails['belongs_to_collection']:
movie.MovieTMDbCollectionName = tmdbMovieDetails['belongs_to_collection'].name[:len(tmdbMovieDetails['belongs_to_collection'].name) - 7] movie.MovieTMDbCollectionName = tmdbMovieDetails['belongs_to_collection'].name[:len(tmdbMovieDetails['belongs_to_collection'].name) - 7]
@ -47,8 +56,9 @@ for item in plexMoviesLibrary.search():
# Add movie to the list of Movies # Add movie to the list of Movies
if movie.MovieTMDbCollectionTMDbId: if movie.MovieTMDbCollectionTMDbId:
logger.info(f'Movie {movie.PlexTitle} has been added to Collection List')
MoviesList.append(movie) MoviesList.append(movie)
print(f":: {dt.now().strftime('%d-%m-%Y %H:%M:%S')} :: CollectionUpdater :: Retrieved Movies from Plex and Updated TMDb information for {len(MoviesList)} movies...") logger.info("Retrieved Movies from Plex and Updated TMDb information for {len(MoviesList)} movies...")
i = 0 i = 0
count = 0 count = 0
@ -60,17 +70,25 @@ while i < len(MoviesList):
if MoviesList[i].MovieTMDbCollectionTMDbId == movie.MovieTMDbCollectionTMDbId: if MoviesList[i].MovieTMDbCollectionTMDbId == movie.MovieTMDbCollectionTMDbId:
count += 1 count += 1
if count > 2: if count > 2:
logger.info(f"Keeping collection {MoviesList[i].MovieTMDbCollectionName} which contains 3 or more movies")
if not MoviesList[i].MovieTMDbCollectionTMDbId in ExistingCollectionId: if not MoviesList[i].MovieTMDbCollectionTMDbId in ExistingCollectionId:
ExistingCollectionId.append(MoviesList[i].MovieTMDbCollectionTMDbId) ExistingCollectionId.append(MoviesList[i].MovieTMDbCollectionTMDbId)
MovieListFinal.append(MoviesList[i]) MovieListFinal.append(MoviesList[i])
i += 1 i += 1
count = 0 count = 0
with open(Config.PlexAutoCollectionConfigFilePath, 'r') as f: logger.info(f"Found a total of {len(MovieListFinal)} collections, updating config file now !")
try:
currentYaml = yaml.safe_load(f) currentYaml = object()
except yaml.YAMLError as exc:
print(exc) try:
with open(Config.PlexAutoCollectionConfigFilePath, 'r') as f:
try:
currentYaml = yaml.safe_load(f)
except yaml.YAMLError as exc:
print(exc)
except:
logger.warning(f"Could not find the config file with path: {Config.PlexAutoCollectionConfigFilePath}")
currentYamlCollections = [] currentYamlCollections = []
@ -84,13 +102,13 @@ for collection in MovieListFinal:
currentYaml['collections'].update(new_coll) currentYaml['collections'].update(new_coll)
if currentYaml: if currentYaml:
print(f":: {dt.now().strftime('%d-%m-%Y %H:%M:%S')} :: CollectionUpdater :: Adding new collection: {collection.MovieTMDbCollectionName} to Yaml file...") logger.info(f"Adding new collection: {collection.MovieTMDbCollectionName} to Yaml file...")
with open(Config.PlexAutoCollectionConfigFilePath, 'w') as f: with open(Config.PlexAutoCollectionConfigFilePath, 'w') as f:
yaml.safe_dump(currentYaml, f) yaml.safe_dump(currentYaml, f)
if not os.path.exists(Config.PlexAutoCollectionConfigFileImagesPath + f"/{collection.MovieTMDbCollectionName}"): if not os.path.exists(Config.PlexAutoCollectionConfigFileImagesPath + f"/{collection.MovieTMDbCollectionName}"):
print(f":: {dt.now().strftime('%d-%m-%Y %H:%M:%S')} :: CollectionUpdater :: Download poster for new collection {collection.MovieTMDbCollectionName}...") logger.info(f"Download poster for new collection {collection.MovieTMDbCollectionName}...")
os.mkdir(Config.PlexAutoCollectionConfigFileImagesPath + f"/{collection.MovieTMDbCollectionName}") os.mkdir(Config.PlexAutoCollectionConfigFileImagesPath + f"/{collection.MovieTMDbCollectionName}")
urllib.request.urlretrieve(Config.tmdbImgUrl + f"{collection.MovieTMDbCollectionPosterPath}", Config.PlexAutoCollectionConfigFileImagesPath + f"/{collection.MovieTMDbCollectionName}/poster.jpeg") urllib.request.urlretrieve(Config.tmdbImgUrl + f"{collection.MovieTMDbCollectionPosterPath}", Config.PlexAutoCollectionConfigFileImagesPath + f"/{collection.MovieTMDbCollectionName}/poster.jpeg")
print(f":: {dt.now().strftime('%d-%m-%Y %H:%M:%S')} :: CollectionUpdater :: All steps are completed...") logger.info(f"All collections have been updated in plex...")

108
backup.py
View File

@ -1,108 +0,0 @@
from config.config import Config
from tmdbv3api import TMDb, Movie, Collection
from plexapi.server import PlexServer
from fuzzywuzzy import fuzz
from models.movie_collection import MovieCollection
from datetime import datetime as dt
import yaml, os, urllib.request
# Instantiate Tmdb object
tmdb = TMDb()
tmdb.api_key = Config.tmdbApiKey
tmdb.language = Config.tmdbLanguage
# Instantiate TMDb movie & collection object
tmdbMovie = Movie()
tmdbCollection = Collection()
# Connect to Plex Server
baseurl = Config.plexBaseUrl
token = Config.plexToken
plex = PlexServer(baseurl, token)
# Create empty lists
PlexMovieList = []
MatchingList = []
TMDbCollection = []
MovieCollectionFinal = []
# Retrieve the library Movies from Plex
print(f":: {dt.now().strftime('%d-%m-%Y %H:%M:%S')} :: CollectionUpdater :: Retrieving Movies section from Plex")
plexMoviesLibrary = plex.library.section('Movies')
print(f":: {dt.now().strftime('%d-%m-%Y %H:%M:%S')} :: CollectionUpdater :: Movies section from Plex retrieved")
print(f":: {dt.now().strftime('%d-%m-%Y %H:%M:%S')} :: CollectionUpdater :: Creating Movies list and Collection Available in Plex")
for movie in plexMoviesLibrary.search():
PlexMovieList.append(movie.title)
print(f":: {dt.now().strftime('%d-%m-%Y %H:%M:%S')} :: CollectionUpdater :: Lists created, found {len(PlexMovieList)} movies")
i = 0
length = len(PlexMovieList)
print(f":: {dt.now().strftime('%d-%m-%Y %H:%M:%S')} :: CollectionUpdater :: Comparing Movies in Plex to find similar movies...")
while i < length:
for movie in PlexMovieList:
print(f":: {dt.now().strftime('%d-%m-%Y %H:%M:%S')} :: CollectionUpdater :: Checking matching between {PlexMovieList[i]} and {movie}, score is: {fuzz.ratio(PlexMovieList[i], movie)}")
if 85 < fuzz.ratio(PlexMovieList[i], movie) < 100:
if PlexMovieList[i] not in MatchingList:
MatchingList.append(PlexMovieList[i])
i += 1
print(f":: {dt.now().strftime('%d-%m-%Y %H:%M:%S')} :: CollectionUpdater :: Comparison is finished...found {len(MatchingList)} similar movies")
print(f":: {dt.now().strftime('%d-%m-%Y %H:%M:%S')} :: CollectionUpdater :: Searching TMDb for movies in the Matching List")
for movie in MatchingList:
movieSearch = tmdbMovie.search(movie)
movieId = movieSearch[0].id
movieDetails = tmdbMovie.details(movie_id=movieId)
if movieDetails.belongs_to_collection is not None:
collectionId = movieDetails.belongs_to_collection
if collectionId.id not in TMDbCollection:
TMDbCollection.append(collectionId.id)
for id in TMDbCollection:
MovieCollectionFinal.append(tmdbCollection.details(id))
MovieCollectionList = []
for movie in MovieCollectionFinal:
coll = MovieCollection()
nameLength = len(movie)
coll.collectionTitle = movie.name[:nameLength - 13]
coll.collectionId = movie.id
coll.collectionImgPath = movie.poster_path
MovieCollectionList.append(coll)
print(f":: {dt.now().strftime('%d-%m-%Y %H:%M:%S')} :: CollectionUpdater :: Checking and Updating Yaml File...")
with open(Config.PlexAutoCollectionConfigFilePath, 'r') as f:
try:
currentYaml = yaml.safe_load(f)
except yaml.YAMLError as exc:
print(exc)
currentYamlCollections = []
for movies in currentYaml['collections']:
currentYamlCollections.append(movies)
for collection in MovieCollectionList:
if collection.collectionTitle not in currentYamlCollections:
with open(Config.PlexAutoCollectionConfigFilePath, 'r') as f:
new_coll = {f'{collection.collectionTitle}': {'sync_mode': 'sync', 'tmdb_collection': collection.collectionId, 'tmdb_summary': collection.collectionId}}
currentYaml['collections'].update(new_coll)
if currentYaml:
print(f":: {dt.now().strftime('%d-%m-%Y %H:%M:%S')} :: CollectionUpdater :: Adding new collection: {collection.collectionTitle} to Yaml file...")
with open(Config.PlexAutoCollectionConfigFilePath, 'w') as f:
yaml.safe_dump(currentYaml, f)
if not os.path.exists(Config.PlexAutoCollectionConfigFileImagesPath + f"/{collection.collectionTitle}"):
print(f":: {dt.now().strftime('%d-%m-%Y %H:%M:%S')} :: CollectionUpdater :: Download poster for new collection {collection.collectionTitle}...")
os.mkdir(Config.PlexAutoCollectionConfigFileImagesPath + f"/{collection.collectionTitle}")
urllib.request.urlretrieve(Config.tmdbImgUrl + f"{collection.collectionImgPath}", Config.PlexAutoCollectionConfigFileImagesPath + f"/{collection.collectionTitle}/poster.jpeg")
print(f":: {dt.now().strftime('%d-%m-%Y %H:%M:%S')} :: CollectionUpdater :: All steps are completed...")