jellyfin-kodi/jellyfin_kodi/full_sync.py

704 lines
26 KiB
Python
Raw Normal View History

2018-09-06 08:36:32 +00:00
# -*- coding: utf-8 -*-
from __future__ import division, absolute_import, print_function, unicode_literals
2018-09-06 08:36:32 +00:00
##################################################################################################
from contextlib import contextmanager
2018-09-06 08:36:32 +00:00
import datetime
2024-06-11 05:10:57 +00:00
import xbmc
2018-09-06 08:36:32 +00:00
2021-10-10 18:38:25 +00:00
from . import downloader as server
from .objects import Movies, TVShows, MusicVideos, Music
from .database import Database, get_sync, save_sync, jellyfin_db
from .helper import translate, settings, window, progress, dialog, LazyLogger, xmls
from .helper.utils import get_screensaver, set_screensaver
from .helper.exceptions import LibraryException, PathValidationException
2018-09-06 08:36:32 +00:00
##################################################################################################
2020-04-19 01:05:59 +00:00
LOG = LazyLogger(__name__)
2018-09-06 08:36:32 +00:00
##################################################################################################
class FullSync(object):
2024-06-10 09:19:47 +00:00
"""This should be called like a context.
i.e. with FullSync('jellyfin') as sync:
sync.libraries()
"""
2018-09-06 08:36:32 +00:00
# Borg - multiple instances, shared state
_shared_state = {}
2018-09-06 08:36:32 +00:00
sync = None
running = False
2019-01-25 11:32:29 +00:00
screensaver = None
2018-09-06 08:36:32 +00:00
2019-01-25 15:30:30 +00:00
def __init__(self, library, server):
2024-06-10 09:19:47 +00:00
"""You can call all big syncing methods here.
Initial, update, repair, remove.
"""
self.__dict__ = self._shared_state
2019-01-25 15:30:30 +00:00
if self.running:
dialog("ok", "{jellyfin}", translate(33197))
2019-01-25 15:30:30 +00:00
raise Exception("Sync is already running.")
self.library = library
self.server = server
def __enter__(self):
2024-06-10 09:19:47 +00:00
"""Do everything we need before the sync"""
2019-01-25 15:30:30 +00:00
LOG.info("-->[ fullsync ]")
2019-01-25 11:32:29 +00:00
2024-06-10 09:19:47 +00:00
if not settings("dbSyncScreensaver.bool"):
2019-01-25 11:32:29 +00:00
2024-06-10 09:19:47 +00:00
xbmc.executebuiltin("InhibitIdleShutdown(true)")
2019-01-25 11:32:29 +00:00
self.screensaver = get_screensaver()
set_screensaver(value="")
2018-09-06 08:36:32 +00:00
2019-01-25 15:30:30 +00:00
self.running = True
2024-06-10 09:19:47 +00:00
window("jellyfin_sync.bool", True)
2019-01-25 15:30:30 +00:00
return self
2021-05-01 00:54:52 +00:00
def libraries(self, libraries=None, update=False):
2024-06-10 09:19:47 +00:00
"""Map the syncing process and start the sync. Ensure only one sync is running."""
self.direct_path = settings("useDirectPaths") == "1"
2019-01-25 15:30:30 +00:00
self.update_library = update
self.sync = get_sync()
2021-05-01 00:54:52 +00:00
if libraries:
# Can be a single ID or a comma separated list
2024-06-10 09:19:47 +00:00
libraries = libraries.split(",")
2021-05-01 00:54:52 +00:00
for library_id in libraries:
# Look up library in local Jellyfin database
library = self.get_library(library_id)
if library:
2024-06-10 09:19:47 +00:00
if library.media_type == "mixed":
self.sync["Libraries"].append("Mixed:%s" % library_id)
2021-05-01 00:54:52 +00:00
# Include boxsets library
libraries = self.get_libraries()
2024-06-10 09:19:47 +00:00
boxsets = [
row.view_id
for row in libraries
if row.media_type == "boxsets"
]
2021-05-01 00:54:52 +00:00
if boxsets:
2024-06-10 09:19:47 +00:00
self.sync["Libraries"].append("Boxsets:%s" % boxsets[0])
elif library.media_type == "movies":
self.sync["Libraries"].append(library_id)
2021-05-01 00:54:52 +00:00
# Include boxsets library
libraries = self.get_libraries()
2024-06-10 09:19:47 +00:00
boxsets = [
row.view_id
for row in libraries
if row.media_type == "boxsets"
]
2021-05-02 16:46:47 +00:00
# Verify we're only trying to sync boxsets once
2024-06-10 09:19:47 +00:00
if boxsets and boxsets[0] not in self.sync["Libraries"]:
self.sync["Libraries"].append("Boxsets:%s" % boxsets[0])
2021-05-01 00:54:52 +00:00
else:
# Only called if the library isn't already known about
2024-06-10 09:19:47 +00:00
self.sync["Libraries"].append(library_id)
else:
2024-06-10 09:19:47 +00:00
self.sync["Libraries"].append(library_id)
else:
2019-01-25 15:30:30 +00:00
self.mapping()
2024-06-10 09:19:47 +00:00
if not xmls.advanced_settings() and self.sync["Libraries"]:
2019-01-25 15:30:30 +00:00
self.start()
2018-09-06 08:36:32 +00:00
def get_libraries(self):
2024-06-10 09:19:47 +00:00
with Database("jellyfin") as jellyfindb:
return jellyfin_db.JellyfinDatabase(jellyfindb.cursor).get_views()
def get_library(self, library_id):
2024-06-10 09:19:47 +00:00
with Database("jellyfin") as jellyfindb:
return jellyfin_db.JellyfinDatabase(jellyfindb.cursor).get_view(library_id)
2018-09-06 08:36:32 +00:00
def mapping(self):
2024-06-10 09:19:47 +00:00
"""Load the mapping of the full sync.
This allows us to restore a previous sync.
"""
if self.sync["Libraries"]:
2018-09-06 08:36:32 +00:00
if not dialog("yesno", "{jellyfin}", translate(33102)):
2018-09-06 08:36:32 +00:00
if not dialog("yesno", "{jellyfin}", translate(33173)):
dialog("ok", "{jellyfin}", translate(33122))
2018-09-06 08:36:32 +00:00
raise LibraryException("ProgressStopped")
else:
2024-06-10 09:19:47 +00:00
self.sync["Libraries"] = []
self.sync["RestorePoint"] = {}
2018-09-06 08:36:32 +00:00
else:
LOG.info("generate full sync")
libraries = []
for library in self.get_libraries():
2024-06-10 09:19:47 +00:00
if library.media_type in (
"movies",
"tvshows",
"musicvideos",
"music",
"mixed",
):
libraries.append(
{
"Id": library.view_id,
"Name": library.view_name,
"Media": library.media_type,
}
)
2018-09-06 08:36:32 +00:00
libraries = self.select_libraries(libraries)
2024-06-10 09:19:47 +00:00
if [x["Media"] for x in libraries if x["Media"] in ("movies", "mixed")]:
self.sync["Libraries"].append("Boxsets:")
2018-09-06 08:36:32 +00:00
save_sync(self.sync)
2018-09-06 08:36:32 +00:00
def select_libraries(self, libraries):
2024-06-10 09:19:47 +00:00
"""Select all or certain libraries to be whitelisted."""
2018-09-06 08:36:32 +00:00
2024-06-10 09:19:47 +00:00
choices = [x["Name"] for x in libraries]
choices.insert(0, translate(33121))
selection = dialog("multi", translate(33120), choices)
2018-09-06 08:36:32 +00:00
if selection is None:
2024-06-10 09:19:47 +00:00
raise LibraryException("LibrarySelection")
2018-09-06 08:36:32 +00:00
elif not selection:
LOG.info("Nothing was selected.")
2018-09-23 08:03:15 +00:00
2024-06-10 09:19:47 +00:00
raise LibraryException("SyncLibraryLater")
2018-09-06 08:36:32 +00:00
if 0 in selection:
selection = list(range(1, len(libraries) + 1))
selected_libraries = []
for x in selection:
library = libraries[x - 1]
2024-06-10 09:19:47 +00:00
if library["Media"] != "mixed":
selected_libraries.append(library["Id"])
2018-09-06 08:36:32 +00:00
else:
2024-06-10 09:19:47 +00:00
selected_libraries.append("Mixed:%s" % library["Id"])
2018-09-06 08:36:32 +00:00
2024-06-10 09:19:47 +00:00
self.sync["Libraries"] = selected_libraries
2018-09-06 08:36:32 +00:00
return [libraries[x - 1] for x in selection]
def start(self):
2024-06-10 09:19:47 +00:00
"""Main sync process."""
LOG.info("starting sync with %s", self.sync["Libraries"])
2018-09-23 08:03:15 +00:00
save_sync(self.sync)
2018-09-06 08:36:32 +00:00
start_time = datetime.datetime.now()
2024-06-10 09:19:47 +00:00
for library in list(self.sync["Libraries"]):
2019-01-25 11:32:29 +00:00
self.process_library(library)
2024-06-10 09:19:47 +00:00
if (
not library.startswith("Boxsets:")
and library not in self.sync["Whitelist"]
):
self.sync["Whitelist"].append(library)
2018-09-06 08:36:32 +00:00
2024-06-10 09:19:47 +00:00
self.sync["Libraries"].pop(self.sync["Libraries"].index(library))
self.sync["RestorePoint"] = {}
2018-09-06 08:36:32 +00:00
elapsed = datetime.datetime.now() - start_time
2024-06-10 09:19:47 +00:00
settings("SyncInstallRunDone.bool", True)
2018-09-06 08:36:32 +00:00
self.library.save_last_sync()
save_sync(self.sync)
2024-06-10 09:19:47 +00:00
xbmc.executebuiltin("UpdateLibrary(video)")
dialog(
"notification",
heading="{jellyfin}",
message="%s %s" % (translate(33025), str(elapsed).split(".")[0]),
icon="{jellyfin}",
sound=False,
)
LOG.info("Full sync completed in: %s", str(elapsed).split(".")[0])
2018-09-06 08:36:32 +00:00
def process_library(self, library_id):
2024-06-10 09:19:47 +00:00
"""Add a library by its id. Create a node and a playlist whenever appropriate."""
2018-09-06 08:36:32 +00:00
media = {
2024-06-10 09:19:47 +00:00
"movies": self.movies,
"musicvideos": self.musicvideos,
"tvshows": self.tvshows,
"music": self.music,
2018-09-06 08:36:32 +00:00
}
try:
2024-06-10 09:19:47 +00:00
if library_id.startswith("Boxsets:"):
boxset_library = {}
2018-09-06 08:36:32 +00:00
# Initial library sync is 'Boxsets:'
# Refresh from the addon menu is 'Boxsets:Refresh'
# Incremental syncs are 'Boxsets:$library_id'
2024-06-10 09:19:47 +00:00
sync_id = library_id.split(":")[1]
2024-06-10 09:19:47 +00:00
if not sync_id or sync_id == "Refresh":
2020-12-27 16:36:03 +00:00
libraries = self.get_libraries()
else:
_lib = self.get_library(sync_id)
libraries = [_lib] if _lib else []
2020-08-02 22:50:57 +00:00
for entry in libraries:
2024-06-10 09:19:47 +00:00
if entry.media_type == "boxsets":
boxset_library = {"Id": entry.view_id, "Name": entry.view_name}
2020-08-02 22:50:57 +00:00
break
if boxset_library:
2024-06-10 09:19:47 +00:00
if sync_id == "Refresh":
2020-08-02 22:50:57 +00:00
self.refresh_boxsets(boxset_library)
else:
self.boxsets(boxset_library)
2018-09-06 08:36:32 +00:00
return
2024-06-10 09:19:47 +00:00
library = self.server.jellyfin.get_item(library_id.replace("Mixed:", ""))
2018-09-06 08:36:32 +00:00
2024-06-10 09:19:47 +00:00
if library_id.startswith("Mixed:"):
for mixed in ("movies", "tvshows"):
2018-09-06 08:36:32 +00:00
media[mixed](library)
2024-06-10 09:19:47 +00:00
self.sync["RestorePoint"] = {}
2018-09-06 08:36:32 +00:00
else:
2024-06-10 09:19:47 +00:00
if library["CollectionType"]:
settings("enableMusic.bool", True)
2018-09-06 08:36:32 +00:00
2024-06-10 09:19:47 +00:00
media[library["CollectionType"]](library)
2018-09-06 08:36:32 +00:00
except LibraryException as error:
2024-06-10 09:19:47 +00:00
if error.status == "StopCalled":
2018-09-06 08:36:32 +00:00
save_sync(self.sync)
raise
2020-07-31 21:45:54 +00:00
except PathValidationException:
raise
2018-09-06 08:36:32 +00:00
except Exception as error:
2020-07-31 21:45:54 +00:00
dialog("ok", "{jellyfin}", translate(33119))
2018-09-06 08:36:32 +00:00
2020-07-31 21:45:54 +00:00
LOG.error("full sync exited unexpectedly")
LOG.exception(error)
2020-07-31 21:45:54 +00:00
save_sync(self.sync)
2018-09-06 08:36:32 +00:00
raise
@contextmanager
def video_database_locks(self):
with self.library.database_lock:
with Database() as videodb:
2024-06-10 09:19:47 +00:00
with Database("jellyfin") as jellyfindb:
yield videodb, jellyfindb
2018-09-06 08:36:32 +00:00
@progress()
def movies(self, library, dialog):
2024-06-10 09:19:47 +00:00
"""Process movies from a single library."""
processed_ids = []
2019-01-25 15:30:30 +00:00
2024-06-10 09:19:47 +00:00
for items in server.get_items(
library["Id"], "Movie", False, self.sync["RestorePoint"].get("params")
):
with self.video_database_locks() as (videodb, jellyfindb):
2024-06-10 09:19:47 +00:00
obj = Movies(
self.server, jellyfindb, videodb, self.direct_path, library
)
self.sync["RestorePoint"] = items["RestorePoint"]
start_index = items["RestorePoint"]["params"]["StartIndex"]
for index, movie in enumerate(items["Items"]):
dialog.update(
int(
(
float(start_index + index)
/ float(items["TotalRecordCount"])
)
* 100
),
heading="%s: %s" % (translate("addon_name"), library["Name"]),
message=movie["Name"],
)
2020-08-02 21:00:34 +00:00
obj.movie(movie)
2024-06-10 09:19:47 +00:00
processed_ids.append(movie["Id"])
2018-09-06 08:36:32 +00:00
with self.video_database_locks() as (videodb, jellyfindb):
2020-08-02 21:00:34 +00:00
obj = Movies(self.server, jellyfindb, videodb, self.direct_path, library)
obj.item_ids = processed_ids
2018-09-06 08:36:32 +00:00
if self.update_library:
self.movies_compare(library, obj, jellyfindb)
def movies_compare(self, library, obj, jellyfinydb):
2024-06-10 09:19:47 +00:00
"""Compare entries from library to what's in the jellyfindb. Remove surplus"""
db = jellyfin_db.JellyfinDatabase(jellyfinydb.cursor)
2024-06-10 09:19:47 +00:00
items = db.get_item_by_media_folder(library["Id"])
current = obj.item_ids
for x in items:
2024-06-10 09:19:47 +00:00
if x[0] not in current and x[1] == "Movie":
obj.remove(x[0])
2018-09-06 08:36:32 +00:00
@progress()
def tvshows(self, library, dialog):
2024-06-10 09:19:47 +00:00
"""Process tvshows and episodes from a single library."""
processed_ids = []
2019-01-25 15:30:30 +00:00
2024-06-10 09:19:47 +00:00
for items in server.get_items(
library["Id"], "Series", False, self.sync["RestorePoint"].get("params")
):
with self.video_database_locks() as (videodb, jellyfindb):
2024-06-10 09:19:47 +00:00
obj = TVShows(
self.server, jellyfindb, videodb, self.direct_path, library, True
)
self.sync["RestorePoint"] = items["RestorePoint"]
start_index = items["RestorePoint"]["params"]["StartIndex"]
for index, show in enumerate(items["Items"]):
percent = int(
(float(start_index + index) / float(items["TotalRecordCount"]))
* 100
)
message = show["Name"]
dialog.update(
percent,
heading="%s: %s" % (translate("addon_name"), library["Name"]),
message=message,
)
2018-09-06 08:36:32 +00:00
2020-08-02 21:00:34 +00:00
if obj.tvshow(show) is not False:
2018-09-06 08:36:32 +00:00
2024-06-10 09:19:47 +00:00
for episodes in server.get_episode_by_show(show["Id"]):
for episode in episodes["Items"]:
if episode.get("Path"):
dialog.update(
percent,
message="%s/%s"
% (message, episode["Name"][:10]),
)
2022-04-03 00:21:09 +00:00
obj.episode(episode)
2024-06-10 09:19:47 +00:00
processed_ids.append(show["Id"])
with self.video_database_locks() as (videodb, jellyfindb):
2024-06-10 09:19:47 +00:00
obj = TVShows(
self.server, jellyfindb, videodb, self.direct_path, library, True
)
obj.item_ids = processed_ids
if self.update_library:
self.tvshows_compare(library, obj, jellyfindb)
def tvshows_compare(self, library, obj, jellyfindb):
2024-06-10 09:19:47 +00:00
"""Compare entries from library to what's in the jellyfindb. Remove surplus"""
db = jellyfin_db.JellyfinDatabase(jellyfindb.cursor)
2018-09-06 08:36:32 +00:00
2024-06-10 09:19:47 +00:00
items = db.get_item_by_media_folder(library["Id"])
for x in list(items):
items.extend(obj.get_child(x[0]))
current = obj.item_ids
2018-09-06 08:36:32 +00:00
for x in items:
2024-06-10 09:19:47 +00:00
if x[0] not in current and x[1] == "Series":
obj.remove(x[0])
2018-09-06 08:36:32 +00:00
@progress()
def musicvideos(self, library, dialog):
2024-06-10 09:19:47 +00:00
"""Process musicvideos from a single library."""
2020-02-27 02:05:38 +00:00
processed_ids = []
2019-01-25 15:30:30 +00:00
2024-06-10 09:19:47 +00:00
for items in server.get_items(
library["Id"], "MusicVideo", False, self.sync["RestorePoint"].get("params")
):
2018-09-06 08:36:32 +00:00
with self.video_database_locks() as (videodb, jellyfindb):
2024-06-10 09:19:47 +00:00
obj = MusicVideos(
self.server, jellyfindb, videodb, self.direct_path, library
)
self.sync["RestorePoint"] = items["RestorePoint"]
start_index = items["RestorePoint"]["params"]["StartIndex"]
for index, mvideo in enumerate(items["Items"]):
dialog.update(
int(
(
float(start_index + index)
/ float(items["TotalRecordCount"])
)
* 100
),
heading="%s: %s" % (translate("addon_name"), library["Name"]),
message=mvideo["Name"],
)
2020-08-02 21:00:34 +00:00
obj.musicvideo(mvideo)
2024-06-10 09:19:47 +00:00
processed_ids.append(mvideo["Id"])
with self.video_database_locks() as (videodb, jellyfindb):
2024-06-10 09:19:47 +00:00
obj = MusicVideos(
self.server, jellyfindb, videodb, self.direct_path, library
)
2020-02-27 02:05:38 +00:00
obj.item_ids = processed_ids
if self.update_library:
self.musicvideos_compare(library, obj, jellyfindb)
def musicvideos_compare(self, library, obj, jellyfindb):
2024-06-10 09:19:47 +00:00
"""Compare entries from library to what's in the jellyfindb. Remove surplus"""
db = jellyfin_db.JellyfinDatabase(jellyfindb.cursor)
2018-09-06 08:36:32 +00:00
2024-06-10 09:19:47 +00:00
items = db.get_item_by_media_folder(library["Id"])
current = obj.item_ids
2018-09-06 08:36:32 +00:00
for x in items:
2024-06-10 09:19:47 +00:00
if x[0] not in current and x[1] == "MusicVideo":
obj.remove(x[0])
2018-09-06 08:36:32 +00:00
@progress()
def music(self, library, dialog):
2024-06-10 09:19:47 +00:00
"""Process artists, album, songs from a single library."""
with self.library.music_database_lock:
2024-06-10 09:19:47 +00:00
with Database("music") as musicdb:
with Database("jellyfin") as jellyfindb:
obj = Music(
self.server, jellyfindb, musicdb, self.direct_path, library
)
2018-09-06 08:36:32 +00:00
2024-06-10 09:19:47 +00:00
library_id = library["Id"]
2020-08-02 21:00:34 +00:00
2024-06-10 09:19:47 +00:00
total_items = server.get_item_count(
library_id, "MusicArtist,MusicAlbum,Audio"
)
count = 0
2024-06-10 09:19:47 +00:00
"""
Music database syncing. Artists must be in the database
before albums, albums before songs. Pulls batches of items
in sizes of setting "Paging - Max items". 'artists',
'albums', and 'songs' are generators containing a dict of
api responses
2024-06-10 09:19:47 +00:00
"""
artists = server.get_artists(library_id)
for batch in artists:
2024-06-10 09:19:47 +00:00
for item in batch["Items"]:
LOG.debug("Artist: {}".format(item.get("Name")))
percent = int((float(count) / float(total_items)) * 100)
2024-06-10 09:19:47 +00:00
dialog.update(
percent, message="Artist: {}".format(item.get("Name"))
)
obj.artist(item)
count += 1
2024-06-10 09:19:47 +00:00
albums = server.get_items(
library_id,
item_type="MusicAlbum",
params={"SortBy": "AlbumArtist"},
)
for batch in albums:
2024-06-10 09:19:47 +00:00
for item in batch["Items"]:
LOG.debug("Album: {}".format(item.get("Name")))
percent = int((float(count) / float(total_items)) * 100)
2024-06-10 09:19:47 +00:00
dialog.update(
percent,
message="Album: {} - {}".format(
item.get("AlbumArtist", ""), item.get("Name")
),
)
obj.album(item)
count += 1
2024-06-10 09:19:47 +00:00
songs = server.get_items(
library_id, item_type="Audio", params={"SortBy": "AlbumArtist"}
)
for batch in songs:
2024-06-10 09:19:47 +00:00
for item in batch["Items"]:
LOG.debug("Song: {}".format(item.get("Name")))
percent = int((float(count) / float(total_items)) * 100)
2024-06-10 09:19:47 +00:00
dialog.update(
percent,
message="Track: {} - {}".format(
item.get("AlbumArtist", ""), item.get("Name")
),
)
obj.song(item)
count += 1
if self.update_library:
self.music_compare(library, obj, jellyfindb)
def music_compare(self, library, obj, jellyfindb):
2024-06-10 09:19:47 +00:00
"""Compare entries from library to what's in the jellyfindb. Remove surplus"""
db = jellyfin_db.JellyfinDatabase(jellyfindb.cursor)
2024-06-10 09:19:47 +00:00
items = db.get_item_by_media_folder(library["Id"])
for x in list(items):
items.extend(obj.get_child(x[0]))
current = obj.item_ids
for x in items:
2024-06-10 09:19:47 +00:00
if x[0] not in current and x[1] == "MusicArtist":
obj.remove(x[0])
@progress(translate(33018))
2020-08-02 22:50:57 +00:00
def boxsets(self, library, dialog=None):
2024-06-10 09:19:47 +00:00
"""Process all boxsets."""
for items in server.get_items(
library["Id"], "BoxSet", False, self.sync["RestorePoint"].get("params")
):
2018-09-06 08:36:32 +00:00
with self.video_database_locks() as (videodb, jellyfindb):
2024-06-10 09:19:47 +00:00
obj = Movies(
self.server, jellyfindb, videodb, self.direct_path, library
)
self.sync["RestorePoint"] = items["RestorePoint"]
start_index = items["RestorePoint"]["params"]["StartIndex"]
for index, boxset in enumerate(items["Items"]):
dialog.update(
int(
(
float(start_index + index)
/ float(items["TotalRecordCount"])
)
* 100
),
heading="%s: %s"
% (translate("addon_name"), translate("boxsets")),
message=boxset["Name"],
)
obj.boxset(boxset)
2018-09-06 08:36:32 +00:00
2020-08-02 22:50:57 +00:00
def refresh_boxsets(self, library):
2024-06-10 09:19:47 +00:00
"""Delete all existing boxsets and re-add."""
with self.video_database_locks() as (videodb, jellyfindb):
2020-08-02 21:00:34 +00:00
obj = Movies(self.server, jellyfindb, videodb, self.direct_path, library)
obj.boxsets_reset()
2018-09-06 08:36:32 +00:00
2020-12-27 16:36:03 +00:00
self.boxsets(library)
2019-01-25 15:30:30 +00:00
@progress(translate(33144))
2019-01-25 15:30:30 +00:00
def remove_library(self, library_id, dialog):
2024-06-10 09:19:47 +00:00
"""Remove library by their id from the Kodi database."""
2019-01-25 15:30:30 +00:00
direct_path = self.library.direct_path
2024-06-10 09:19:47 +00:00
with Database("jellyfin") as jellyfindb:
2019-01-25 15:30:30 +00:00
db = jellyfin_db.JellyfinDatabase(jellyfindb.cursor)
2024-06-10 09:19:47 +00:00
library = db.get_view(library_id.replace("Mixed:", ""))
items = db.get_item_by_media_folder(library_id.replace("Mixed:", ""))
media = "music" if library.media_type == "music" else "video"
2019-01-25 15:30:30 +00:00
2024-06-10 09:19:47 +00:00
if media == "music":
settings("MusicRescan.bool", False)
2019-01-25 15:30:30 +00:00
if items:
2024-06-10 09:19:47 +00:00
with (
self.library.music_database_lock
if media == "music"
else self.library.database_lock
):
2019-01-25 15:30:30 +00:00
with Database(media) as kodidb:
2020-09-27 15:14:53 +00:00
count = 0
2024-06-10 09:19:47 +00:00
if library.media_type == "mixed":
2019-01-25 15:30:30 +00:00
2024-06-10 09:19:47 +00:00
movies = [x for x in items if x[1] == "Movie"]
tvshows = [x for x in items if x[1] == "Series"]
2019-01-25 15:30:30 +00:00
2024-06-10 09:19:47 +00:00
obj = Movies(
self.server, jellyfindb, kodidb, direct_path, library
).remove
2019-01-25 15:30:30 +00:00
for item in movies:
obj(item[0])
2024-06-10 09:19:47 +00:00
dialog.update(
int((float(count) / float(len(items)) * 100)),
heading="%s: %s"
% (translate("addon_name"), library.view_name),
)
2019-01-25 15:30:30 +00:00
count += 1
2024-06-10 09:19:47 +00:00
obj = TVShows(
self.server, jellyfindb, kodidb, direct_path, library
).remove
2019-01-25 15:30:30 +00:00
for item in tvshows:
obj(item[0])
2024-06-10 09:19:47 +00:00
dialog.update(
int((float(count) / float(len(items)) * 100)),
heading="%s: %s"
% (translate("addon_name"), library.view_name),
)
2019-01-25 15:30:30 +00:00
count += 1
else:
2024-06-10 09:19:47 +00:00
default_args = (
self.server,
jellyfindb,
kodidb,
direct_path,
)
2019-01-25 15:30:30 +00:00
for item in items:
2024-06-10 09:19:47 +00:00
if item[1] in ("Series", "Season", "Episode"):
2020-03-29 03:37:07 +00:00
TVShows(*default_args).remove(item[0])
2024-06-10 09:19:47 +00:00
elif item[1] in ("Movie", "BoxSet"):
2020-03-29 03:37:07 +00:00
Movies(*default_args).remove(item[0])
2024-06-10 09:19:47 +00:00
elif item[1] in (
"MusicAlbum",
"MusicArtist",
"AlbumArtist",
"Audio",
):
2020-03-29 03:37:07 +00:00
Music(*default_args).remove(item[0])
2024-06-10 09:19:47 +00:00
elif item[1] == "MusicVideo":
2020-03-29 03:37:07 +00:00
MusicVideos(*default_args).remove(item[0])
2019-01-25 15:30:30 +00:00
2024-06-10 09:19:47 +00:00
dialog.update(
int((float(count) / float(len(items)) * 100)),
heading="%s: %s"
% (translate("addon_name"), library[0]),
)
2019-01-25 15:30:30 +00:00
count += 1
self.sync = get_sync()
2024-06-10 09:19:47 +00:00
if library_id in self.sync["Whitelist"]:
self.sync["Whitelist"].remove(library_id)
2019-07-09 20:05:28 +00:00
2024-06-10 09:19:47 +00:00
elif "Mixed:%s" % library_id in self.sync["Whitelist"]:
self.sync["Whitelist"].remove("Mixed:%s" % library_id)
2019-01-25 15:30:30 +00:00
save_sync(self.sync)
def __exit__(self, exc_type, exc_val, exc_tb):
2024-06-10 09:19:47 +00:00
"""Exiting sync"""
2019-01-25 15:30:30 +00:00
self.running = False
2024-06-10 09:19:47 +00:00
window("jellyfin_sync", clear=True)
2019-01-25 15:30:30 +00:00
2024-06-10 09:19:47 +00:00
if not settings("dbSyncScreensaver.bool") and self.screensaver is not None:
2019-01-25 15:30:30 +00:00
2024-06-10 09:19:47 +00:00
xbmc.executebuiltin("InhibitIdleShutdown(false)")
2019-01-25 15:30:30 +00:00
set_screensaver(value=self.screensaver)
LOG.info("--<[ fullsync ]")