ServiceRegistry.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/ServiceRegistry.kt
1package eu.friedcutlet.yokan.app23import eu.friedcutlet.yokan.database.DbItemType4import eu.friedcutlet.yokan.database.DbPageUrl5import eu.friedcutlet.yokan.database.YokanDatabase6import eu.friedcutlet.yokan.domain.ProfileId7import eu.friedcutlet.yokan.services.backup.BackupService8import eu.friedcutlet.yokan.services.discovery.DiscoveryService9import eu.friedcutlet.yokan.services.discovery.HttpDiscoveryService10import eu.friedcutlet.yokan.services.download.DownloadAutomation11import eu.friedcutlet.yokan.services.download.DownloadService12import eu.friedcutlet.yokan.services.download.ExternalDownloads13import eu.friedcutlet.yokan.services.download.ImageDataSaver14import eu.friedcutlet.yokan.services.download.PersistentDownloadService15import eu.friedcutlet.yokan.services.download.keepDownloadsAlive16import eu.friedcutlet.yokan.services.extensions.DynamicExtensionRuntimeFactory17import eu.friedcutlet.yokan.services.extensions.ExtensionRuntimeFactory18import eu.friedcutlet.yokan.services.extensions.HttpSourceCatalogService19import eu.friedcutlet.yokan.services.extensions.SourceCatalogService20import eu.friedcutlet.yokan.services.extensions.mergeSourcePageHeaders21import eu.friedcutlet.yokan.services.extensions.mihon.DefaultExtensionServerRuntimeService22import eu.friedcutlet.yokan.services.extensions.mihon.ExtensionServerRuntimeService23import eu.friedcutlet.yokan.services.extensions.mihon.createPlatformExtensionServerAdapter24import eu.friedcutlet.yokan.services.extensions.mihon.resolveMihonProxy25import eu.friedcutlet.yokan.services.extensions.recipe.RecipeCatalogInstallationService26import eu.friedcutlet.yokan.services.extensions.recipe.RecipeInstallationClock27import eu.friedcutlet.yokan.services.extensions.recipe.createPlatformRecipeServices28import eu.friedcutlet.yokan.services.extensions.withSourceRuntime29import eu.friedcutlet.yokan.services.files.LocalArchiveService30import eu.friedcutlet.yokan.services.files.LocalFileService31import eu.friedcutlet.yokan.services.http.EnhancedHttpService32import eu.friedcutlet.yokan.services.http.HostResolver33import eu.friedcutlet.yokan.services.http.HttpService34import eu.friedcutlet.yokan.services.http.KtorHttpService35import eu.friedcutlet.yokan.services.http.ProfileHttpService36import eu.friedcutlet.yokan.services.http.cookies.CookieJar37import eu.friedcutlet.yokan.services.http.createPlatformHttpClientEngine38import eu.friedcutlet.yokan.services.http.createPlatformHttpService39import eu.friedcutlet.yokan.services.library.DefaultLibraryUpdaterService40import eu.friedcutlet.yokan.services.library.DefaultLocalEntryManagementService41import eu.friedcutlet.yokan.services.library.DefaultLocalLibraryService42import eu.friedcutlet.yokan.services.library.LibraryAiringService43import eu.friedcutlet.yokan.services.library.LibraryUpdaterService44import eu.friedcutlet.yokan.services.library.LocalEntryManagementService45import eu.friedcutlet.yokan.services.library.LocalLibraryService46import eu.friedcutlet.yokan.services.media.AnimeExtractorService47import eu.friedcutlet.yokan.services.media.SubtitleService48import eu.friedcutlet.yokan.services.media.extractors.DoodExtractor49import eu.friedcutlet.yokan.services.media.extractors.FilemoonExtractor50import eu.friedcutlet.yokan.services.media.extractors.GogoCdnExtractor51import eu.friedcutlet.yokan.services.media.extractors.KwikExtractor52import eu.friedcutlet.yokan.services.media.extractors.Mp4UploadExtractor53import eu.friedcutlet.yokan.services.media.extractors.MyStreamExtractor54import eu.friedcutlet.yokan.services.media.extractors.MytvExtractor55import eu.friedcutlet.yokan.services.media.extractors.OkruExtractor56import eu.friedcutlet.yokan.services.media.extractors.QuarkUcExtractor57import eu.friedcutlet.yokan.services.media.extractors.SendvidExtractor58import eu.friedcutlet.yokan.services.media.extractors.SibnetExtractor59import eu.friedcutlet.yokan.services.media.extractors.StreamTapeExtractor60import eu.friedcutlet.yokan.services.media.extractors.StreamWishExtractor61import eu.friedcutlet.yokan.services.media.extractors.StreamlareExtractor62import eu.friedcutlet.yokan.services.media.extractors.VidBomExtractor63import eu.friedcutlet.yokan.services.media.extractors.VoeExtractor64import eu.friedcutlet.yokan.services.media.extractors.YourUploadExtractor65import eu.friedcutlet.yokan.services.metadata.HttpMetadataService66import eu.friedcutlet.yokan.services.metadata.MetadataService67import eu.friedcutlet.yokan.services.metadata.RecommendationService68import eu.friedcutlet.yokan.services.metadata.WatchOrderService69import eu.friedcutlet.yokan.services.notifications.NotificationService70import eu.friedcutlet.yokan.services.sync.CloudBackupSyncService71import eu.friedcutlet.yokan.services.sync.DefaultCloudBackupSyncService72import eu.friedcutlet.yokan.services.sync.GoogleDriveCloudStorageProvider73import eu.friedcutlet.yokan.services.sync.GoogleDriveSyncService74import eu.friedcutlet.yokan.services.sync.HubSyncService75import eu.friedcutlet.yokan.services.sync.HybridSyncService76import eu.friedcutlet.yokan.services.sync.MangayomiSyncService77import eu.friedcutlet.yokan.services.sync.ProfileSyncServices78import eu.friedcutlet.yokan.services.sync.SyncAccountLeases79import eu.friedcutlet.yokan.services.sync.SyncOperationMonitor80import eu.friedcutlet.yokan.services.sync.SyncService81import eu.friedcutlet.yokan.services.sync.SyncYomiSyncService82import eu.friedcutlet.yokan.services.sync.adoptConfiguredSyncAccount83import eu.friedcutlet.yokan.services.system.createNetworkMonitor84import eu.friedcutlet.yokan.services.torrent.TorrentStreams85import eu.friedcutlet.yokan.services.torrent.createPlatformTorrServerHost86import eu.friedcutlet.yokan.services.tracking.AnilistTrackerService87import eu.friedcutlet.yokan.services.tracking.AnilistTrackerSyncId88import eu.friedcutlet.yokan.services.tracking.BangumiTrackerService89import eu.friedcutlet.yokan.services.tracking.BangumiTrackerSyncId90import eu.friedcutlet.yokan.services.tracking.HikkaTrackerService91import eu.friedcutlet.yokan.services.tracking.HikkaTrackerSyncId92import eu.friedcutlet.yokan.services.tracking.JellyfinTrackerService93import eu.friedcutlet.yokan.services.tracking.JellyfinTrackerSyncId94import eu.friedcutlet.yokan.services.tracking.KavitaTrackerService95import eu.friedcutlet.yokan.services.tracking.KavitaTrackerSyncId96import eu.friedcutlet.yokan.services.tracking.KitsuTrackerService97import eu.friedcutlet.yokan.services.tracking.KitsuTrackerSyncId98import eu.friedcutlet.yokan.services.tracking.KomgaTrackerService99import eu.friedcutlet.yokan.services.tracking.KomgaTrackerSyncId100import eu.friedcutlet.yokan.services.tracking.MalTrackerService101import eu.friedcutlet.yokan.services.tracking.MalTrackerSyncId102import eu.friedcutlet.yokan.services.tracking.MangaBakaTrackerService103import eu.friedcutlet.yokan.services.tracking.MangaBakaTrackerSyncId104import eu.friedcutlet.yokan.services.tracking.MangaUpdatesTrackerService105import eu.friedcutlet.yokan.services.tracking.MangaUpdatesTrackerSyncId106import eu.friedcutlet.yokan.services.tracking.MetadataTrackerService107import eu.friedcutlet.yokan.services.tracking.MetadataTrackerSyncId108import eu.friedcutlet.yokan.services.tracking.ShikimoriTrackerService109import eu.friedcutlet.yokan.services.tracking.ShikimoriTrackerSyncId110import eu.friedcutlet.yokan.services.tracking.SimklTrackerService111import eu.friedcutlet.yokan.services.tracking.SimklTrackerSyncId112import eu.friedcutlet.yokan.services.tracking.SuwayomiTrackerService113import eu.friedcutlet.yokan.services.tracking.SuwayomiTrackerSyncId114import eu.friedcutlet.yokan.services.tracking.TmdbTrackerService115import eu.friedcutlet.yokan.services.tracking.TmdbTrackerSyncId116import eu.friedcutlet.yokan.services.tracking.TrackerAccounts117import eu.friedcutlet.yokan.services.tracking.TrackerService118import eu.friedcutlet.yokan.services.tracking.TraktTrackerService119import eu.friedcutlet.yokan.services.tracking.TraktTrackerSyncId120import eu.friedcutlet.yokan.services.translation.LibreTranslateTranslatorService121import eu.friedcutlet.yokan.services.translation.TranslatorService122import eu.friedcutlet.yokan.services.tts.ProfileSpeechService123import eu.friedcutlet.yokan.services.tts.TextToSpeechService124import eu.friedcutlet.yokan.services.tts.createPlatformTextToSpeechService125import eu.friedcutlet.yokan.services.webview.WebViewRequest126import eu.friedcutlet.yokan.services.webview.WebViewService127import eu.friedcutlet.yokan.services.webview.createPlatformWebViewService128import kotlinx.coroutines.CoroutineScope129import kotlinx.coroutines.Job130import kotlinx.coroutines.cancelAndJoin131import kotlinx.coroutines.sync.Mutex132import kotlinx.coroutines.sync.withLock133134class YokanServices(135 val database: YokanDatabase,136 val extensionRuntimeFactory: ExtensionRuntimeFactory,137 val extensionServer: ExtensionServerRuntimeService,138 val trackers: List<TrackerService>,139 val trackerAccounts: TrackerAccounts,140 val downloader: DownloadService,141 val backup: BackupService,142 val sync: SyncService,143 val cloudSync: CloudBackupSyncService,144 val sourceCatalog: SourceCatalogService,145 val libraryUpdater: LibraryUpdaterService,146 val subtitle: SubtitleService,147 val watchOrder: WatchOrderService,148 val recommendation: RecommendationService,149 val metadata: MetadataService,150 val translator: TranslatorService,151 val webView: WebViewService,152 val http: HttpService,153 textToSpeech: TextToSpeechService,154 val animeExtractors: List<AnimeExtractorService>,155 val localLibrary: LocalLibraryService,156 val localEntryManagement: LocalEntryManagementService,157 val cookieJar: CookieJar,158 val recipeCatalogInstallation: RecipeCatalogInstallationService,159 /** Owns background coroutines (download workers, foreground scheduler, startup jobs). */160 val scope: CoroutineScope,161 val downloadAutomation: DownloadAutomation,162 val imageDataSaver: ImageDataSaver,163 val externalDownloads: ExternalDownloads,164 private val platformHttp: KtorHttpService,165 isOwnerOpen: () -> Boolean,166 val libraryAirings: LibraryAiringService,167 val torrents: TorrentStreams,168) {169 val discovery: DiscoveryService by lazy {170 HttpDiscoveryService(http, database, extensionRuntimeFactory)171 }172 val textToSpeech = ProfileSpeechService(textToSpeech, scope, isOwnerOpen)173 private val retirementLock = Mutex()174175 /** Session retirement waits for worker finalizers before releasing captured runtimes. */176 suspend fun closeAndJoin() = retirementLock.withLock {177 scope.coroutineContext[Job]?.cancelAndJoin()178 textToSpeech.closeAndJoin()179 extensionServer.stop()180 torrents.stop()181 extensionRuntimeFactory.clear()182 sync.closeAndJoin()183 platformHttp.closeAndJoin()184 }185}186187/**188 * Builds the service graph. [files]/[archives]/[notifications]/[backup] are passed in so the whole189 * session shares one instance of each (the JVM archive service keeps extraction caches).190 * [resolveDownloadPages] resolves a chapter's pages when its download starts.191 */192fun defaultServices(193 database: YokanDatabase,194 files: LocalFileService,195 archives: LocalArchiveService,196 notifications: NotificationService,197 backup: BackupService,198 resolveDownloadPages: suspend (chapterId: Long, forceRefresh: Boolean) -> List<DbPageUrl>,199 scope: CoroutineScope,200 profileId: ProfileId,201 isOwnerOpen: () -> Boolean,202 syncLeases: SyncAccountLeases,203 /** DNS-over-HTTPS lookup for the main client; must not itself resolve through that client. */204 resolveHost: HostResolver?,205): YokanServices {206 requireNotNull(scope.coroutineContext[Job]) { "Profile services require an owner job" }207 val cookieJar = CookieJar(database, profileId) { scope.coroutineContext[Job]?.isActive == true }208 val platformHttp = createPlatformHttpService(profileId, scope, resolveHost)209 val rawHttp = ProfileHttpService(profileId, platformHttp, scope)210 val enhancedHttp = EnhancedHttpService(rawHttp, database, cookieJar)211 val http = ProfileHttpService(profileId, enhancedHttp, scope)212 val imageDataSaver = ImageDataSaver(rawHttp, cookieJar)213 // Genuine cycle, closed once here: the WebView solver retries through the enhanced client214 // (cookie jar + solver-bypass header) and the client hands challenges to the solver.215 val webView = createPlatformWebViewService(http, cookieJar, files, scope).also { webView ->216 enhancedHttp.cloudflareSolver = { url, headers -> webView.resolveCloudflare(WebViewRequest(url = url, title = "", headers = headers)) }217 }218 val animeExtractors = animeExtractors(http, cookieJar)219 val extensionServer: ExtensionServerRuntimeService = DefaultExtensionServerRuntimeService(220 database,221 http,222 createPlatformExtensionServerAdapter(profileId),223 )224 val recipeInstallationClock = RecipeInstallationClock { kotlin.time.Clock.System.now().toEpochMilliseconds() / 1_000 }225 val recipeServices = createPlatformRecipeServices(database, recipeInstallationClock)226 val runtimeFactory = DynamicExtensionRuntimeFactory(227 database = database,228 http = http,229 prepareMihonProxy = { proxy -> extensionServer.resolveMihonProxy(proxy) },230 recipeRuntime = recipeServices.runtimeBindings,231 archives = archives,232 webView = webView,233 animeExtractors = animeExtractors,234 )235 val metadata = HttpMetadataService(http)236 val syncOperationMonitor = SyncOperationMonitor()237 val cloudSync = DefaultCloudBackupSyncService(238 database = database,239 backup = backup,240 providers = listOf(GoogleDriveCloudStorageProvider(http)),241 operationMonitor = syncOperationMonitor,242 leases = syncLeases,243 )244 val serverSync = HubSyncService(245 database,246 http,247 createPlatformHttpClientEngine(profileId),248 scope = scope,249 operationMonitor = syncOperationMonitor,250 leases = syncLeases,251 )252 // Direct owned transport: the enhanced app client persists Set-Cookie into the profile jar,253 // while Mangayomi's id= JWT must remain isolated in the sync preference only.254 val mangayomiSync = MangayomiSyncService(database, rawHttp, syncOperationMonitor, syncLeases)255 // Same isolation for SyncYomi's API key and Google OAuth tokens.256 val syncYomiSync = SyncYomiSyncService(database, backup, rawHttp, syncOperationMonitor, syncLeases)257 val googleDriveSync = GoogleDriveSyncService(database, backup, rawHttp, syncOperationMonitor, syncLeases)258 val profileSync = ProfileSyncServices(259 profileId = profileId,260 delegate = HybridSyncService(serverSync, cloudSync, database, syncOperationMonitor, mangayomiSync, syncYomiSync, googleDriveSync),261 cloudDelegate = cloudSync,262 ownerScope = scope,263 )264 adoptConfiguredSyncAccount(syncLeases, database, scope)265 val localLibrary = DefaultLocalLibraryService(database, files, archives)266 // User-hosted/loopback server: direct transport like the self-hosted trackers below.267 val torrents = TorrentStreams(database, rawHttp, files, createPlatformTorrServerHost(profileId))268 var automationOwner: DownloadAutomation? = null269 val downloadPages: suspend (Long, Boolean) -> List<DbPageUrl> = { chapterId, forceRefresh ->270 val chapter = checkNotNull(database.chapter(chapterId))271 val title = checkNotNull(chapter.mangaId?.let(database::manga))272 if (title.itemType == DbItemType.Anime) {273 runtimeFactory.withSourceRuntime(database, checkNotNull(title.sourceId)) { runtime ->274 runtime.videoList(chapter.url).firstOrNull()?.let { video ->275 // Animetail downloads torrent videos through TorrServer's stream URL.276 val resolved = torrents.expand(listOf(video), title.name.orEmpty()).first()277 mergeSourcePageHeaders(runtime.headers(), listOf(DbPageUrl(url = resolved.url, headers = resolved.headers)))278 }.orEmpty()279 }280 } else resolveDownloadPages(chapterId, forceRefresh)281 }282 val externalDownloads = ExternalDownloads(database, rawHttp, scope, downloadPages)283 val downloader = PersistentDownloadService(284 database = database,285 http = http,286 files = files,287 archives = archives,288 scope = scope,289 resolvePages = downloadPages,290 resolveNovelText = { chapterId ->291 val chapter = checkNotNull(database.chapter(chapterId))292 val title = checkNotNull(chapter.mangaId?.let(database::manga))293 runtimeFactory.withSourceRuntime(database, checkNotNull(title.sourceId)) { runtime ->294 runtime.cleanHtmlContent(runtime.htmlContent(chapter.name.orEmpty(), chapter.url))295 }296 },297 notifications = notifications,298 network = createNetworkMonitor(),299 onCompleted = { chapterId -> automationOwner?.downloadCompleted(chapterId) },300 imageDataSaver = imageDataSaver,301 imageHttp = rawHttp,302 ).also { keepDownloadsAlive(it, database, scope, profileId) }303 val downloadAutomation = DownloadAutomation(database, downloader, scope)304 automationOwner = downloadAutomation305 val trackers = trackers(database, http, rawHttp, metadata)306 return YokanServices(307 externalDownloads = externalDownloads,308 torrents = torrents,309 imageDataSaver = imageDataSaver,310 database = database,311 extensionRuntimeFactory = runtimeFactory,312 extensionServer = extensionServer,313 trackers = trackers,314 trackerAccounts = TrackerAccounts(database, trackers, scope),315 downloader = downloader,316 backup = backup,317 sync = profileSync.sync,318 cloudSync = profileSync.cloud,319 sourceCatalog = HttpSourceCatalogService(http, files),320 libraryUpdater = DefaultLibraryUpdaterService(database, runtimeFactory, downloadAutomation),321 libraryAirings = LibraryAiringService(database, rawHttp, scope),322 downloadAutomation = downloadAutomation,323 subtitle = SubtitleService(http),324 watchOrder = WatchOrderService(http),325 recommendation = RecommendationService(http, database),326 metadata = metadata,327 translator = LibreTranslateTranslatorService(http),328 webView = webView,329 http = http,330 textToSpeech = createPlatformTextToSpeechService(),331 animeExtractors = animeExtractors,332 localLibrary = localLibrary,333 localEntryManagement = DefaultLocalEntryManagementService(database, localLibrary),334 cookieJar = cookieJar,335 scope = scope,336 platformHttp = platformHttp,337 recipeCatalogInstallation = recipeServices.installation,338 isOwnerOpen = isOwnerOpen,339 )340}341342// All 16 anime extractors from the Flutter `lib/services/anime_extractors/` directory are ported.343// Sendvid and YourUpload sometimes need source-supplied headers (Referer mostly); those still get344// forwarded through `extract(url, headers)`.345private fun animeExtractors(http: HttpService, cookieJar: CookieJar): List<AnimeExtractorService> = listOf(346 StreamTapeExtractor(http),347 VoeExtractor(http),348 StreamWishExtractor(http),349 FilemoonExtractor(http),350 GogoCdnExtractor(http),351 DoodExtractor(http),352 Mp4UploadExtractor(http),353 MyStreamExtractor(http),354 MytvExtractor(http),355 OkruExtractor(http),356 SendvidExtractor(http),357 SibnetExtractor(http),358 StreamlareExtractor(http),359 VidBomExtractor(http),360 YourUploadExtractor(http),361 QuarkUcExtractor(http, cookieJar),362 // Kwik / Pahewin — AnimePahe's HLS / MP4 wrapper. HLS path is363 // packed-eval; MP4 path is the kwik.cx custom obfuscator + form364 // POST. See KwikExtractor.kt for caveats around Cloudflare.365 KwikExtractor(http),366)367368private fun trackers(369 database: YokanDatabase,370 http: HttpService,371 rawHttp: HttpService,372 metadata: MetadataService,373): List<TrackerService> = listOf(374 MalTrackerService(MalTrackerSyncId, database, http),375 AnilistTrackerService(AnilistTrackerSyncId, database, http),376 KitsuTrackerService(KitsuTrackerSyncId, database, http),377 SimklTrackerService(SimklTrackerSyncId, database, http),378 TraktTrackerService(TraktTrackerSyncId, database, http),379 MetadataTrackerService(MetadataTrackerSyncId, database, metadata),380 MangaUpdatesTrackerService(MangaUpdatesTrackerSyncId, database, http),381 ShikimoriTrackerService(ShikimoriTrackerSyncId, database, http),382 BangumiTrackerService(BangumiTrackerSyncId, database, http),383 HikkaTrackerService(HikkaTrackerSyncId, database, http),384 MangaBakaTrackerService(MangaBakaTrackerSyncId, database, http),385 TmdbTrackerService(TmdbTrackerSyncId, database, http),386 // User-hosted servers (often LAN addresses) bypass the DoH/cookie layer, like the sync servers.387 KomgaTrackerService(KomgaTrackerSyncId, database, rawHttp),388 KavitaTrackerService(KavitaTrackerSyncId, database, rawHttp),389 SuwayomiTrackerService(SuwayomiTrackerSyncId, database, rawHttp),390 JellyfinTrackerService(JellyfinTrackerSyncId, database, rawHttp),391)392