Repository: recloudstream/cloudstream
Branch: master
Commit: 19efb1ffc3f7
Files: 1156
Total size: 6.6 MB
Directory structure:
gitextract_bfixog4j/
├── .github/
│ ├── ISSUE_TEMPLATE/
│ │ ├── application-bug.yml
│ │ ├── config.yml
│ │ └── feature-request.yml
│ ├── locales.py
│ └── workflows/
│ ├── build_to_archive.yml
│ ├── generate_dokka.yml
│ ├── issue_action.yml
│ ├── prerelease.yml
│ ├── pull_request.yml
│ └── update_locales.yml
├── .gitignore
├── AI-POLICY.md
├── LICENSE
├── README.md
├── app/
│ ├── .gitignore
│ ├── build.gradle.kts
│ ├── lint.xml
│ ├── proguard-rules.pro
│ └── src/
│ ├── androidTest/
│ │ └── java/
│ │ └── com/
│ │ └── lagradost/
│ │ └── cloudstream3/
│ │ └── ExampleInstrumentedTest.kt
│ ├── debug/
│ │ └── res/
│ │ ├── drawable/
│ │ │ └── ic_banner_foreground.xml
│ │ ├── drawable-anydpi-v24/
│ │ │ └── ic_stat_name.xml
│ │ ├── drawable-v24/
│ │ │ ├── ic_banner_background.xml
│ │ │ └── ic_launcher_foreground.xml
│ │ ├── mipmap-anydpi-v26/
│ │ │ ├── ic_banner.xml
│ │ │ ├── ic_launcher.xml
│ │ │ └── ic_launcher_round.xml
│ │ └── values/
│ │ ├── ic_launcher_background.xml
│ │ └── strings.xml
│ ├── main/
│ │ ├── AndroidManifest.xml
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── lagradost/
│ │ │ └── cloudstream3/
│ │ │ ├── AcraApplication.kt
│ │ │ ├── CloudStreamApp.kt
│ │ │ ├── CommonActivity.kt
│ │ │ ├── DownloaderTestImpl.kt
│ │ │ ├── MainActivity.kt
│ │ │ ├── actions/
│ │ │ │ ├── AlwaysAskAction.kt
│ │ │ │ ├── OpenInAppAction.kt
│ │ │ │ ├── VideoClickAction.kt
│ │ │ │ └── temp/
│ │ │ │ ├── Aria2Package.kt
│ │ │ │ ├── BiglyBTPackage.kt
│ │ │ │ ├── CloudStreamPackage.kt
│ │ │ │ ├── CopyClipboardAction.kt
│ │ │ │ ├── JustPlayerPackage.kt
│ │ │ │ ├── LibreTorrentPackage.kt
│ │ │ │ ├── MpvKtPackage.kt
│ │ │ │ ├── MpvPackage.kt
│ │ │ │ ├── NextPlayerPackage.kt
│ │ │ │ ├── PlayInBrowserAction.kt
│ │ │ │ ├── PlayMirrorAction.kt
│ │ │ │ ├── ViewM3U8Action.kt
│ │ │ │ ├── VlcPackage.kt
│ │ │ │ ├── WebVideoCastPackage.kt
│ │ │ │ └── fcast/
│ │ │ │ ├── FcastAction.kt
│ │ │ │ ├── FcastManager.kt
│ │ │ │ ├── FcastSession.kt
│ │ │ │ └── Packets.kt
│ │ │ ├── mvvm/
│ │ │ │ └── Lifecycle.kt
│ │ │ ├── network/
│ │ │ │ ├── CloudflareKiller.kt
│ │ │ │ ├── DdosGuardKiller.kt
│ │ │ │ ├── DohProviders.kt
│ │ │ │ └── RequestsHelper.kt
│ │ │ ├── plugins/
│ │ │ │ ├── Plugin.kt
│ │ │ │ ├── PluginManager.kt
│ │ │ │ ├── RepositoryManager.kt
│ │ │ │ └── VotingApi.kt
│ │ │ ├── receivers/
│ │ │ │ └── VideoDownloadRestartReceiver.kt
│ │ │ ├── services/
│ │ │ │ ├── BackupWorkManager.kt
│ │ │ │ ├── DownloadQueueService.kt
│ │ │ │ ├── PackageInstallerService.kt
│ │ │ │ ├── SubscriptionWorkManager.kt
│ │ │ │ └── VideoDownloadService.kt
│ │ │ ├── subtitles/
│ │ │ │ ├── AbstractSubProvider.kt
│ │ │ │ └── AbstractSubtitleEntities.kt
│ │ │ ├── syncproviders/
│ │ │ │ ├── AccountManager.kt
│ │ │ │ ├── AuthAPI.kt
│ │ │ │ ├── AuthRepo.kt
│ │ │ │ ├── BackupAPI.kt
│ │ │ │ ├── SubtitleAPI.kt
│ │ │ │ ├── SubtitleRepo.kt
│ │ │ │ ├── SyncAPI.kt
│ │ │ │ ├── SyncRepo.kt
│ │ │ │ └── providers/
│ │ │ │ ├── Addic7ed.kt
│ │ │ │ ├── AniListApi.kt
│ │ │ │ ├── KitsuApi.kt
│ │ │ │ ├── LocalList.kt
│ │ │ │ ├── MALApi.kt
│ │ │ │ ├── OpenSubtitlesApi.kt
│ │ │ │ ├── SimklApi.kt
│ │ │ │ ├── SubSource.kt
│ │ │ │ └── Subdl.kt
│ │ │ ├── ui/
│ │ │ │ ├── APIRepository.kt
│ │ │ │ ├── BaseAdapter.kt
│ │ │ │ ├── BaseFragment.kt
│ │ │ │ ├── ControllerActivity.kt
│ │ │ │ ├── CustomRecyclerViews.kt
│ │ │ │ ├── EasterEggMonkeFragment.kt
│ │ │ │ ├── MiniControllerFragment.kt
│ │ │ │ ├── NonFinalAdapterListUpdateCallback.kt
│ │ │ │ ├── WatchType.kt
│ │ │ │ ├── WebviewFragment.kt
│ │ │ │ ├── account/
│ │ │ │ │ ├── AccountAdapter.kt
│ │ │ │ │ ├── AccountHelper.kt
│ │ │ │ │ ├── AccountSelectActivity.kt
│ │ │ │ │ ├── AccountSelectLinearItemDecoration.kt
│ │ │ │ │ └── AccountViewModel.kt
│ │ │ │ ├── download/
│ │ │ │ │ ├── DownloadAdapter.kt
│ │ │ │ │ ├── DownloadButtonSetup.kt
│ │ │ │ │ ├── DownloadChildFragment.kt
│ │ │ │ │ ├── DownloadFragment.kt
│ │ │ │ │ ├── DownloadViewModel.kt
│ │ │ │ │ ├── button/
│ │ │ │ │ │ ├── BaseFetchButton.kt
│ │ │ │ │ │ ├── DownloadButton.kt
│ │ │ │ │ │ ├── PieFetchButton.kt
│ │ │ │ │ │ └── ProgressBarAnimation.kt
│ │ │ │ │ └── queue/
│ │ │ │ │ ├── DownloadQueueAdapter.kt
│ │ │ │ │ ├── DownloadQueueFragment.kt
│ │ │ │ │ └── DownloadQueueViewModel.kt
│ │ │ │ ├── home/
│ │ │ │ │ ├── HomeChildItemAdapter.kt
│ │ │ │ │ ├── HomeFragment.kt
│ │ │ │ │ ├── HomeParentItemAdapter.kt
│ │ │ │ │ ├── HomeParentItemAdapterPreview.kt
│ │ │ │ │ ├── HomeScrollAdapter.kt
│ │ │ │ │ ├── HomeScrollTransformer.kt
│ │ │ │ │ └── HomeViewModel.kt
│ │ │ │ ├── library/
│ │ │ │ │ ├── LibraryFragment.kt
│ │ │ │ │ ├── LibraryScrollTransformer.kt
│ │ │ │ │ ├── LibraryViewModel.kt
│ │ │ │ │ ├── LoadingPosterAdapter.kt
│ │ │ │ │ ├── PageAdapter.kt
│ │ │ │ │ └── ViewpagerAdapter.kt
│ │ │ │ ├── player/
│ │ │ │ │ ├── AbstractPlayerFragment.kt
│ │ │ │ │ ├── CS3IPlayer.kt
│ │ │ │ │ ├── CustomSubripParser.kt
│ │ │ │ │ ├── CustomSubtitleDecoderFactory.kt
│ │ │ │ │ ├── DownloadFileGenerator.kt
│ │ │ │ │ ├── DownloadedPlayerActivity.kt
│ │ │ │ │ ├── ExtractorLinkGenerator.kt
│ │ │ │ │ ├── FixedNextRenderersFactory.kt
│ │ │ │ │ ├── FullScreenPlayer.kt
│ │ │ │ │ ├── GeneratorPlayer.kt
│ │ │ │ │ ├── IGenerator.kt
│ │ │ │ │ ├── IPlayer.kt
│ │ │ │ │ ├── LinkGenerator.kt
│ │ │ │ │ ├── OfflinePlaybackHelper.kt
│ │ │ │ │ ├── OutlineSpan.kt
│ │ │ │ │ ├── PlayerGeneratorViewModel.kt
│ │ │ │ │ ├── PlayerPipHelper.kt
│ │ │ │ │ ├── PlayerSubtitleHelper.kt
│ │ │ │ │ ├── PreviewGenerator.kt
│ │ │ │ │ ├── RepoLinkGenerator.kt
│ │ │ │ │ ├── RoundedBackgroundColorSpan.kt
│ │ │ │ │ ├── SSLTrustManager.kt
│ │ │ │ │ ├── SubtitleOffsetItemAdapter.kt
│ │ │ │ │ ├── Torrent.kt
│ │ │ │ │ ├── UpdatedDefaultExtractorsFactory.kt
│ │ │ │ │ ├── UpdatedMatroskaExtractor.kt
│ │ │ │ │ └── source_priority/
│ │ │ │ │ ├── PriorityAdapter.kt
│ │ │ │ │ ├── ProfilesAdapter.kt
│ │ │ │ │ ├── QualityDataHelper.kt
│ │ │ │ │ ├── QualityProfileDialog.kt
│ │ │ │ │ └── SourcePriorityDialog.kt
│ │ │ │ ├── quicksearch/
│ │ │ │ │ └── QuickSearchFragment.kt
│ │ │ │ ├── result/
│ │ │ │ │ ├── ActorAdaptor.kt
│ │ │ │ │ ├── EpisodeAdapter.kt
│ │ │ │ │ ├── ImageAdapter.kt
│ │ │ │ │ ├── LinearListLayout.kt
│ │ │ │ │ ├── ResultFragment.kt
│ │ │ │ │ ├── ResultFragmentPhone.kt
│ │ │ │ │ ├── ResultFragmentTv.kt
│ │ │ │ │ ├── ResultTrailerPlayer.kt
│ │ │ │ │ ├── ResultViewModel2.kt
│ │ │ │ │ ├── SelectAdaptor.kt
│ │ │ │ │ └── SyncViewModel.kt
│ │ │ │ ├── search/
│ │ │ │ │ ├── SearchAdaptor.kt
│ │ │ │ │ ├── SearchFragment.kt
│ │ │ │ │ ├── SearchHelper.kt
│ │ │ │ │ ├── SearchHistoryAdaptor.kt
│ │ │ │ │ ├── SearchResultBuilder.kt
│ │ │ │ │ ├── SearchSuggestionAdapter.kt
│ │ │ │ │ ├── SearchSuggestionApi.kt
│ │ │ │ │ ├── SearchViewModel.kt
│ │ │ │ │ └── SyncSearchViewModel.kt
│ │ │ │ ├── settings/
│ │ │ │ │ ├── AccountAdapter.kt
│ │ │ │ │ ├── Globals.kt
│ │ │ │ │ ├── LogcatAdapter.kt
│ │ │ │ │ ├── SettingsAccount.kt
│ │ │ │ │ ├── SettingsFragment.kt
│ │ │ │ │ ├── SettingsGeneral.kt
│ │ │ │ │ ├── SettingsPlayer.kt
│ │ │ │ │ ├── SettingsProviders.kt
│ │ │ │ │ ├── SettingsUI.kt
│ │ │ │ │ ├── SettingsUpdates.kt
│ │ │ │ │ ├── extensions/
│ │ │ │ │ │ ├── ExtensionsFragment.kt
│ │ │ │ │ │ ├── ExtensionsViewModel.kt
│ │ │ │ │ │ ├── PluginAdapter.kt
│ │ │ │ │ │ ├── PluginDetailsFragment.kt
│ │ │ │ │ │ ├── PluginsFragment.kt
│ │ │ │ │ │ ├── PluginsViewModel.kt
│ │ │ │ │ │ └── RepoAdapter.kt
│ │ │ │ │ ├── testing/
│ │ │ │ │ │ ├── TestFragment.kt
│ │ │ │ │ │ ├── TestResultAdapter.kt
│ │ │ │ │ │ ├── TestView.kt
│ │ │ │ │ │ └── TestViewModel.kt
│ │ │ │ │ └── utils/
│ │ │ │ │ └── DirectoryPicker.kt
│ │ │ │ ├── setup/
│ │ │ │ │ ├── SetupFragmentExtensions.kt
│ │ │ │ │ ├── SetupFragmentLanguage.kt
│ │ │ │ │ ├── SetupFragmentLayout.kt
│ │ │ │ │ ├── SetupFragmentMedia.kt
│ │ │ │ │ └── SetupFragmentProviderLanguage.kt
│ │ │ │ └── subtitles/
│ │ │ │ ├── ChromecastSubtitlesFragment.kt
│ │ │ │ └── SubtitlesFragment.kt
│ │ │ ├── utils/
│ │ │ │ ├── AniSkip.kt
│ │ │ │ ├── AppContextUtils.kt
│ │ │ │ ├── BackPressedCallbackHelper.kt
│ │ │ │ ├── BackupUtils.kt
│ │ │ │ ├── BiometricAuthenticator.kt
│ │ │ │ ├── CastHelper.kt
│ │ │ │ ├── CastOptionsProvider.kt
│ │ │ │ ├── ConsistentLiveData.kt
│ │ │ │ ├── DataStore.kt
│ │ │ │ ├── DataStoreHelper.kt
│ │ │ │ ├── DownloadFileWorkManager.kt
│ │ │ │ ├── Event.kt
│ │ │ │ ├── FillerEpisodeCheck.kt
│ │ │ │ ├── IDisposable.kt
│ │ │ │ ├── ImageModuleCoil.kt
│ │ │ │ ├── ImageUtil.kt
│ │ │ │ ├── InAppUpdater.kt
│ │ │ │ ├── IntentHelpers.kt
│ │ │ │ ├── PackageInstaller.kt
│ │ │ │ ├── PercentageCropImageView.kt
│ │ │ │ ├── PowerManagerAPI.kt
│ │ │ │ ├── SingleSelectionHelper.kt
│ │ │ │ ├── SnackbarHelper.kt
│ │ │ │ ├── SubtitleUtils.kt
│ │ │ │ ├── SyncUtil.kt
│ │ │ │ ├── TestingUtils.kt
│ │ │ │ ├── TextUtil.kt
│ │ │ │ ├── TvChannelUtils.kt
│ │ │ │ ├── UIHelper.kt
│ │ │ │ ├── Vector2.kt
│ │ │ │ ├── VideoDownloadHelper.kt
│ │ │ │ └── downloader/
│ │ │ │ ├── DownloadFileManagement.kt
│ │ │ │ ├── DownloadManager.kt
│ │ │ │ ├── DownloadObjects.kt
│ │ │ │ ├── DownloadQueueManager.kt
│ │ │ │ └── DownloadUtils.kt
│ │ │ └── widget/
│ │ │ ├── CenterZoomLayoutManager.kt
│ │ │ ├── FlowLayout.kt
│ │ │ └── LinearRecycleViewLayoutManager.kt
│ │ └── res/
│ │ ├── anim/
│ │ │ ├── enter_anim.xml
│ │ │ ├── exit_anim.xml
│ │ │ ├── go_left.xml
│ │ │ ├── go_right.xml
│ │ │ ├── pop_enter.xml
│ │ │ ├── pop_exit.xml
│ │ │ ├── rotate_around_center_point.xml
│ │ │ ├── rotate_left.xml
│ │ │ └── rotate_right.xml
│ │ ├── color/
│ │ │ ├── black_button_ripple.xml
│ │ │ ├── button_selector_color.xml
│ │ │ ├── check_selection_color.xml
│ │ │ ├── chip_color.xml
│ │ │ ├── chip_color_text.xml
│ │ │ ├── color_primary_transparent.xml
│ │ │ ├── item_select_color.xml
│ │ │ ├── item_select_color_tv.xml
│ │ │ ├── player_button_tv.xml
│ │ │ ├── player_on_button_tv.xml
│ │ │ ├── player_on_button_tv_attr.xml
│ │ │ ├── selectable_black.xml
│ │ │ ├── selectable_white.xml
│ │ │ ├── tag_stroke_color.xml
│ │ │ ├── text_selection_color.xml
│ │ │ ├── toggle_button.xml
│ │ │ ├── toggle_button_outline.xml
│ │ │ ├── toggle_button_text.xml
│ │ │ ├── toggle_selector.xml
│ │ │ ├── white_attr_20.xml
│ │ │ └── white_transparent_toggle.xml
│ │ ├── drawable/
│ │ │ ├── arrow_and_edge_24px.xml
│ │ │ ├── arrow_or_edge_24px.xml
│ │ │ ├── arrows_input_24px.xml
│ │ │ ├── background_shadow.xml
│ │ │ ├── baseline_description_24.xml
│ │ │ ├── baseline_downloading_24.xml
│ │ │ ├── baseline_fullscreen_24.xml
│ │ │ ├── baseline_fullscreen_exit_24.xml
│ │ │ ├── baseline_grid_view_24.xml
│ │ │ ├── baseline_headphones_24.xml
│ │ │ ├── baseline_help_outline_24.xml
│ │ │ ├── baseline_list_alt_24.xml
│ │ │ ├── baseline_network_ping_24.xml
│ │ │ ├── baseline_notifications_none_24.xml
│ │ │ ├── baseline_remove_24.xml
│ │ │ ├── baseline_restore_page_24.xml
│ │ │ ├── baseline_save_as_24.xml
│ │ │ ├── baseline_skip_previous_24.xml
│ │ │ ├── baseline_stop_24.xml
│ │ │ ├── baseline_sync_24.xml
│ │ │ ├── baseline_text_snippet_24.xml
│ │ │ ├── baseline_theaters_24.xml
│ │ │ ├── benene.xml
│ │ │ ├── bg_color_both.xml
│ │ │ ├── bg_color_bottom.xml
│ │ │ ├── bg_color_center.xml
│ │ │ ├── bg_color_top.xml
│ │ │ ├── bg_imdb_badge.xml
│ │ │ ├── bookmark_star_24px.xml
│ │ │ ├── circle_shape.xml
│ │ │ ├── circle_shape_dotted.xml
│ │ │ ├── circular_progress_bar.xml
│ │ │ ├── circular_progress_bar_clockwise.xml
│ │ │ ├── circular_progress_bar_counter_clockwise.xml
│ │ │ ├── circular_progress_bar_filled.xml
│ │ │ ├── circular_progress_bar_small_to_large.xml
│ │ │ ├── circular_progress_bar_top_to_bottom.xml
│ │ │ ├── clear_all_24px.xml
│ │ │ ├── cloud_2.xml
│ │ │ ├── cloud_2_gradient.xml
│ │ │ ├── cloud_2_gradient_beta.xml
│ │ │ ├── cloud_2_gradient_beta_old.xml
│ │ │ ├── cloud_2_gradient_debug.xml
│ │ │ ├── cloud_2_solid.xml
│ │ │ ├── custom_rating_bar.xml
│ │ │ ├── dashed_line_horizontal.xml
│ │ │ ├── default_cover.xml
│ │ │ ├── delete_all.xml
│ │ │ ├── dialog__window_background.xml
│ │ │ ├── download_icon_done.xml
│ │ │ ├── download_icon_error.xml
│ │ │ ├── download_icon_load.xml
│ │ │ ├── download_icon_pause.xml
│ │ │ ├── dub_bg_color.xml
│ │ │ ├── episodes_shadow.xml
│ │ │ ├── go_back_30.xml
│ │ │ ├── go_forward_30.xml
│ │ │ ├── home_alt.xml
│ │ │ ├── home_icon_filled_24.xml
│ │ │ ├── home_icon_outline_24.xml
│ │ │ ├── home_icon_selector.xml
│ │ │ ├── hourglass_24.xml
│ │ │ ├── ic_anilist_icon.xml
│ │ │ ├── ic_banner_foreground.xml
│ │ │ ├── ic_baseline_add_24.xml
│ │ │ ├── ic_baseline_arrow_back_24.xml
│ │ │ ├── ic_baseline_arrow_back_ios_24.xml
│ │ │ ├── ic_baseline_arrow_forward_24.xml
│ │ │ ├── ic_baseline_aspect_ratio_24.xml
│ │ │ ├── ic_baseline_autorenew_24.xml
│ │ │ ├── ic_baseline_bookmark_24.xml
│ │ │ ├── ic_baseline_bookmark_border_24.xml
│ │ │ ├── ic_baseline_brightness_1_24.xml
│ │ │ ├── ic_baseline_brightness_2_24.xml
│ │ │ ├── ic_baseline_brightness_3_24.xml
│ │ │ ├── ic_baseline_brightness_4_24.xml
│ │ │ ├── ic_baseline_brightness_5_24.xml
│ │ │ ├── ic_baseline_brightness_6_24.xml
│ │ │ ├── ic_baseline_brightness_7_24.xml
│ │ │ ├── ic_baseline_check_24.xml
│ │ │ ├── ic_baseline_check_24_listview.xml
│ │ │ ├── ic_baseline_clear_24.xml
│ │ │ ├── ic_baseline_close_24.xml
│ │ │ ├── ic_baseline_collections_bookmark_24.xml
│ │ │ ├── ic_baseline_color_lens_24.xml
│ │ │ ├── ic_baseline_construction_24.xml
│ │ │ ├── ic_baseline_delete_outline_24.xml
│ │ │ ├── ic_baseline_developer_mode_24.xml
│ │ │ ├── ic_baseline_discord_24.xml
│ │ │ ├── ic_baseline_dns_24.xml
│ │ │ ├── ic_baseline_edit_24.xml
│ │ │ ├── ic_baseline_equalizer_24.xml
│ │ │ ├── ic_baseline_exit_24.xml
│ │ │ ├── ic_baseline_extension_24.xml
│ │ │ ├── ic_baseline_fast_forward_24.xml
│ │ │ ├── ic_baseline_favorite_24.xml
│ │ │ ├── ic_baseline_favorite_border_24.xml
│ │ │ ├── ic_baseline_film_roll_24.xml
│ │ │ ├── ic_baseline_filter_list_24.xml
│ │ │ ├── ic_baseline_folder_open_24.xml
│ │ │ ├── ic_baseline_hd_24.xml
│ │ │ ├── ic_baseline_hearing_24.xml
│ │ │ ├── ic_baseline_keyboard_arrow_down_24.xml
│ │ │ ├── ic_baseline_keyboard_arrow_left_24.xml
│ │ │ ├── ic_baseline_keyboard_arrow_right_24.xml
│ │ │ ├── ic_baseline_language_24.xml
│ │ │ ├── ic_baseline_more_vert_24.xml
│ │ │ ├── ic_baseline_north_west_24.xml
│ │ │ ├── ic_baseline_notifications_active_24.xml
│ │ │ ├── ic_baseline_ondemand_video_24.xml
│ │ │ ├── ic_baseline_open_in_new_24.xml
│ │ │ ├── ic_baseline_pause_24.xml
│ │ │ ├── ic_baseline_people_24.xml
│ │ │ ├── ic_baseline_picture_in_picture_alt_24.xml
│ │ │ ├── ic_baseline_play_arrow_24.xml
│ │ │ ├── ic_baseline_playlist_play_24.xml
│ │ │ ├── ic_baseline_public_24.xml
│ │ │ ├── ic_baseline_remove_red_eye_24.xml
│ │ │ ├── ic_baseline_replay_24.xml
│ │ │ ├── ic_baseline_restart_24.xml
│ │ │ ├── ic_baseline_resume_arrow.xml
│ │ │ ├── ic_baseline_resume_arrow2.xml
│ │ │ ├── ic_baseline_skip_next_24.xml
│ │ │ ├── ic_baseline_skip_next_24_big.xml
│ │ │ ├── ic_baseline_skip_next_rounded_24.xml
│ │ │ ├── ic_baseline_sort_24.xml
│ │ │ ├── ic_baseline_speed_24.xml
│ │ │ ├── ic_baseline_star_24.xml
│ │ │ ├── ic_baseline_star_border_24.xml
│ │ │ ├── ic_baseline_storage_24.xml
│ │ │ ├── ic_baseline_subtitles_24.xml
│ │ │ ├── ic_baseline_system_update_24.xml
│ │ │ ├── ic_baseline_text_format_24.xml
│ │ │ ├── ic_baseline_thumb_down_24.xml
│ │ │ ├── ic_baseline_thumb_up_24.xml
│ │ │ ├── ic_baseline_touch_app_24.xml
│ │ │ ├── ic_baseline_tune_24.xml
│ │ │ ├── ic_baseline_tv_24.xml
│ │ │ ├── ic_baseline_visibility_off_24.xml
│ │ │ ├── ic_baseline_volume_down_24.xml
│ │ │ ├── ic_baseline_volume_mute_24.xml
│ │ │ ├── ic_baseline_volume_up_24.xml
│ │ │ ├── ic_baseline_warning_24.xml
│ │ │ ├── ic_battery.xml
│ │ │ ├── ic_cloudstream_monochrome.xml
│ │ │ ├── ic_cloudstream_monochrome_big.xml
│ │ │ ├── ic_cloudstreamlogotv.xml
│ │ │ ├── ic_cloudstreamlogotv_2.xml
│ │ │ ├── ic_cloudstreamlogotv_pre.xml
│ │ │ ├── ic_cloudstreamlogotv_pre_2.xml
│ │ │ ├── ic_dashboard_black_24dp.xml
│ │ │ ├── ic_filled_notifications_24dp.xml
│ │ │ ├── ic_fingerprint.xml
│ │ │ ├── ic_github_logo.xml
│ │ │ ├── ic_home_black_24dp.xml
│ │ │ ├── ic_launcher_background.xml
│ │ │ ├── ic_launcher_foreground.xml
│ │ │ ├── ic_mic.xml
│ │ │ ├── ic_network_stream.xml
│ │ │ ├── ic_notifications_black_24dp.xml
│ │ │ ├── ic_offline_pin_24.xml
│ │ │ ├── ic_outline_account_circle_24.xml
│ │ │ ├── ic_outline_home_24.xml
│ │ │ ├── ic_outline_info_24.xml
│ │ │ ├── ic_outline_notifications_24dp.xml
│ │ │ ├── ic_outline_remove_red_eye_24.xml
│ │ │ ├── ic_outline_settings_24.xml
│ │ │ ├── ic_outline_share_24.xml
│ │ │ ├── ic_outline_subtitles_24.xml
│ │ │ ├── ic_outline_voice_over_off_24.xml
│ │ │ ├── ic_refresh.xml
│ │ │ ├── indicator_background.xml
│ │ │ ├── kid_star_24px.xml
│ │ │ ├── kitsu_icon.xml
│ │ │ ├── library_icon.xml
│ │ │ ├── library_icon_filled.xml
│ │ │ ├── library_icon_selector.xml
│ │ │ ├── mal_logo.xml
│ │ │ ├── material_outline_background.xml
│ │ │ ├── monke_benene.xml
│ │ │ ├── monke_burrito.xml
│ │ │ ├── monke_coco.xml
│ │ │ ├── monke_cookie.xml
│ │ │ ├── monke_drink.xml
│ │ │ ├── monke_flusdered.xml
│ │ │ ├── monke_funny.xml
│ │ │ ├── monke_like.xml
│ │ │ ├── monke_party.xml
│ │ │ ├── monke_sob.xml
│ │ │ ├── netflix_download.xml
│ │ │ ├── netflix_download_batch.xml
│ │ │ ├── netflix_pause.xml
│ │ │ ├── netflix_play.xml
│ │ │ ├── netflix_skip_back.xml
│ │ │ ├── netflix_skip_forward.xml
│ │ │ ├── notifications_icon_selector.xml
│ │ │ ├── open_subtitles_icon.xml
│ │ │ ├── outline.xml
│ │ │ ├── outline_big_15_gray.xml
│ │ │ ├── outline_big_20.xml
│ │ │ ├── outline_big_20_gray.xml
│ │ │ ├── outline_big_25_gray.xml
│ │ │ ├── outline_big_35_gray.xml
│ │ │ ├── outline_bookmark_add_24.xml
│ │ │ ├── outline_card.xml
│ │ │ ├── outline_drawable.xml
│ │ │ ├── outline_drawable_forced.xml
│ │ │ ├── outline_drawable_forced_round.xml
│ │ │ ├── outline_drawable_less.xml
│ │ │ ├── outline_drawable_less_inset.xml
│ │ │ ├── outline_drawable_round_20.xml
│ │ │ ├── outline_less.xml
│ │ │ ├── pause_to_play.xml
│ │ │ ├── pin_ic.xml
│ │ │ ├── play_button.xml
│ │ │ ├── play_button_transparent.xml
│ │ │ ├── play_to_pause.xml
│ │ │ ├── player_button_tv.xml
│ │ │ ├── player_button_tv_attr.xml
│ │ │ ├── player_button_tv_attr_no_bg.xml
│ │ │ ├── player_gradient_tv.xml
│ │ │ ├── preview_seekbar_24.xml
│ │ │ ├── progress_drawable_vertical.xml
│ │ │ ├── question_mark_24.xml
│ │ │ ├── quick_novel_icon.xml
│ │ │ ├── rating_bg_color.xml
│ │ │ ├── rating_empty.xml
│ │ │ ├── rating_fill.xml
│ │ │ ├── rddone.xml
│ │ │ ├── rderror.xml
│ │ │ ├── rdload.xml
│ │ │ ├── rdpause.xml
│ │ │ ├── round_keyboard_arrow_up_24.xml
│ │ │ ├── rounded_dialog.xml
│ │ │ ├── rounded_outline.xml
│ │ │ ├── rounded_progress.xml
│ │ │ ├── rounded_select_ripple.xml
│ │ │ ├── screen_rotation.xml
│ │ │ ├── search_background.xml
│ │ │ ├── search_icon.xml
│ │ │ ├── settings_alt.xml
│ │ │ ├── settings_icon_filled.xml
│ │ │ ├── settings_icon_outline.xml
│ │ │ ├── settings_icon_selector.xml
│ │ │ ├── simkl_logo.xml
│ │ │ ├── solid_primary.xml
│ │ │ ├── speedup.xml
│ │ │ ├── splash_background.xml
│ │ │ ├── storage_bar_left.xml
│ │ │ ├── storage_bar_left_box.xml
│ │ │ ├── storage_bar_mid.xml
│ │ │ ├── storage_bar_mid_box.xml
│ │ │ ├── storage_bar_right.xml
│ │ │ ├── storage_bar_right_box.xml
│ │ │ ├── sub_bg_color.xml
│ │ │ ├── subdl_logo_big.xml
│ │ │ ├── subtitles_background_gradient.xml
│ │ │ ├── sun_1.xml
│ │ │ ├── sun_2.xml
│ │ │ ├── sun_3.xml
│ │ │ ├── sun_4.xml
│ │ │ ├── sun_5.xml
│ │ │ ├── sun_6.xml
│ │ │ ├── sun_7.xml
│ │ │ ├── sun_7_24.xml
│ │ │ ├── tab_selector.xml
│ │ │ ├── title_24px.xml
│ │ │ ├── title_shadow.xml
│ │ │ ├── type_bg_color.xml
│ │ │ ├── video_bottom_button.xml
│ │ │ ├── video_frame.xml
│ │ │ ├── video_locked.xml
│ │ │ ├── video_outline.xml
│ │ │ ├── video_pause.xml
│ │ │ ├── video_play.xml
│ │ │ ├── video_tap_button.xml
│ │ │ ├── video_tap_button_always_white.xml
│ │ │ ├── video_tap_button_skip.xml
│ │ │ └── video_unlocked.xml
│ │ ├── drawable-v24/
│ │ │ ├── ic_banner_background.xml
│ │ │ ├── ic_banner_foreground.xml
│ │ │ └── ic_launcher_foreground.xml
│ │ ├── font/
│ │ │ └── google_sans.xml
│ │ ├── layout/
│ │ │ ├── account_edit_dialog.xml
│ │ │ ├── account_list_item.xml
│ │ │ ├── account_list_item_add.xml
│ │ │ ├── account_list_item_edit.xml
│ │ │ ├── account_managment.xml
│ │ │ ├── account_select_linear.xml
│ │ │ ├── account_single.xml
│ │ │ ├── account_switch.xml
│ │ │ ├── activity_account_select.xml
│ │ │ ├── activity_main.xml
│ │ │ ├── activity_main_tv.xml
│ │ │ ├── add_account_input.xml
│ │ │ ├── add_remove_sites.xml
│ │ │ ├── add_repo_input.xml
│ │ │ ├── add_site_input.xml
│ │ │ ├── bottom_input_dialog.xml
│ │ │ ├── bottom_loading.xml
│ │ │ ├── bottom_resultview_preview.xml
│ │ │ ├── bottom_resultview_preview_tv.xml
│ │ │ ├── bottom_selection_dialog.xml
│ │ │ ├── bottom_selection_dialog_direct.xml
│ │ │ ├── bottom_text_dialog.xml
│ │ │ ├── cast_item.xml
│ │ │ ├── chromecast_subtitle_settings.xml
│ │ │ ├── confirm_exit_dialog.xml
│ │ │ ├── custom_preference_category_material.xml
│ │ │ ├── custom_preference_material.xml
│ │ │ ├── custom_preference_widget_seekbar.xml
│ │ │ ├── device_auth.xml
│ │ │ ├── dialog_loading.xml
│ │ │ ├── dialog_online_subtitles.xml
│ │ │ ├── download_button.xml
│ │ │ ├── download_button_layout.xml
│ │ │ ├── download_button_view.xml
│ │ │ ├── download_child_episode.xml
│ │ │ ├── download_header_episode.xml
│ │ │ ├── download_queue_item.xml
│ │ │ ├── empty_layout.xml
│ │ │ ├── extra_brightness_overlay.xml
│ │ │ ├── fragment_child_downloads.xml
│ │ │ ├── fragment_download_queue.xml
│ │ │ ├── fragment_downloads.xml
│ │ │ ├── fragment_easter_egg_monke.xml
│ │ │ ├── fragment_extensions.xml
│ │ │ ├── fragment_home.xml
│ │ │ ├── fragment_home_head.xml
│ │ │ ├── fragment_home_head_tv.xml
│ │ │ ├── fragment_home_tv.xml
│ │ │ ├── fragment_library.xml
│ │ │ ├── fragment_library_tv.xml
│ │ │ ├── fragment_player.xml
│ │ │ ├── fragment_player_tv.xml
│ │ │ ├── fragment_plugin_details.xml
│ │ │ ├── fragment_plugins.xml
│ │ │ ├── fragment_result.xml
│ │ │ ├── fragment_result_swipe.xml
│ │ │ ├── fragment_result_tv.xml
│ │ │ ├── fragment_search.xml
│ │ │ ├── fragment_search_tv.xml
│ │ │ ├── fragment_setup_extensions.xml
│ │ │ ├── fragment_setup_language.xml
│ │ │ ├── fragment_setup_layout.xml
│ │ │ ├── fragment_setup_media.xml
│ │ │ ├── fragment_setup_provider_languages.xml
│ │ │ ├── fragment_testing.xml
│ │ │ ├── fragment_trailer.xml
│ │ │ ├── fragment_webview.xml
│ │ │ ├── home_episodes_expanded.xml
│ │ │ ├── home_remove_grid.xml
│ │ │ ├── home_remove_grid_expanded.xml
│ │ │ ├── home_result_big_grid.xml
│ │ │ ├── home_result_grid.xml
│ │ │ ├── home_result_grid_expanded.xml
│ │ │ ├── home_scroll_view.xml
│ │ │ ├── home_scroll_view_tv.xml
│ │ │ ├── home_select_mainpage.xml
│ │ │ ├── homepage_parent.xml
│ │ │ ├── homepage_parent_emulator.xml
│ │ │ ├── homepage_parent_tv.xml
│ │ │ ├── item_logcat.xml
│ │ │ ├── library_viewpager_page.xml
│ │ │ ├── loading_downloads.xml
│ │ │ ├── loading_episode.xml
│ │ │ ├── loading_line.xml
│ │ │ ├── loading_line_short.xml
│ │ │ ├── loading_line_short_center.xml
│ │ │ ├── loading_list.xml
│ │ │ ├── loading_poster.xml
│ │ │ ├── loading_poster_dynamic.xml
│ │ │ ├── lock_pin_dialog.xml
│ │ │ ├── logcat.xml
│ │ │ ├── main_settings.xml
│ │ │ ├── options_popup_tv.xml
│ │ │ ├── player_custom_layout.xml
│ │ │ ├── player_custom_layout_tv.xml
│ │ │ ├── player_prioritize_item.xml
│ │ │ ├── player_quality_profile_dialog.xml
│ │ │ ├── player_quality_profile_item.xml
│ │ │ ├── player_select_source_and_subs.xml
│ │ │ ├── player_select_source_priority.xml
│ │ │ ├── player_select_tracks.xml
│ │ │ ├── provider_list.xml
│ │ │ ├── provider_test_item.xml
│ │ │ ├── quick_search.xml
│ │ │ ├── rail_footer.xml
│ │ │ ├── rail_header.xml
│ │ │ ├── repository_item.xml
│ │ │ ├── repository_item_tv.xml
│ │ │ ├── result_episode.xml
│ │ │ ├── result_episode_large.xml
│ │ │ ├── result_mini_image.xml
│ │ │ ├── result_poster.xml
│ │ │ ├── result_recommendations.xml
│ │ │ ├── result_selection.xml
│ │ │ ├── result_sync.xml
│ │ │ ├── result_tag.xml
│ │ │ ├── search_history_footer.xml
│ │ │ ├── search_history_item.xml
│ │ │ ├── search_result_compact.xml
│ │ │ ├── search_result_grid.xml
│ │ │ ├── search_result_grid_expanded.xml
│ │ │ ├── search_result_super_compact.xml
│ │ │ ├── search_suggestion_footer.xml
│ │ │ ├── search_suggestion_item.xml
│ │ │ ├── settings_title_top.xml
│ │ │ ├── sort_bottom_footer_add_choice.xml
│ │ │ ├── sort_bottom_sheet.xml
│ │ │ ├── sort_bottom_single_choice.xml
│ │ │ ├── sort_bottom_single_choice_color.xml
│ │ │ ├── sort_bottom_single_choice_double_text.xml
│ │ │ ├── sort_bottom_single_choice_no_checkmark.xml
│ │ │ ├── sort_bottom_single_provider_choice.xml
│ │ │ ├── speed_dialog.xml
│ │ │ ├── standard_toolbar.xml
│ │ │ ├── stream_input.xml
│ │ │ ├── subtitle_offset.xml
│ │ │ ├── subtitle_offset_item.xml
│ │ │ ├── subtitle_settings.xml
│ │ │ ├── subtitle_settings_dialog.xml
│ │ │ ├── toast.xml
│ │ │ ├── trailer_custom_layout.xml
│ │ │ ├── tvtypes_chips.xml
│ │ │ ├── tvtypes_chips_scroll.xml
│ │ │ └── view_test.xml
│ │ ├── layout-port/
│ │ │ ├── player_select_source_and_subs.xml
│ │ │ ├── player_select_source_priority.xml
│ │ │ └── subtitle_offset.xml
│ │ ├── menu/
│ │ │ ├── bottom_nav_menu.xml
│ │ │ ├── cast_expanded_controller_menu.xml
│ │ │ ├── download_queue.xml
│ │ │ ├── library_menu.xml
│ │ │ └── repository.xml
│ │ ├── mipmap-anydpi-v26/
│ │ │ ├── ic_banner.xml
│ │ │ ├── ic_launcher.xml
│ │ │ └── ic_launcher_round.xml
│ │ ├── navigation/
│ │ │ └── mobile_navigation.xml
│ │ ├── values/
│ │ │ ├── array.xml
│ │ │ ├── attrs.xml
│ │ │ ├── colors.xml
│ │ │ ├── dimens.xml
│ │ │ ├── donottranslate-strings.xml
│ │ │ ├── ic_launcher_background.xml
│ │ │ ├── strings.xml
│ │ │ └── styles.xml
│ │ ├── values-arz/
│ │ │ └── strings.xml
│ │ ├── values-b+af/
│ │ │ └── strings.xml
│ │ ├── values-b+am/
│ │ │ └── strings.xml
│ │ ├── values-b+apc/
│ │ │ └── strings.xml
│ │ ├── values-b+ar/
│ │ │ └── strings.xml
│ │ ├── values-b+ars/
│ │ │ └── strings.xml
│ │ ├── values-b+as/
│ │ │ └── strings.xml
│ │ ├── values-b+az/
│ │ │ └── strings.xml
│ │ ├── values-b+bg/
│ │ │ └── strings.xml
│ │ ├── values-b+bn/
│ │ │ └── strings.xml
│ │ ├── values-b+ckb/
│ │ │ └── strings.xml
│ │ ├── values-b+cs/
│ │ │ └── strings.xml
│ │ ├── values-b+de/
│ │ │ └── strings.xml
│ │ ├── values-b+el/
│ │ │ └── strings.xml
│ │ ├── values-b+eo/
│ │ │ └── strings.xml
│ │ ├── values-b+es/
│ │ │ ├── array.xml
│ │ │ └── strings.xml
│ │ ├── values-b+fa/
│ │ │ └── strings.xml
│ │ ├── values-b+fil/
│ │ │ └── strings.xml
│ │ ├── values-b+fr/
│ │ │ └── strings.xml
│ │ ├── values-b+gl/
│ │ │ └── strings.xml
│ │ ├── values-b+hi/
│ │ │ └── strings.xml
│ │ ├── values-b+hr/
│ │ │ └── strings.xml
│ │ ├── values-b+hu/
│ │ │ └── strings.xml
│ │ ├── values-b+in/
│ │ │ └── strings.xml
│ │ ├── values-b+it/
│ │ │ └── strings.xml
│ │ ├── values-b+iw/
│ │ │ └── strings.xml
│ │ ├── values-b+ja/
│ │ │ └── strings.xml
│ │ ├── values-b+kn/
│ │ │ └── strings.xml
│ │ ├── values-b+ko/
│ │ │ └── strings.xml
│ │ ├── values-b+lt/
│ │ │ └── strings.xml
│ │ ├── values-b+lv/
│ │ │ └── strings.xml
│ │ ├── values-b+mk/
│ │ │ └── strings.xml
│ │ ├── values-b+ml/
│ │ │ └── strings.xml
│ │ ├── values-b+ms/
│ │ │ └── strings.xml
│ │ ├── values-b+mt/
│ │ │ └── strings.xml
│ │ ├── values-b+my/
│ │ │ └── strings.xml
│ │ ├── values-b+ne/
│ │ │ └── strings.xml
│ │ ├── values-b+nl/
│ │ │ └── strings.xml
│ │ ├── values-b+nn/
│ │ │ └── strings.xml
│ │ ├── values-b+no/
│ │ │ └── strings.xml
│ │ ├── values-b+or/
│ │ │ └── strings.xml
│ │ ├── values-b+pl/
│ │ │ ├── array.xml
│ │ │ └── strings.xml
│ │ ├── values-b+pt/
│ │ │ └── strings.xml
│ │ ├── values-b+pt+BR/
│ │ │ └── strings.xml
│ │ ├── values-b+qt/
│ │ │ └── strings.xml
│ │ ├── values-b+ro/
│ │ │ └── strings.xml
│ │ ├── values-b+ru/
│ │ │ └── strings.xml
│ │ ├── values-b+sk/
│ │ │ └── strings.xml
│ │ ├── values-b+so/
│ │ │ └── strings.xml
│ │ ├── values-b+sv/
│ │ │ └── strings.xml
│ │ ├── values-b+ta/
│ │ │ └── strings.xml
│ │ ├── values-b+ti/
│ │ │ └── strings.xml
│ │ ├── values-b+tl/
│ │ │ └── strings.xml
│ │ ├── values-b+tr/
│ │ │ ├── array.xml
│ │ │ └── strings.xml
│ │ ├── values-b+uk/
│ │ │ └── strings.xml
│ │ ├── values-b+ur/
│ │ │ └── strings.xml
│ │ ├── values-b+vi/
│ │ │ ├── array.xml
│ │ │ └── strings.xml
│ │ ├── values-b+zh/
│ │ │ └── strings.xml
│ │ ├── values-b+zh+TW/
│ │ │ └── strings.xml
│ │ ├── values-be/
│ │ │ └── strings.xml
│ │ ├── values-ca/
│ │ │ └── strings.xml
│ │ └── xml/
│ │ ├── backup_descriptor.xml
│ │ ├── data_extraction_rules.xml
│ │ ├── provider_paths.xml
│ │ ├── settings_account.xml
│ │ ├── settings_general.xml
│ │ ├── settings_player.xml
│ │ ├── settings_providers.xml
│ │ ├── settings_ui.xml
│ │ └── settings_updates.xml
│ ├── prerelease/
│ │ └── res/
│ │ ├── drawable/
│ │ │ └── ic_banner_foreground.xml
│ │ ├── drawable-v24/
│ │ │ ├── ic_banner_background.xml
│ │ │ └── ic_launcher_foreground.xml
│ │ ├── mipmap-anydpi-v26/
│ │ │ ├── ic_banner.xml
│ │ │ ├── ic_launcher.xml
│ │ │ └── ic_launcher_round.xml
│ │ └── values/
│ │ ├── ic_launcher_background.xml
│ │ └── strings.xml
│ └── test/
│ └── java/
│ └── com/
│ └── lagradost/
│ └── cloudstream3/
│ ├── ProviderTests.kt
│ └── SubtitleSelectionTest.kt
├── build.gradle.kts
├── discoverium.yml
├── docs/
│ ├── .gitignore
│ └── build.gradle.kts
├── fastlane/
│ └── metadata/
│ └── android/
│ ├── af/
│ │ ├── changelogs/
│ │ │ └── 2.txt
│ │ ├── full_description.txt
│ │ ├── short_description.txt
│ │ └── title.txt
│ ├── am/
│ │ ├── changelogs/
│ │ │ └── 2.txt
│ │ ├── full_description.txt
│ │ ├── short_description.txt
│ │ └── title.txt
│ ├── apc/
│ │ ├── changelogs/
│ │ │ └── 2.txt
│ │ ├── full_description.txt
│ │ ├── short_description.txt
│ │ └── title.txt
│ ├── ar/
│ │ ├── changelogs/
│ │ │ └── 2.txt
│ │ ├── full_description.txt
│ │ ├── short_description.txt
│ │ └── title.txt
│ ├── ar-SA/
│ │ ├── changelogs/
│ │ │ └── 2.txt
│ │ ├── full_description.txt
│ │ ├── short_description.txt
│ │ └── title.txt
│ ├── as/
│ │ ├── changelogs/
│ │ │ └── 2.txt
│ │ ├── full_description.txt
│ │ ├── short_description.txt
│ │ └── title.txt
│ ├── be/
│ │ ├── changelogs/
│ │ │ └── 2.txt
│ │ ├── full_description.txt
│ │ ├── short_description.txt
│ │ └── title.txt
│ ├── bg/
│ │ ├── changelogs/
│ │ │ └── 2.txt
│ │ ├── full_description.txt
│ │ ├── short_description.txt
│ │ └── title.txt
│ ├── ca/
│ │ ├── changelogs/
│ │ │ └── 2.txt
│ │ ├── full_description.txt
│ │ ├── short_description.txt
│ │ └── title.txt
│ ├── ckb/
│ │ ├── changelogs/
│ │ │ └── 2.txt
│ │ ├── full_description.txt
│ │ ├── short_description.txt
│ │ └── title.txt
│ ├── cs-CZ/
│ │ ├── changelogs/
│ │ │ └── 2.txt
│ │ ├── full_description.txt
│ │ ├── short_description.txt
│ │ └── title.txt
│ ├── de-DE/
│ │ ├── changelogs/
│ │ │ └── 2.txt
│ │ ├── full_description.txt
│ │ ├── short_description.txt
│ │ └── title.txt
│ ├── el-GR/
│ │ ├── changelogs/
│ │ │ └── 2.txt
│ │ ├── full_description.txt
│ │ ├── short_description.txt
│ │ └── title.txt
│ ├── en-US/
│ │ ├── changelogs/
│ │ │ └── 2.txt
│ │ ├── full_description.txt
│ │ ├── short_description.txt
│ │ └── title.txt
│ ├── es-AR/
│ │ ├── changelogs/
│ │ │ └── 2.txt
│ │ ├── full_description.txt
│ │ ├── short_description.txt
│ │ └── title.txt
│ ├── es-ES/
│ │ ├── changelogs/
│ │ │ └── 2.txt
│ │ ├── full_description.txt
│ │ ├── short_description.txt
│ │ └── title.txt
│ ├── fa-IR/
│ │ ├── changelogs/
│ │ │ └── 2.txt
│ │ ├── full_description.txt
│ │ ├── short_description.txt
│ │ └── title.txt
│ ├── fr-FR/
│ │ ├── changelogs/
│ │ │ └── 2.txt
│ │ ├── full_description.txt
│ │ ├── short_description.txt
│ │ └── title.txt
│ ├── hi-IN/
│ │ ├── changelogs/
│ │ │ └── 2.txt
│ │ ├── full_description.txt
│ │ ├── short_description.txt
│ │ └── title.txt
│ ├── hr/
│ │ ├── changelogs/
│ │ │ └── 2.txt
│ │ ├── full_description.txt
│ │ ├── short_description.txt
│ │ └── title.txt
│ ├── hu-HU/
│ │ ├── changelogs/
│ │ │ └── 2.txt
│ │ ├── full_description.txt
│ │ ├── short_description.txt
│ │ └── title.txt
│ ├── id/
│ │ ├── changelogs/
│ │ │ └── 2.txt
│ │ ├── full_description.txt
│ │ ├── short_description.txt
│ │ └── title.txt
│ ├── it-IT/
│ │ ├── changelogs/
│ │ │ └── 2.txt
│ │ ├── full_description.txt
│ │ ├── short_description.txt
│ │ └── title.txt
│ ├── ja-JP/
│ │ ├── changelogs/
│ │ │ └── 2.txt
│ │ ├── full_description.txt
│ │ ├── short_description.txt
│ │ └── title.txt
│ ├── ko-KR/
│ │ ├── changelogs/
│ │ │ └── 2.txt
│ │ ├── full_description.txt
│ │ ├── short_description.txt
│ │ └── title.txt
│ ├── lt/
│ │ ├── changelogs/
│ │ │ └── 2.txt
│ │ ├── full_description.txt
│ │ ├── short_description.txt
│ │ └── title.txt
│ ├── lv/
│ │ ├── changelogs/
│ │ │ └── 2.txt
│ │ ├── full_description.txt
│ │ ├── short_description.txt
│ │ └── title.txt
│ ├── mk-MK/
│ │ ├── changelogs/
│ │ │ └── 2.txt
│ │ ├── full_description.txt
│ │ ├── short_description.txt
│ │ └── title.txt
│ ├── ml-IN/
│ │ ├── changelogs/
│ │ │ └── 2.txt
│ │ ├── full_description.txt
│ │ ├── short_description.txt
│ │ └── title.txt
│ ├── mt/
│ │ ├── changelogs/
│ │ │ └── 2.txt
│ │ ├── full_description.txt
│ │ ├── short_description.txt
│ │ └── title.txt
│ ├── nl-NL/
│ │ ├── short_description.txt
│ │ └── title.txt
│ ├── no-NO/
│ │ ├── changelogs/
│ │ │ └── 2.txt
│ │ ├── full_description.txt
│ │ ├── short_description.txt
│ │ └── title.txt
│ ├── or/
│ │ └── changelogs/
│ │ └── 2.txt
│ ├── pa/
│ │ ├── changelogs/
│ │ │ └── 2.txt
│ │ ├── full_description.txt
│ │ ├── short_description.txt
│ │ └── title.txt
│ ├── pl-PL/
│ │ ├── changelogs/
│ │ │ └── 2.txt
│ │ ├── full_description.txt
│ │ ├── short_description.txt
│ │ └── title.txt
│ ├── pt/
│ │ ├── changelogs/
│ │ │ └── 2.txt
│ │ ├── full_description.txt
│ │ ├── short_description.txt
│ │ └── title.txt
│ ├── pt-BR/
│ │ ├── changelogs/
│ │ │ └── 2.txt
│ │ ├── full_description.txt
│ │ ├── short_description.txt
│ │ └── title.txt
│ ├── ro/
│ │ ├── changelogs/
│ │ │ └── 2.txt
│ │ ├── full_description.txt
│ │ ├── short_description.txt
│ │ └── title.txt
│ ├── ru-RU/
│ │ ├── changelogs/
│ │ │ └── 2.txt
│ │ ├── full_description.txt
│ │ ├── short_description.txt
│ │ └── title.txt
│ ├── sk/
│ │ ├── changelogs/
│ │ │ └── 2.txt
│ │ ├── full_description.txt
│ │ ├── short_description.txt
│ │ └── title.txt
│ ├── sv-SE/
│ │ ├── changelogs/
│ │ │ └── 2.txt
│ │ ├── full_description.txt
│ │ ├── short_description.txt
│ │ └── title.txt
│ ├── ta-IN/
│ │ ├── changelogs/
│ │ │ └── 2.txt
│ │ ├── full_description.txt
│ │ ├── short_description.txt
│ │ └── title.txt
│ ├── tr-TR/
│ │ ├── changelogs/
│ │ │ └── 2.txt
│ │ ├── full_description.txt
│ │ ├── short_description.txt
│ │ └── title.txt
│ ├── uk/
│ │ ├── changelogs/
│ │ │ └── 2.txt
│ │ ├── full_description.txt
│ │ ├── short_description.txt
│ │ └── title.txt
│ ├── ur/
│ │ ├── changelogs/
│ │ │ └── 2.txt
│ │ ├── full_description.txt
│ │ ├── short_description.txt
│ │ └── title.txt
│ ├── vi/
│ │ ├── changelogs/
│ │ │ └── 2.txt
│ │ ├── full_description.txt
│ │ ├── short_description.txt
│ │ └── title.txt
│ ├── zh-CN/
│ │ ├── changelogs/
│ │ │ └── 2.txt
│ │ ├── full_description.txt
│ │ ├── short_description.txt
│ │ └── title.txt
│ └── zh-TW/
│ ├── changelogs/
│ │ └── 2.txt
│ ├── full_description.txt
│ ├── short_description.txt
│ └── title.txt
├── gradle/
│ ├── libs.versions.toml
│ └── wrapper/
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradle.properties
├── gradlew
├── gradlew.bat
├── jitpack.yml
├── library/
│ ├── .gitignore
│ ├── build.gradle.kts
│ ├── lint.xml
│ └── src/
│ ├── androidMain/
│ │ ├── AndroidManifest.xml
│ │ └── kotlin/
│ │ └── com/
│ │ └── lagradost/
│ │ ├── api/
│ │ │ ├── ContextHelper.android.kt
│ │ │ └── Log.kt
│ │ └── cloudstream3/
│ │ ├── network/
│ │ │ └── WebViewResolver.android.kt
│ │ └── utils/
│ │ └── Coroutines.android.kt
│ ├── commonMain/
│ │ └── kotlin/
│ │ └── com/
│ │ └── lagradost/
│ │ ├── api/
│ │ │ ├── ContextHelper.kt
│ │ │ └── Log.kt
│ │ └── cloudstream3/
│ │ ├── MainAPI.kt
│ │ ├── MainActivity.kt
│ │ ├── ParCollections.kt
│ │ ├── extractors/
│ │ │ ├── Acefile.kt
│ │ │ ├── Bigwarp.kt
│ │ │ ├── Blogger.kt
│ │ │ ├── ByseSX.kt
│ │ │ ├── Cda.kt
│ │ │ ├── CineMMRedirect.kt
│ │ │ ├── CloudMailRuExtractor.kt
│ │ │ ├── ContentXExtractor.kt
│ │ │ ├── Dailymotion.kt
│ │ │ ├── DoodExtractor.kt
│ │ │ ├── Embedgram.kt
│ │ │ ├── EmturbovidExtractor.kt
│ │ │ ├── Evolaod.kt
│ │ │ ├── Fastream.kt
│ │ │ ├── Filemoon.kt
│ │ │ ├── Filesim.kt
│ │ │ ├── GDMirrorbot.kt
│ │ │ ├── GUpload.kt
│ │ │ ├── GamoVideo.kt
│ │ │ ├── Gdriveplayer.kt
│ │ │ ├── GenericM3U8.kt
│ │ │ ├── Gofile.kt
│ │ │ ├── GoodstreamExtractor.kt
│ │ │ ├── HDMomPlayerExtractor.kt
│ │ │ ├── HDPlayerSystemExtractor.kt
│ │ │ ├── HDStreamAbleExtractor.kt
│ │ │ ├── HotlingerExtractor.kt
│ │ │ ├── HubCloud.kt
│ │ │ ├── Hxfile.kt
│ │ │ ├── InternetArchive.kt
│ │ │ ├── JWPlayer.kt
│ │ │ ├── Jeniusplay.kt
│ │ │ ├── Krakenfiles.kt
│ │ │ ├── Linkbox.kt
│ │ │ ├── LuluStream.kt
│ │ │ ├── M3u8Manifest.kt
│ │ │ ├── MailRuExtractor.kt
│ │ │ ├── Maxstream.kt
│ │ │ ├── Mediafire.kt
│ │ │ ├── Minoplres.kt
│ │ │ ├── MixDrop.kt
│ │ │ ├── Moviehab.kt
│ │ │ ├── Mp4Upload.kt
│ │ │ ├── MultiQuality.kt
│ │ │ ├── Mvidoo.kt
│ │ │ ├── OdnoklassnikiExtractor.kt
│ │ │ ├── OkRuExtractor.kt
│ │ │ ├── PeaceMakerstExtractor.kt
│ │ │ ├── Pelisplus.kt
│ │ │ ├── PixelDrainExtractor.kt
│ │ │ ├── PlayLtXyz.kt
│ │ │ ├── PlayerVoxzer.kt
│ │ │ ├── Rabbitstream.kt
│ │ │ ├── RapidVidExtractor.kt
│ │ │ ├── SBPlay.kt
│ │ │ ├── SecvideoOnline.kt
│ │ │ ├── Sendvid.kt
│ │ │ ├── SibNetExtractor.kt
│ │ │ ├── SobreatsesuypExtractor.kt
│ │ │ ├── StreamEmbed.kt
│ │ │ ├── StreamSB.kt
│ │ │ ├── StreamSilk.kt
│ │ │ ├── StreamTape.kt
│ │ │ ├── StreamWishExtractor.kt
│ │ │ ├── Streamhub.kt
│ │ │ ├── Streamlare.kt
│ │ │ ├── StreamoUpload.kt
│ │ │ ├── Streamplay.kt
│ │ │ ├── Streamup.kt
│ │ │ ├── Supervideo.kt
│ │ │ ├── TRsTXExtractor.kt
│ │ │ ├── Tantifilm.kt
│ │ │ ├── TauVideoExtractor.kt
│ │ │ ├── Up4Stream.kt
│ │ │ ├── UpstreamExtractor.kt
│ │ │ ├── Uqload.kt
│ │ │ ├── Userload.kt
│ │ │ ├── Userscloud.kt
│ │ │ ├── Uservideo.kt
│ │ │ ├── Vicloud.kt
│ │ │ ├── VidHidePro.kt
│ │ │ ├── VidMoxyExtractor.kt
│ │ │ ├── VidNest.kt
│ │ │ ├── VidStack.kt
│ │ │ ├── Videa.kt
│ │ │ ├── VideoSeyredExtractor.kt
│ │ │ ├── VidhideExtractor.kt
│ │ │ ├── Vidmoly.kt
│ │ │ ├── Vido.kt
│ │ │ ├── Vidoza.kt
│ │ │ ├── Vidsonic.kt
│ │ │ ├── Vidstream.kt
│ │ │ ├── Vinovo.kt
│ │ │ ├── VkExtractor.kt
│ │ │ ├── Voe.kt
│ │ │ ├── Vtbe.kt
│ │ │ ├── WatchSB.kt
│ │ │ ├── Wibufile.kt
│ │ │ ├── XStreamCdn.kt
│ │ │ ├── YourUpload.kt
│ │ │ ├── YoutubeExtractor.kt
│ │ │ ├── Zplayer.kt
│ │ │ └── helper/
│ │ │ ├── AesHelper.kt
│ │ │ ├── AsianEmbedHelper.kt
│ │ │ ├── CryptoJSHelper.kt
│ │ │ ├── GogoHelper.kt
│ │ │ ├── NineAnimeHelper.kt
│ │ │ ├── VstreamhubHelper.kt
│ │ │ └── WcoHelper.kt
│ │ ├── metaproviders/
│ │ │ ├── CrossTmdbProvider.kt
│ │ │ ├── MyDramaList.kt
│ │ │ ├── SyncRedirector.kt
│ │ │ ├── TmdbProvider.kt
│ │ │ └── TraktProvider.kt
│ │ ├── mvvm/
│ │ │ └── ArchComponentExt.kt
│ │ ├── network/
│ │ │ └── WebViewResolver.kt
│ │ ├── plugins/
│ │ │ ├── BasePlugin.kt
│ │ │ └── CloudstreamPlugin.kt
│ │ ├── syncproviders/
│ │ │ └── SyncAPI.kt
│ │ └── utils/
│ │ ├── AppDebug.kt
│ │ ├── AppUtils.kt
│ │ ├── Coroutines.kt
│ │ ├── ExtractorApi.kt
│ │ ├── HlsPlaylistParser.kt
│ │ ├── JsHunter.kt
│ │ ├── JsUnpacker.kt
│ │ ├── M3u8Helper.kt
│ │ ├── StringUtils.kt
│ │ ├── SubtitleHelper.kt
│ │ └── UnshortenUrl.kt
│ └── jvmMain/
│ └── kotlin/
│ └── com/
│ └── lagradost/
│ ├── api/
│ │ ├── ContextHelper.jvm.kt
│ │ └── Log.kt
│ └── cloudstream3/
│ ├── network/
│ │ └── WebViewResolver.jvm.kt
│ └── utils/
│ └── Coroutines.jvm.kt
└── settings.gradle.kts
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/ISSUE_TEMPLATE/application-bug.yml
================================================
name: 🐞 Application Issue Report
description: Report a issue in CloudStream
labels: [bug]
body:
- type: textarea
id: reproduce-steps
attributes:
label: Steps to reproduce
description: Provide an example of the issue.
placeholder: |
Example:
1. First step
2. Second step
3. Issue here
validations:
required: true
- type: textarea
id: expected-behavior
attributes:
label: Expected behavior
placeholder: |
Example:
"This should happen..."
validations:
required: true
- type: textarea
id: actual-behavior
attributes:
label: Actual behavior
placeholder: |
Example:
"This happened instead..."
validations:
required: true
- type: input
id: cloudstream-version
attributes:
label: Cloudstream version and commit hash
description: |
You can find your Cloudstream version in **Settings**. Commit hash is the 7 character string next to the version.
placeholder: |
Example: "2.8.16 a49f466"
validations:
required: true
- type: input
id: android-version
attributes:
label: Android version
description: |
You can find this somewhere in your Android settings.
placeholder: |
Example: "Android 12"
validations:
required: true
- type: textarea
id: logcat
attributes:
label: Logcat
placeholder: |
To get logcat please go to Settings > Updates and backup > Show logcat 🐈.
You can attach a file or link to some pastebin service if the file is too big.
render: java
- type: textarea
id: other-details
attributes:
label: Other details
placeholder: |
Additional details and attachments.
- type: checkboxes
id: acknowledgements
attributes:
label: Acknowledgements
description: Your issue will be closed if you haven't done these steps.
options:
- label: I am sure my issue is related to the app and **NOT some extension**.
required: true
- label: I have searched the existing issues and this is a new ticket, **NOT** a duplicate or related to another open issue.
required: true
- label: I have written a short but informative title.
required: true
- label: I have updated the app to pre-release version **[Latest](https://github.com/recloudstream/cloudstream/releases)**.
required: true
- label: I will fill out all of the requested information in this form.
required: true
================================================
FILE: .github/ISSUE_TEMPLATE/config.yml
================================================
blank_issues_enabled: false
contact_links:
- name: Request a new provider or report bug with an existing provider
url: https://github.com/recloudstream
about: EXTREMELY IMPORTANT - Please do not report any provider bugs here or request new providers. This repository does not contain any providers. Please find the appropriate repository and report your issue there or join the discord.
- name: Discord
url: https://discord.gg/5Hus6fM
about: Join our discord for faster support on smaller issues.
================================================
FILE: .github/ISSUE_TEMPLATE/feature-request.yml
================================================
name: ⭐ Feature request
description: Suggest a feature to improve the app
labels: [enhancement]
body:
- type: textarea
id: feature-description
attributes:
label: Describe your suggested feature
description: How can an existing source be improved?
placeholder: |
Example:
"It should work like this..."
validations:
required: true
- type: textarea
id: other-details
attributes:
label: Other details
placeholder: |
Additional details and attachments.
- type: checkboxes
id: acknowledgements
attributes:
label: Acknowledgements
description: Your issue will be closed if you haven't done these steps.
options:
- label: My suggestion is **NOT** about adding a new provider
required: true
- label: I have searched the existing issues and this is a new ticket, **NOT** a duplicate or related to another open issue.
required: true
================================================
FILE: .github/locales.py
================================================
import re
import glob
import requests
import lxml.etree as ET # builtin library doesn't preserve comments
SETTINGS_PATH = "app/src/main/java/com/lagradost/cloudstream3/ui/settings/SettingsGeneral.kt"
START_MARKER = "/* begin language list */"
END_MARKER = "/* end language list */"
XML_NAME = "app/src/main/res/values-b+"
ISO_MAP_URL = "https://raw.githubusercontent.com/haliaeetus/iso-639/master/data/iso_639-1.min.json"
INDENT = " "*4
iso_map = requests.get(ISO_MAP_URL, timeout=300).json()
# Load settings file
src = open(SETTINGS_PATH, "r", encoding='utf-8').read()
before_src, rest = src.split(START_MARKER)
rest, after_src = rest.split(END_MARKER)
# Load already added langs
languages = {}
for lang in re.finditer(r'Pair\("(.*)", "(.*)"\)', rest):
name, iso = lang.groups()
languages[iso] = name
# Add not yet added langs
for folder in glob.glob(f"{XML_NAME}*"):
iso = folder[len(XML_NAME):].replace("+", "-")
if iso not in languages.keys():
entry = iso_map.get(iso.lower(), {'nativeName':iso}) # fallback to iso code if not found
languages[iso] = entry['nativeName'].split(',')[0] # first name if there are multiple
# Create pairs
pairs = []
for iso in sorted(languages, key=lambda iso: languages[iso].lower()): # sort by language name
name = languages[iso]
pairs.append(f'{INDENT}Pair("{name}", "{iso}"),')
# Update settings file
open(SETTINGS_PATH, "w+",encoding='utf-8').write(
before_src +
START_MARKER +
"\n" +
"\n".join(pairs) +
"\n" +
END_MARKER +
after_src
)
# Go through each values.xml file and fix escaped \@string
for file in glob.glob(f"{XML_NAME}*/strings.xml"):
try:
tree = ET.parse(file)
for child in tree.getroot():
if not child.text:
continue
if child.text.startswith("\\@string/"):
print(f"[{file}] fixing {child.attrib['name']}")
child.text = child.text.replace("\\@string/", "@string/")
with open(file, 'wb') as fp:
fp.write(b'\n')
tree.write(fp, encoding="utf-8", method="xml", pretty_print=True, xml_declaration=False)
except ET.ParseError as ex:
print(f"[{file}] {ex}")
================================================
FILE: .github/workflows/build_to_archive.yml
================================================
name: Archive build
on:
push:
branches: [ master ]
paths-ignore:
- '*.md'
- '*.json'
- '**/wcokey.txt'
workflow_dispatch:
concurrency:
group: "Archive-build"
cancel-in-progress: true
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Generate access token
id: generate_token
uses: tibdex/github-app-token@v2
with:
app_id: ${{ secrets.GH_APP_ID }}
private_key: ${{ secrets.GH_APP_KEY }}
repository: "recloudstream/secrets"
- name: Generate access token (archive)
id: generate_archive_token
uses: tibdex/github-app-token@v2
with:
app_id: ${{ secrets.GH_APP_ID }}
private_key: ${{ secrets.GH_APP_KEY }}
repository: "recloudstream/cloudstream-archive"
- uses: actions/checkout@v6
- name: Set up JDK 17
uses: actions/setup-java@v5
with:
distribution: temurin
java-version: 17
- name: Grant execute permission for gradlew
run: chmod +x gradlew
- name: Fetch keystore
id: fetch_keystore
run: |
TMP_KEYSTORE_FILE_PATH="${RUNNER_TEMP}"/keystore
mkdir -p "${TMP_KEYSTORE_FILE_PATH}"
curl -H "Authorization: token ${{ steps.generate_token.outputs.token }}" -o "${TMP_KEYSTORE_FILE_PATH}/prerelease_keystore.keystore" "https://raw.githubusercontent.com/recloudstream/secrets/master/keystore.jks"
curl -H "Authorization: token ${{ steps.generate_token.outputs.token }}" -o "keystore_password.txt" "https://raw.githubusercontent.com/recloudstream/secrets/master/keystore_password.txt"
KEY_PWD="$(cat keystore_password.txt)"
echo "::add-mask::${KEY_PWD}"
echo "key_pwd=$KEY_PWD" >> $GITHUB_OUTPUT
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v5
with:
cache-encryption-key: ${{ secrets.GRADLE_ENCRYPTION_KEY }}
- name: Run Gradle
run: ./gradlew assemblePrerelease
env:
SIGNING_KEY_ALIAS: "key0"
SIGNING_KEY_PASSWORD: ${{ steps.fetch_keystore.outputs.key_pwd }}
SIGNING_STORE_PASSWORD: ${{ steps.fetch_keystore.outputs.key_pwd }}
SIMKL_CLIENT_ID: ${{ secrets.SIMKL_CLIENT_ID }}
SIMKL_CLIENT_SECRET: ${{ secrets.SIMKL_CLIENT_SECRET }}
- uses: actions/checkout@v6
with:
repository: "recloudstream/cloudstream-archive"
token: ${{ steps.generate_archive_token.outputs.token }}
path: "archive"
- name: Move build
run: cp app/build/outputs/apk/prerelease/release/*.apk "archive/$(git rev-parse --short HEAD).apk"
- name: Push archive
run: |
cd $GITHUB_WORKSPACE/archive
git config --local user.email "actions@github.com"
git config --local user.name "GitHub Actions"
git add .
git commit --amend -m "Build $GITHUB_SHA" || exit 0 # do not error if nothing to commit
git push --force
================================================
FILE: .github/workflows/generate_dokka.yml
================================================
name: Dokka
on:
push:
branches: [ master ]
paths-ignore:
- '*.md'
concurrency:
group: "dokka"
cancel-in-progress: true
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Generate access token
id: generate_token
uses: tibdex/github-app-token@v2
with:
app_id: ${{ secrets.GH_APP_ID }}
private_key: ${{ secrets.GH_APP_KEY }}
repository: "recloudstream/dokka"
- name: Checkout
uses: actions/checkout@v6
with:
path: "src"
- name: Checkout dokka
uses: actions/checkout@v6
with:
repository: "recloudstream/dokka"
path: "dokka"
token: ${{ steps.generate_token.outputs.token }}
- name: Clean old builds
run: |
cd $GITHUB_WORKSPACE/dokka/
rm -rf "./app"
rm -rf "./library"
- name: Set up JDK 17
uses: actions/setup-java@v5
with:
distribution: temurin
java-version: 17
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v5
with:
cache-encryption-key: ${{ secrets.GRADLE_ENCRYPTION_KEY }}
- name: Set up Android SDK
uses: android-actions/setup-android@v3
- name: Generate Dokka
run: |
cd $GITHUB_WORKSPACE/src/
chmod +x gradlew
./gradlew docs:dokkaGeneratePublicationHtml
- name: Copy Dokka
run: cp -r $GITHUB_WORKSPACE/src/docs/build/dokka/html/* $GITHUB_WORKSPACE/dokka/
- name: Push builds
run: |
cd $GITHUB_WORKSPACE/dokka
touch .nojekyll
git config --local user.email "111277985+recloudstream[bot]@users.noreply.github.com"
git config --local user.name "recloudstream[bot]"
git add .
git commit --amend -m "Generate dokka for recloudstream/cloudstream@${GITHUB_SHA}" || exit 0 # do not error if nothing to commit
git push --force
================================================
FILE: .github/workflows/issue_action.yml
================================================
name: Issue automatic actions
on:
issues:
types: [opened]
jobs:
issue-moderator:
runs-on: ubuntu-latest
steps:
- name: Generate access token
id: generate_token
uses: tibdex/github-app-token@v2
with:
app_id: ${{ secrets.GH_APP_ID }}
private_key: ${{ secrets.GH_APP_KEY }}
- name: Similarity analysis
id: similarity
uses: actions-cool/issues-similarity-analysis@v1
with:
token: ${{ steps.generate_token.outputs.token }}
filter-threshold: 0.60
title-excludes: ''
comment-title: |
### Your issue looks similar to these issues:
Please close if duplicate.
comment-body: '${index}. ${similarity} #${number}'
- name: Label if possible duplicate
if: steps.similarity.outputs.similar-issues-found =='true'
uses: actions/github-script@v8
with:
github-token: ${{ steps.generate_token.outputs.token }}
script: |
github.rest.issues.addLabels({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
labels: ["possible duplicate"]
})
- uses: actions/checkout@v6
- name: Automatically close issues that dont follow the issue template
uses: lucasbento/auto-close-issues@v1.0.2
with:
github-token: ${{ steps.generate_token.outputs.token }}
issue-close-message: |
@${issue.user.login}: hello! :wave:
This issue is being automatically closed because it does not follow the issue template."
closed-issues-label: "invalid"
- name: Check if issue mentions a provider
id: provider_check
env:
GH_TEXT: "${{ github.event.issue.title }} ${{ github.event.issue.body }}"
run: |
wget --output-document check_issue.py "https://raw.githubusercontent.com/recloudstream/.github/master/.github/check_issue.py"
pip3 install httpx
RES="$(python3 ./check_issue.py)"
echo "name=${RES}" >> $GITHUB_OUTPUT
- name: Comment if issue mentions a provider
if: steps.provider_check.outputs.name != 'none'
uses: actions-cool/issues-helper@v3
with:
actions: 'create-comment'
token: ${{ steps.generate_token.outputs.token }}
body: |
Hello ${{ github.event.issue.user.login }}.
Please do not report any provider bugs here. This repository does not contain any providers. Please find the appropriate repository and report your issue there or join the [discord](https://discord.gg/5Hus6fM).
Found provider name: `${{ steps.provider_check.outputs.name }}`
- name: Label if mentions provider
if: steps.provider_check.outputs.name != 'none'
uses: actions/github-script@v8
with:
github-token: ${{ steps.generate_token.outputs.token }}
script: |
github.rest.issues.addLabels({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
labels: ["possible provider issue"]
})
- name: Add eyes reaction to all issues
uses: actions-cool/emoji-helper@v1.0.0
with:
type: 'issue'
token: ${{ steps.generate_token.outputs.token }}
emoji: 'eyes'
================================================
FILE: .github/workflows/prerelease.yml
================================================
name: Pre-release
on:
push:
branches: [ master ]
paths-ignore:
- '*.md'
- '*.json'
- '**/wcokey.txt'
concurrency:
group: "pre-release"
cancel-in-progress: true
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Generate access token
id: generate_token
uses: tibdex/github-app-token@v2
with:
app_id: ${{ secrets.GH_APP_ID }}
private_key: ${{ secrets.GH_APP_KEY }}
repository: "recloudstream/secrets"
- uses: actions/checkout@v6
- name: Set up JDK 17
uses: actions/setup-java@v5
with:
distribution: temurin
java-version: 17
- name: Grant execute permission for gradlew
run: chmod +x gradlew
- name: Fetch keystore
id: fetch_keystore
run: |
TMP_KEYSTORE_FILE_PATH="${RUNNER_TEMP}"/keystore
mkdir -p "${TMP_KEYSTORE_FILE_PATH}"
curl -H "Authorization: token ${{ steps.generate_token.outputs.token }}" -o "${TMP_KEYSTORE_FILE_PATH}/prerelease_keystore.keystore" "https://raw.githubusercontent.com/recloudstream/secrets/master/keystore.jks"
curl -H "Authorization: token ${{ steps.generate_token.outputs.token }}" -o "keystore_password.txt" "https://raw.githubusercontent.com/recloudstream/secrets/master/keystore_password.txt"
KEY_PWD="$(cat keystore_password.txt)"
echo "::add-mask::${KEY_PWD}"
echo "key_pwd=$KEY_PWD" >> $GITHUB_OUTPUT
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v5
with:
cache-encryption-key: ${{ secrets.GRADLE_ENCRYPTION_KEY }}
- name: Run Gradle
run: ./gradlew assemblePrerelease build androidSourcesJar makeJar
env:
SIGNING_KEY_ALIAS: "key0"
SIGNING_KEY_PASSWORD: ${{ steps.fetch_keystore.outputs.key_pwd }}
SIGNING_STORE_PASSWORD: ${{ steps.fetch_keystore.outputs.key_pwd }}
SIMKL_CLIENT_ID: ${{ secrets.SIMKL_CLIENT_ID }}
SIMKL_CLIENT_SECRET: ${{ secrets.SIMKL_CLIENT_SECRET }}
MDL_API_KEY: ${{ secrets.MDL_API_KEY }}
- name: Create pre-release
uses: marvinpinto/action-automatic-releases@latest
with:
repo_token: "${{ secrets.GITHUB_TOKEN }}"
automatic_release_tag: "pre-release"
prerelease: true
title: "Pre-release Build"
files: |
app/build/outputs/apk/prerelease/release/*.apk
app/build/libs/app-sources.jar
app/build/classes.jar
================================================
FILE: .github/workflows/pull_request.yml
================================================
name: Artifact Build
on: [pull_request]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- name: Set up JDK 17
uses: actions/setup-java@v5
with:
distribution: temurin
java-version: 17
- name: Grant execute permission for gradlew
run: chmod +x gradlew
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v5
with:
cache-encryption-key: ${{ secrets.GRADLE_ENCRYPTION_KEY }}
cache-read-only: false
- name: Run Gradle
run: ./gradlew assemblePrereleaseDebug lint
- name: Upload Artifact
uses: actions/upload-artifact@v6
with:
name: pull-request-build
path: "app/build/outputs/apk/prerelease/debug/*.apk"
================================================
FILE: .github/workflows/update_locales.yml
================================================
name: Fix locale issues
on:
push:
branches: [ master ]
paths:
- '**.xml'
workflow_dispatch:
concurrency:
group: "locale"
cancel-in-progress: true
jobs:
create:
runs-on: ubuntu-latest
steps:
- name: Generate access token
id: generate_token
uses: tibdex/github-app-token@v2
with:
app_id: ${{ secrets.GH_APP_ID }}
private_key: ${{ secrets.GH_APP_KEY }}
repository: "recloudstream/cloudstream"
- uses: actions/checkout@v6
with:
token: ${{ steps.generate_token.outputs.token }}
- name: Install dependencies
run: pip3 install lxml requests
- name: Edit files
run: python3 .github/locales.py
- name: Commit to the repo
run: |
git config --local user.email "111277985+recloudstream[bot]@users.noreply.github.com"
git config --local user.name "recloudstream[bot]"
git add .
# "echo" returns true so the build succeeds, even if no changed files
git commit -m 'chore(locales): fix locale issues' || echo
git push
================================================
FILE: .gitignore
================================================
/local.properties
/.idea/caches
/.idea/misc.xml
/.idea/libraries
/.idea/modules.xml
/.idea/workspace.xml
/.idea/navEditor.xml
/.idea/assetWizardSettings.xml
.DS_Store
/build
/captures
.cxx
.kotlin/*
# Created by https://www.toptal.com/developers/gitignore/api/kotlin,java,android,androidstudio,visualstudiocode
# Edit at https://www.toptal.com/developers/gitignore?templates=kotlin,java,android,androidstudio,visualstudiocode
### Android ###
# Gradle files
.gradle/
build/
# Local configuration file (sdk path, etc)
local.properties
# Log/OS Files
*.log
# Android Studio generated files and folders
captures/
.externalNativeBuild/
.cxx/
*.apk
output.json
# IntelliJ
*.iml
.idea/
misc.xml
deploymentTargetDropDown.xml
render.experimental.xml
# Keystore files
*.jks
*.keystore
# Google Services (e.g. APIs or Firebase)
google-services.json
# Android Profiling
*.hprof
### Android Patch ###
gen-external-apklibs
# Replacement of .externalNativeBuild directories introduced
# with Android Studio 3.5.
### Java ###
# Compiled class file
*.class
# Log file
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
replay_pid*
### Kotlin ###
# Compiled class file
# Log file
# BlueJ files
# Mobile Tools for Java (J2ME)
# Package Files #
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
### VisualStudioCode ###
.vscode/*
# Local History for Visual Studio Code
.history/
# Built Visual Studio Code Extensions
*.vsix
### VisualStudioCode Patch ###
# Ignore all local history of files
.history
.ionide
### AndroidStudio ###
# Covers files to be ignored for android development using Android Studio.
# Built application files
*.ap_
*.aab
# Files for the ART/Dalvik VM
*.dex
# Java class files
# Generated files
bin/
gen/
out/
# Gradle files
.gradle
# Signing files
.signing/
# Local configuration file (sdk path, etc)
# Proguard folder generated by Eclipse
proguard/
# Log Files
# Android Studio
/*/build/
/*/local.properties
/*/out
/*/*/build
/*/*/production
.navigation/
*.ipr
*~
*.swp
# Keystore files
# Google Services (e.g. APIs or Firebase)
# google-services.json
# Android Patch
# External native build folder generated in Android Studio 2.2 and later
.externalNativeBuild
# NDK
obj/
# IntelliJ IDEA
*.iws
/out/
# User-specific configurations
.idea/caches/
.idea/libraries/
.idea/shelf/
.idea/workspace.xml
.idea/tasks.xml
.idea/.name
.idea/compiler.xml
.idea/copyright/profiles_settings.xml
.idea/encodings.xml
.idea/misc.xml
.idea/modules.xml
.idea/scopes/scope_settings.xml
.idea/dictionaries
.idea/vcs.xml
.idea/jsLibraryMappings.xml
.idea/datasources.xml
.idea/dataSources.ids
.idea/sqlDataSources.xml
.idea/dynamic.xml
.idea/uiDesigner.xml
.idea/assetWizardSettings.xml
.idea/gradle.xml
.idea/jarRepositories.xml
.idea/navEditor.xml
# Legacy Eclipse project files
.classpath
.project
.cproject
.settings/
# Mobile Tools for Java (J2ME)
# Package Files #
# virtual machine crash logs (Reference: http://www.java.com/en/download/help/error_hotspot.xml)
## Plugin-specific files:
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Mongo Explorer plugin
.idea/mongoSettings.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
### AndroidStudio Patch ###
!/gradle/wrapper/gradle-wrapper.jar
# End of https://www.toptal.com/developers/gitignore/api/kotlin,java,android,androidstudio,visualstudiocode
================================================
FILE: AI-POLICY.md
================================================
# AI Policy
AI is a great tool. However, we want you to follow these rules regarding usage of AI in order to ensure the quality of both code and discussions.
1. Always state any AI usage in pull requests and issues.
2. Always test code before making a pull request. We do not want to test your AI generated code.
3. Listen to humans over computers. Contributors to CloudStream know this codebase better than an AI.
4. You should be able to explain and fix any code you submit. We do in-depth reviews and will reject low effort contributions.
================================================
FILE: LICENSE
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
================================================
FILE: README.md
================================================
# CloudStream
**⚠️ Warning: By default, this app doesn't provide any video sources; you have to install extensions to add functionality to the app.**
[](https://discord.gg/5Hus6fM)
## Table of Contents:
+ [About Us:](#about_us)
+ [Installation Steps:](#install_rules)
+ [Contributing:](#contributing)
+ [Issues:](#issues)
+ [Bugs Reports:](#bug_report)
+ [Enhancement:](#enhancment)
+ [Extension Development:](#extensions)
+ [Language Support:](#languages)
+ [Further Sources](#contact_and_sources)
## About us:
**CloudStream is a media center that prioritizes and emphasizes complete freedom and flexibility for users and developers.**
CloudStream is an extension-based multimedia player with tracking support. There are extensions to view videos from:
+ [Librevox (audio-books)](https://librivox.org/)
+ [Youtube](https://www.youtube.com/)
+ [Twitch](https://www.twitch.tv/)
+ [iptv-org (A collection of publicly available IPTV (Internet Protocol television) channels from all over the world.)](https://github.com/iptv-org/iptv)
+ [nginx](https://nginx.org/)
+ And more...
**Please don't create illegal extensions or use any that host any copyrighted media.** For more details about our stance on the DMCA and EUCD, you can read about it on our organization: [reCloudStream](https://github.com/recloudstream)
#### Important Copyright Note:
Our documentation is unmaintained and open to contributions; therefore, apps and sources, extensions in recommended sources, and recommended apps are not officially moderated or endorsed by CloudStream; if you or another copyright owner identify an extension that breaches your copyright, please let us know.
#### Features:
+ **AdFree**, No ads whatsoever
+ No tracking/analytics
+ Bookmarks
+ Phone and TV support
+ Chromecast
+ Extension system for personal customization
## Installation:
Our documentation provides the steps to install and configure CloudStream for your streaming needs.
[Getting Started With CloudStream:](https://recloudstream.github.io/csdocs/)
## Contributing:
We **happily** accept any contributions to our project. To find out where you can start contributing towards the project, please look [at our issues tab](/cloudstream/issues)
### Issues:
While we **actively** accept issues and pull requests, we do require you fill out an [template](https://github.com/recloudstream/cloudstream/issues/new/choose) for issues. These include the following:
- [Bug Report Template: ](https://github.com/recloudstream/cloudstream/issues/new?assignees=&labels=bug&projects=&template=application-bug.yml)
- For bug reports, we want as much info as possible, including your downloaded version of CloudeStream, device and updated version (if possible, current API),
expected behavior of the program, and the actual behavior that the program did, most importantly we require clear, reproducible steps of the bug. If your bug can't be reproduced, it is unlikely we'll work on your issue.
- [Feature Request Template: ](https://github.com/recloudstream/cloudstream/issues/new?assignees=&labels=enhancement&projects=&template=feature-request.yml)
- Before adding a feature request, please check to see if a feature request already has been requested.
### Extensions:
**Further details on creating extensions for CloudStream are found in our documentation.**
[Guide: For Extension Developers](https://recloudstream.github.io/csdocs/devs/gettingstarted/)
## Further Sources:
As well as providing clear install steps, our [website](https://dweb.link/ipns/cloudstream.on.fleek.co/) includes a wide variety of other tools, such as:
- [Troubleshooting](https://recloudstream.github.io/csdocs/troubleshooting/)
- [Further CloudStream Repositories](https://recloudstream.github.io/csdocs/repositories/)
- Set-Up for other devices, such as:
- [Android TV](https://recloudstream.github.io/csdocs/other-devices/tv/)
- [Windows](https://recloudstream.github.io/csdocs/other-devices/windows/)
- [Linux](https://recloudstream.github.io/csdocs/other-devices/linux/)
- And more...
### Supported languages:
Even if you can't contribute to the code or documentation, we always look for those who can contribute to translation and language support. Your contribution is exceptionally appreciated; you can check our translation from the figure below.
================================================
FILE: app/.gitignore
================================================
/build
================================================
FILE: app/build.gradle.kts
================================================
import com.android.build.gradle.internal.cxx.configure.gradleLocalProperties
import org.jetbrains.dokka.gradle.engine.parameters.KotlinPlatform
import org.jetbrains.dokka.gradle.engine.parameters.VisibilityModifier
import org.jetbrains.kotlin.gradle.dsl.JvmDefaultMode
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
import org.jetbrains.kotlin.gradle.tasks.KotlinJvmCompile
plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.dokka)
alias(libs.plugins.kotlin.android)
}
val javaTarget = JvmTarget.fromTarget(libs.versions.jvmTarget.get())
val tmpFilePath = System.getProperty("user.home") + "/work/_temp/keystore/"
val prereleaseStoreFile: File? = File(tmpFilePath).listFiles()?.first()
fun getGitCommitHash(): String {
return try {
val headFile = file("${project.rootDir}/.git/HEAD")
// Read the commit hash from .git/HEAD
if (headFile.exists()) {
val headContent = headFile.readText().trim()
if (headContent.startsWith("ref:")) {
val refPath = headContent.substring(5) // e.g., refs/heads/main
val commitFile = file("${project.rootDir}/.git/$refPath")
if (commitFile.exists()) commitFile.readText().trim() else ""
} else headContent // If it's a detached HEAD (commit hash directly)
} else {
"" // If .git/HEAD doesn't exist
}.take(7) // Return the short commit hash
} catch (_: Throwable) {
"" // Just return an empty string if any exception occurs
}
}
android {
@Suppress("UnstableApiUsage")
testOptions {
unitTests.isReturnDefaultValues = true
}
viewBinding {
enable = true
}
signingConfigs {
if (prereleaseStoreFile != null) {
create("prerelease") {
storeFile = file(prereleaseStoreFile)
storePassword = System.getenv("SIGNING_STORE_PASSWORD")
keyAlias = System.getenv("SIGNING_KEY_ALIAS")
keyPassword = System.getenv("SIGNING_KEY_PASSWORD")
}
}
}
compileSdk = libs.versions.compileSdk.get().toInt()
defaultConfig {
applicationId = "com.lagradost.cloudstream3"
minSdk = libs.versions.minSdk.get().toInt()
targetSdk = libs.versions.targetSdk.get().toInt()
versionCode = 67
versionName = "4.6.2"
resValue("string", "commit_hash", getGitCommitHash())
manifestPlaceholders["target_sdk_version"] = libs.versions.targetSdk.get()
// Reads local.properties
val localProperties = gradleLocalProperties(rootDir, project.providers)
buildConfigField(
"long",
"BUILD_DATE",
"${System.currentTimeMillis()}"
)
buildConfigField(
"String",
"SIMKL_CLIENT_ID",
"\"" + (System.getenv("SIMKL_CLIENT_ID") ?: localProperties["simkl.id"]) + "\""
)
buildConfigField(
"String",
"SIMKL_CLIENT_SECRET",
"\"" + (System.getenv("SIMKL_CLIENT_SECRET") ?: localProperties["simkl.secret"]) + "\""
)
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
isDebuggable = false
isMinifyEnabled = false
isShrinkResources = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
debug {
isDebuggable = true
applicationIdSuffix = ".debug"
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
flavorDimensions.add("state")
productFlavors {
create("stable") {
dimension = "state"
}
create("prerelease") {
dimension = "state"
applicationIdSuffix = ".prerelease"
if (signingConfigs.names.contains("prerelease")) {
signingConfig = signingConfigs.getByName("prerelease")
} else {
logger.warn("No prerelease signing config!")
}
versionNameSuffix = "-PRE"
versionCode = (System.currentTimeMillis() / 60000).toInt()
}
}
compileOptions {
isCoreLibraryDesugaringEnabled = true
sourceCompatibility = JavaVersion.toVersion(javaTarget.target)
targetCompatibility = JavaVersion.toVersion(javaTarget.target)
}
java {
// Use Java 17 toolchain even if a higher JDK runs the build.
// We still use Java 8 for now which higher JDKs have deprecated.
toolchain {
languageVersion.set(JavaLanguageVersion.of(libs.versions.jdkToolchain.get()))
}
}
lint {
abortOnError = false
checkReleaseBuilds = false
}
buildFeatures {
buildConfig = true
resValues = true
}
packaging {
jniLibs {
// Enables legacy JNI packaging to reduce APK size (similar to builds before minSdk 23).
// Note: This may increase app startup time slightly.
useLegacyPackaging = true
}
}
namespace = "com.lagradost.cloudstream3"
}
dependencies {
// Testing
testImplementation(libs.junit)
testImplementation(libs.json)
androidTestImplementation(libs.core)
implementation(libs.junit.ktx)
androidTestImplementation(libs.ext.junit)
androidTestImplementation(libs.espresso.core)
// Android Core & Lifecycle
implementation(libs.core.ktx)
implementation(libs.activity.ktx)
implementation(libs.appcompat)
implementation(libs.fragment.ktx)
implementation(libs.bundles.lifecycle)
implementation(libs.bundles.navigation)
// Design & UI
implementation(libs.preference.ktx)
implementation(libs.material)
implementation(libs.constraintlayout)
// Coil Image Loading
implementation(libs.bundles.coil)
// Media 3 (ExoPlayer)
implementation(libs.bundles.media3)
implementation(libs.video)
// FFmpeg Decoding
implementation(libs.bundles.nextlib)
// PlayBack
implementation(libs.colorpicker) // Subtitle Color Picker
implementation(libs.newpipeextractor) // For Trailers
implementation(libs.juniversalchardet) // Subtitle Decoding
// UI Stuff
implementation(libs.shimmer) // Shimmering Effect (Loading Skeleton)
implementation(libs.palette.ktx) // Palette for Images -> Colors
implementation(libs.tvprovider)
implementation(libs.overlappingpanels) // Gestures
implementation(libs.biometric) // Fingerprint Authentication
implementation(libs.previewseekbar.media3) // SeekBar Preview
implementation(libs.qrcode.kotlin) // QR Code for PIN Auth on TV
// Extensions & Other Libs
implementation(libs.jsoup) // HTML Parser
implementation(libs.rhino) // Run JavaScript
implementation(libs.fuzzywuzzy) // Library/Ext Searching with Levenshtein Distance
implementation(libs.safefile) // To Prevent the URI File Fu*kery
coreLibraryDesugaring(libs.desugar.jdk.libs.nio) // NIO Flavor Needed for NewPipeExtractor
implementation(libs.conscrypt.android) // To Fix SSL Fu*kery on Android 9
implementation(libs.jackson.module.kotlin) // JSON Parser
implementation(libs.zipline)
// Torrent Support
implementation(libs.torrentserver)
// Downloading & Networking
implementation(libs.work.runtime.ktx)
implementation(libs.nicehttp) // HTTP Lib
implementation(project(":library"))
}
tasks.register("androidSourcesJar") {
archiveClassifier.set("sources")
from(android.sourceSets.getByName("main").java.directories) // Full Sources
}
tasks.register("copyJar") {
dependsOn("build", ":library:jvmJar")
from(
"build/intermediates/compile_app_classes_jar/prereleaseDebug/bundlePrereleaseDebugClassesToCompileJar",
"../library/build/libs"
)
into("build/app-classes")
include("classes.jar", "library-jvm*.jar")
// Remove the version
rename("library-jvm.*.jar", "library-jvm.jar")
}
// Merge the app classes and the library classes into classes.jar
tasks.register("makeJar") {
// Duplicates cause hard to catch errors, better to fail at compile time.
duplicatesStrategy = DuplicatesStrategy.FAIL
dependsOn(tasks.getByName("copyJar"))
from(
zipTree("build/app-classes/classes.jar"),
zipTree("build/app-classes/library-jvm.jar")
)
destinationDirectory.set(layout.buildDirectory)
archiveBaseName = "classes"
}
tasks.withType {
compilerOptions {
jvmTarget.set(javaTarget)
jvmDefault.set(JvmDefaultMode.ENABLE)
freeCompilerArgs.add("-Xannotation-default-target=param-property")
optIn.addAll(
"com.lagradost.cloudstream3.InternalAPI",
"com.lagradost.cloudstream3.Prerelease",
)
}
}
dokka {
moduleName = "App"
dokkaSourceSets {
main {
analysisPlatform = KotlinPlatform.JVM
documentedVisibilities(
VisibilityModifier.Public,
VisibilityModifier.Protected
)
sourceLink {
localDirectory = file("..")
remoteUrl("https://github.com/recloudstream/cloudstream/tree/master")
remoteLineSuffix = "#L"
}
}
}
}
================================================
FILE: app/lint.xml
================================================
================================================
FILE: app/proguard-rules.pro
================================================
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.kts.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
================================================
FILE: app/src/androidTest/java/com/lagradost/cloudstream3/ExampleInstrumentedTest.kt
================================================
package com.lagradost.cloudstream3
import android.app.Activity
import android.os.Bundle
import android.os.PersistableBundle
import android.view.LayoutInflater
import androidx.test.core.app.ActivityScenario
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.viewbinding.ViewBinding
import com.lagradost.cloudstream3.databinding.BottomResultviewPreviewBinding
import com.lagradost.cloudstream3.databinding.FragmentHomeBinding
import com.lagradost.cloudstream3.databinding.FragmentHomeTvBinding
import com.lagradost.cloudstream3.databinding.FragmentLibraryBinding
import com.lagradost.cloudstream3.databinding.FragmentLibraryTvBinding
import com.lagradost.cloudstream3.databinding.FragmentPlayerBinding
import com.lagradost.cloudstream3.databinding.FragmentPlayerTvBinding
import com.lagradost.cloudstream3.databinding.FragmentResultBinding
import com.lagradost.cloudstream3.databinding.FragmentResultTvBinding
import com.lagradost.cloudstream3.databinding.FragmentSearchBinding
import com.lagradost.cloudstream3.databinding.FragmentSearchTvBinding
import com.lagradost.cloudstream3.databinding.HomeResultGridBinding
import com.lagradost.cloudstream3.databinding.HomepageParentBinding
import com.lagradost.cloudstream3.databinding.HomepageParentEmulatorBinding
import com.lagradost.cloudstream3.databinding.HomepageParentTvBinding
import com.lagradost.cloudstream3.databinding.PlayerCustomLayoutBinding
import com.lagradost.cloudstream3.databinding.PlayerCustomLayoutTvBinding
import com.lagradost.cloudstream3.databinding.RepositoryItemBinding
import com.lagradost.cloudstream3.databinding.RepositoryItemTvBinding
import com.lagradost.cloudstream3.databinding.SearchResultGridBinding
import com.lagradost.cloudstream3.databinding.SearchResultGridExpandedBinding
import com.lagradost.cloudstream3.databinding.TrailerCustomLayoutBinding
import com.lagradost.cloudstream3.utils.SubtitleHelper
import com.lagradost.cloudstream3.utils.TestingUtils
import kotlinx.coroutines.runBlocking
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class TestApplication : Activity() {
override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
super.onCreate(savedInstanceState, persistentState)
}
}
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
private fun getAllProviders(): Array {
println("Providers: ${APIHolder.allProviders.size}")
return APIHolder.allProviders.toTypedArray() //.filter { !it.usesWebView }
}
@Test
fun providersExist() {
Assert.assertTrue(getAllProviders().isNotEmpty())
println("Done providersExist")
}
@Throws
private inline fun testAllLayouts(
activity: Activity,
vararg layouts: Int
) {
val bind = T::class.java.methods.first { it.name == "bind" }
val inflater = LayoutInflater.from(activity)
for (layout in layouts) {
val root = inflater.inflate(layout, null, false)
bind.invoke(null, root)
}
}
@Test
@Throws
fun layoutTest() {
ActivityScenario.launch(MainActivity::class.java).use { scenario ->
scenario.onActivity { activity: MainActivity ->
// FragmentHomeHeadBinding and FragmentHomeHeadTvBinding CANT be the same
//testAllLayouts(activity, R.layout.fragment_home_head, R.layout.fragment_home_head_tv)
//testAllLayouts(activity, R.layout.fragment_home_head, R.layout.fragment_home_head_tv)
// main cant be tested
// testAllLayouts(activity,R.layout.activity_main, R.layout.activity_main_tv)
// testAllLayouts(activity,R.layout.activity_main, R.layout.activity_main_tv)
//testAllLayouts(activity, R.layout.activity_main_tv)
testAllLayouts(activity, R.layout.bottom_resultview_preview,R.layout.bottom_resultview_preview_tv)
testAllLayouts(activity, R.layout.fragment_player,R.layout.fragment_player_tv)
testAllLayouts(activity, R.layout.fragment_player,R.layout.fragment_player_tv)
// testAllLayouts(activity, R.layout.fragment_result,R.layout.fragment_result_tv)
// testAllLayouts(activity, R.layout.fragment_result,R.layout.fragment_result_tv)
testAllLayouts(activity, R.layout.player_custom_layout,R.layout.player_custom_layout_tv, R.layout.trailer_custom_layout)
testAllLayouts(activity, R.layout.player_custom_layout,R.layout.player_custom_layout_tv, R.layout.trailer_custom_layout)
testAllLayouts(activity, R.layout.player_custom_layout,R.layout.player_custom_layout_tv, R.layout.trailer_custom_layout)
testAllLayouts(activity, R.layout.repository_item_tv, R.layout.repository_item)
testAllLayouts(activity, R.layout.repository_item_tv, R.layout.repository_item)
testAllLayouts(activity, R.layout.repository_item_tv, R.layout.repository_item)
testAllLayouts(activity, R.layout.repository_item_tv, R.layout.repository_item)
testAllLayouts(activity, R.layout.fragment_home_tv, R.layout.fragment_home)
testAllLayouts(activity, R.layout.fragment_home_tv, R.layout.fragment_home)
testAllLayouts(activity, R.layout.fragment_search_tv, R.layout.fragment_search)
testAllLayouts(activity, R.layout.fragment_search_tv, R.layout.fragment_search)
testAllLayouts(activity, R.layout.home_result_grid_expanded, R.layout.home_result_grid)
//testAllLayouts(activity, R.layout.home_result_grid_expanded, R.layout.home_result_grid) ??? fails ???
testAllLayouts(activity, R.layout.search_result_grid, R.layout.search_result_grid_expanded)
testAllLayouts(activity, R.layout.search_result_grid, R.layout.search_result_grid_expanded)
// testAllLayouts(activity, R.layout.home_scroll_view, R.layout.home_scroll_view_tv)
// testAllLayouts(activity, R.layout.home_scroll_view, R.layout.home_scroll_view_tv)
testAllLayouts(activity, R.layout.homepage_parent_tv, R.layout.homepage_parent_emulator, R.layout.homepage_parent)
testAllLayouts(activity, R.layout.homepage_parent_tv, R.layout.homepage_parent_emulator, R.layout.homepage_parent)
testAllLayouts(activity, R.layout.homepage_parent_tv, R.layout.homepage_parent_emulator, R.layout.homepage_parent)
testAllLayouts(activity, R.layout.fragment_library_tv, R.layout.fragment_library)
testAllLayouts(activity, R.layout.fragment_library_tv, R.layout.fragment_library)
}
}
}
@Test
@Throws(AssertionError::class)
fun providerCorrectData() {
val langTagsIETF = SubtitleHelper.languages.map { it.IETF_tag }
Assert.assertFalse("IETFTagNames does not contain any languages", langTagsIETF.isNullOrEmpty())
for (api in getAllProviders()) {
Assert.assertTrue("Api does not contain a mainUrl", api.mainUrl != "NONE")
Assert.assertTrue("Api does not contain a name", api.name != "NONE")
Assert.assertTrue(
"Api ${api.name} does not contain a valid language code",
langTagsIETF.contains(api.lang)
)
Assert.assertTrue(
"Api ${api.name} does not contain any supported types",
api.supportedTypes.isNotEmpty()
)
}
println("Done providerCorrectData")
}
@Test
fun providerCorrectHomepage() {
runBlocking {
getAllProviders().toList().amap { api ->
TestingUtils.testHomepage(api, TestingUtils.Logger())
}
}
println("Done providerCorrectHomepage")
}
@Test
fun testAllProvidersCorrect() {
runBlocking {
TestingUtils.getDeferredProviderTests(
this,
getAllProviders(),
) { _, _ -> }
}
}
}
================================================
FILE: app/src/debug/res/drawable/ic_banner_foreground.xml
================================================
================================================
FILE: app/src/debug/res/drawable-anydpi-v24/ic_stat_name.xml
================================================
================================================
FILE: app/src/debug/res/drawable-v24/ic_banner_background.xml
================================================
================================================
FILE: app/src/debug/res/drawable-v24/ic_launcher_foreground.xml
================================================
================================================
FILE: app/src/debug/res/mipmap-anydpi-v26/ic_banner.xml
================================================
================================================
FILE: app/src/debug/res/mipmap-anydpi-v26/ic_launcher.xml
================================================
================================================
FILE: app/src/debug/res/mipmap-anydpi-v26/ic_launcher_round.xml
================================================
================================================
FILE: app/src/debug/res/values/ic_launcher_background.xml
================================================
#000000
================================================
FILE: app/src/debug/res/values/strings.xml
================================================
CloudStream Debug
================================================
FILE: app/src/main/AndroidManifest.xml
================================================
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/AcraApplication.kt
================================================
package com.lagradost.cloudstream3
import android.content.Context
import com.lagradost.api.setContext
import com.lagradost.cloudstream3.utils.DataStore.getKey
import com.lagradost.cloudstream3.utils.DataStore.removeKeys
import com.lagradost.cloudstream3.utils.DataStore.setKey
import java.lang.ref.WeakReference
/**
* Deprecated alias for CloudStreamApp for backwards compatibility with plugins.
* Use CloudStreamApp instead.
*/
// Deprecate after next stable
/*@Deprecated(
message = "AcraApplication is deprecated, use CloudStreamApp instead",
replaceWith = ReplaceWith("com.lagradost.cloudstream3.CloudStreamApp"),
level = DeprecationLevel.WARNING
)*/
class AcraApplication {
// All methods here can be changed to be a wrapper around CloudStream app
// without a seperate deprecation after next stable. All methods should
// also be deprecated at that time.
companion object {
// This can be removed without deprecation after next stable
private var _context: WeakReference? = null
/*@Deprecated(
message = "AcraApplication is deprecated, use CloudStreamApp instead",
replaceWith = ReplaceWith("com.lagradost.cloudstream3.CloudStreamApp.context"),
level = DeprecationLevel.WARNING
)*/
var context
get() = _context?.get()
internal set(value) {
_context = WeakReference(value)
setContext(WeakReference(value))
}
/*@Deprecated(
message = "AcraApplication is deprecated, use CloudStreamApp instead",
replaceWith = ReplaceWith("com.lagradost.cloudstream3.CloudStreamApp.removeKeys(folder)"),
level = DeprecationLevel.WARNING
)*/
fun removeKeys(folder: String): Int? {
return context?.removeKeys(folder)
}
/*@Deprecated(
message = "AcraApplication is deprecated, use CloudStreamApp instead",
replaceWith = ReplaceWith("com.lagradost.cloudstream3.CloudStreamApp.setKey(path, value)"),
level = DeprecationLevel.WARNING
)*/
fun setKey(path: String, value: T) {
context?.setKey(path, value)
}
/*@Deprecated(
message = "AcraApplication is deprecated, use CloudStreamApp instead",
replaceWith = ReplaceWith("com.lagradost.cloudstream3.CloudStreamApp.setKey(folder, path, value)"),
level = DeprecationLevel.WARNING
)*/
fun setKey(folder: String, path: String, value: T) {
context?.setKey(folder, path, value)
}
/*@Deprecated(
message = "AcraApplication is deprecated, use CloudStreamApp instead",
replaceWith = ReplaceWith("com.lagradost.cloudstream3.CloudStreamApp.getKey(path, defVal)"),
level = DeprecationLevel.WARNING
)*/
inline fun getKey(path: String, defVal: T?): T? {
return context?.getKey(path, defVal)
}
/*@Deprecated(
message = "AcraApplication is deprecated, use CloudStreamApp instead",
replaceWith = ReplaceWith("com.lagradost.cloudstream3.CloudStreamApp.getKey(path)"),
level = DeprecationLevel.WARNING
)*/
inline fun getKey(path: String): T? {
return context?.getKey(path)
}
/*@Deprecated(
message = "AcraApplication is deprecated, use CloudStreamApp instead",
replaceWith = ReplaceWith("com.lagradost.cloudstream3.CloudStreamApp.getKey(folder, path)"),
level = DeprecationLevel.WARNING
)*/
inline fun getKey(folder: String, path: String): T? {
return context?.getKey(folder, path)
}
/*@Deprecated(
message = "AcraApplication is deprecated, use CloudStreamApp instead",
replaceWith = ReplaceWith("com.lagradost.cloudstream3.CloudStreamApp.getKey(folder, path, defVal)"),
level = DeprecationLevel.WARNING
)*/
inline fun getKey(folder: String, path: String, defVal: T?): T? {
return context?.getKey(folder, path, defVal)
}
}
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/CloudStreamApp.kt
================================================
package com.lagradost.cloudstream3
import android.app.Activity
import android.app.Application
import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import android.os.Build
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import coil3.ImageLoader
import coil3.PlatformContext
import coil3.SingletonImageLoader
import com.lagradost.api.setContext
import com.lagradost.cloudstream3.BuildConfig
import com.lagradost.cloudstream3.mvvm.safe
import com.lagradost.cloudstream3.mvvm.safeAsync
import com.lagradost.cloudstream3.plugins.PluginManager
import com.lagradost.cloudstream3.ui.settings.Globals.EMULATOR
import com.lagradost.cloudstream3.ui.settings.Globals.TV
import com.lagradost.cloudstream3.ui.settings.Globals.isLayout
import com.lagradost.cloudstream3.utils.AppContextUtils.openBrowser
import com.lagradost.cloudstream3.utils.AppDebug
import com.lagradost.cloudstream3.utils.Coroutines.runOnMainThread
import com.lagradost.cloudstream3.utils.DataStore.getKey
import com.lagradost.cloudstream3.utils.DataStore.getKeys
import com.lagradost.cloudstream3.utils.DataStore.removeKey
import com.lagradost.cloudstream3.utils.DataStore.removeKeys
import com.lagradost.cloudstream3.utils.DataStore.setKey
import com.lagradost.cloudstream3.utils.ImageLoader.buildImageLoader
import kotlinx.coroutines.runBlocking
import java.io.File
import java.io.FileNotFoundException
import java.io.PrintStream
import java.lang.ref.WeakReference
import java.util.Locale
import kotlin.concurrent.thread
import kotlin.system.exitProcess
class ExceptionHandler(
val errorFile: File,
val onError: (() -> Unit)
) : Thread.UncaughtExceptionHandler {
override fun uncaughtException(thread: Thread, error: Throwable) {
try {
val threadId = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BAKLAVA) {
thread.threadId()
} else {
@Suppress("DEPRECATION")
thread.id
}
PrintStream(errorFile).use { ps ->
ps.println("Currently loading extension: ${PluginManager.currentlyLoading ?: "none"}")
ps.println("Fatal exception on thread ${thread.name} ($threadId)")
error.printStackTrace(ps)
}
} catch (_: FileNotFoundException) {
}
try {
onError()
} catch (_: Exception) {
}
exitProcess(1)
}
}
@Prerelease
class CloudStreamApp : Application(), SingletonImageLoader.Factory {
override fun onCreate() {
super.onCreate()
// If we want to initialize Coil as early as possible, maybe when
// loading an image or GIF in a splash screen activity.
// buildImageLoader(applicationContext)
ExceptionHandler(filesDir.resolve("last_error")) {
val intent = context!!.packageManager.getLaunchIntentForPackage(context!!.packageName)
startActivity(Intent.makeRestartActivityTask(intent!!.component))
}.also {
exceptionHandler = it
Thread.setDefaultUncaughtExceptionHandler(it)
}
AppDebug.isDebug = BuildConfig.DEBUG
}
override fun attachBaseContext(base: Context?) {
super.attachBaseContext(base)
context = base
// This can be removed without deprecation after next stable
AcraApplication.context = context
}
override fun newImageLoader(context: PlatformContext): ImageLoader {
// Coil module will be initialized globally when first loadImage() is invoked.
return buildImageLoader(applicationContext)
}
companion object {
var exceptionHandler: ExceptionHandler? = null
/** Use to get Activity from Context. */
tailrec fun Context.getActivity(): Activity? {
return when (this) {
is Activity -> this
is ContextWrapper -> baseContext.getActivity()
else -> null
}
}
private var _context: WeakReference? = null
var context
get() = _context?.get()
private set(value) {
_context = WeakReference(value)
setContext(WeakReference(value))
}
fun getKeyClass(path: String, valueType: Class): T? {
return context?.getKey(path, valueType)
}
fun setKeyClass(path: String, value: T) {
context?.setKey(path, value)
}
fun removeKeys(folder: String): Int? {
return context?.removeKeys(folder)
}
fun setKey(path: String, value: T) {
context?.setKey(path, value)
}
fun setKey(folder: String, path: String, value: T) {
context?.setKey(folder, path, value)
}
inline fun getKey(path: String, defVal: T?): T? {
return context?.getKey(path, defVal)
}
inline fun getKey(path: String): T? {
return context?.getKey(path)
}
inline fun getKey(folder: String, path: String): T? {
return context?.getKey(folder, path)
}
inline fun getKey(folder: String, path: String, defVal: T?): T? {
return context?.getKey(folder, path, defVal)
}
fun getKeys(folder: String): List? {
return context?.getKeys(folder)
}
fun removeKey(folder: String, path: String) {
context?.removeKey(folder, path)
}
fun removeKey(path: String) {
context?.removeKey(path)
}
/** If fallbackWebView is true and a fragment is supplied then it will open a WebView with the URL if the browser fails. */
fun openBrowser(url: String, fallbackWebView: Boolean = false, fragment: Fragment? = null) {
context?.openBrowser(url, fallbackWebView, fragment)
}
/** Will fall back to WebView if in TV or emulator layout. */
fun openBrowser(url: String, activity: FragmentActivity?) {
openBrowser(
url,
isLayout(TV or EMULATOR),
activity?.supportFragmentManager?.fragments?.lastOrNull()
)
}
}
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/CommonActivity.kt
================================================
package com.lagradost.cloudstream3
import android.annotation.SuppressLint
import android.app.Activity
import android.app.PictureInPictureParams
import android.content.Context
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.content.res.Resources
import android.Manifest
import android.os.Build
import android.util.DisplayMetrics
import android.util.Log
import android.view.Gravity
import android.view.KeyEvent
import android.view.View
import android.view.View.NO_ID
import android.view.ViewGroup
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.MainThread
import androidx.annotation.StringRes
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.SearchView
import androidx.core.content.ContextCompat
import androidx.core.view.children
import androidx.core.view.isNotEmpty
import androidx.preference.PreferenceManager
import com.google.android.gms.cast.framework.CastSession
import com.google.android.material.chip.ChipGroup
import com.google.android.material.navigationrail.NavigationRailView
import com.lagradost.cloudstream3.CloudStreamApp.Companion.getKey
import com.lagradost.cloudstream3.CloudStreamApp.Companion.removeKey
import com.lagradost.cloudstream3.actions.OpenInAppAction
import com.lagradost.cloudstream3.actions.VideoClickActionHolder
import com.lagradost.cloudstream3.databinding.ToastBinding
import com.lagradost.cloudstream3.mvvm.logError
import com.lagradost.cloudstream3.syncproviders.AccountManager
import com.lagradost.cloudstream3.ui.home.HomeChildItemAdapter
import com.lagradost.cloudstream3.ui.home.ParentItemAdapter
import com.lagradost.cloudstream3.ui.player.PlayerEventType
import com.lagradost.cloudstream3.ui.player.PlayerPipHelper.isPIPPossible
import com.lagradost.cloudstream3.ui.player.Torrent
import com.lagradost.cloudstream3.ui.result.ActorAdaptor
import com.lagradost.cloudstream3.ui.result.EpisodeAdapter
import com.lagradost.cloudstream3.ui.result.ImageAdapter
import com.lagradost.cloudstream3.ui.search.SearchAdapter
import com.lagradost.cloudstream3.ui.settings.Globals.isLayout
import com.lagradost.cloudstream3.ui.settings.Globals.TV
import com.lagradost.cloudstream3.ui.settings.Globals.updateTv
import com.lagradost.cloudstream3.ui.settings.extensions.PluginAdapter
import com.lagradost.cloudstream3.utils.AppContextUtils.isRtl
import com.lagradost.cloudstream3.utils.Coroutines.ioSafe
import com.lagradost.cloudstream3.utils.Event
import com.lagradost.cloudstream3.utils.UIHelper.showInputMethod
import com.lagradost.cloudstream3.utils.UIHelper.toPx
import com.lagradost.cloudstream3.utils.UiText
import java.lang.ref.WeakReference
import java.util.Locale
import kotlin.math.max
import kotlin.math.min
import org.schabi.newpipe.extractor.NewPipe
enum class FocusDirection {
Start,
End,
Up,
Down,
}
object CommonActivity {
private var _activity: WeakReference? = null
var activity
get() = _activity?.get()
private set(value) {
_activity = WeakReference(value)
}
@MainThread
fun setActivityInstance(newActivity: Activity?) {
activity = newActivity
}
@MainThread
fun Activity?.getCastSession(): CastSession? {
return (this as MainActivity?)?.mSessionManager?.currentCastSession
}
val displayMetrics: DisplayMetrics = Resources.getSystem().displayMetrics
// screenWidth and screenHeight does always
// refer to the screen while in landscape mode
val screenWidth: Int
get() {
return max(displayMetrics.widthPixels, displayMetrics.heightPixels)
}
val screenHeight: Int
get() {
return min(displayMetrics.widthPixels, displayMetrics.heightPixels)
}
val screenWidthWithOrientation: Int
get() {
return displayMetrics.widthPixels
}
val screenHeightWithOrientation: Int
get() {
return displayMetrics.heightPixels
}
var isPipDesired: Boolean = false
var isInPIPMode: Boolean = false
val onColorSelectedEvent = Event>()
val onDialogDismissedEvent = Event()
var playerEventListener: ((PlayerEventType) -> Unit)? = null
var keyEventListener: ((Pair) -> Boolean)? = null
var appliedTheme: Int = 0
var appliedColor: Int = 0
private var currentToast: Toast? = null
fun showToast(@StringRes message: Int, duration: Int? = null) {
val act = activity ?: return
act.runOnUiThread {
showToast(act, act.getString(message), duration)
}
}
fun showToast(message: String?, duration: Int? = null) {
val act = activity ?: return
act.runOnUiThread {
showToast(act, message, duration)
}
}
fun showToast(message: UiText?, duration: Int? = null) {
val act = activity ?: return
if (message == null) return
act.runOnUiThread {
showToast(act, message.asString(act), duration)
}
}
@MainThread
fun showToast(act: Activity?, text: UiText, duration: Int) {
if (act == null) return
text.asStringNull(act)?.let {
showToast(act, it, duration)
}
}
/** duration is Toast.LENGTH_SHORT if null*/
@MainThread
fun showToast(act: Activity?, @StringRes message: Int, duration: Int? = null) {
if (act == null) return
showToast(act, act.getString(message), duration)
}
const val TAG = "COMPACT"
/** duration is Toast.LENGTH_SHORT if null*/
@MainThread
fun showToast(act: Activity?, message: String?, duration: Int? = null) {
if (act == null || message == null) {
Log.w(TAG, "invalid showToast act = $act message = $message")
return
}
Log.i(TAG, "showToast = $message")
try {
currentToast?.cancel()
} catch (e: Exception) {
logError(e)
}
try {
val binding = ToastBinding.inflate(act.layoutInflater)
binding.text.text = message.trim()
// custom toasts are deprecated and won't appear when cs3 sets minSDK to api30 (A11)
val toast = Toast(act)
toast.duration = duration ?: Toast.LENGTH_SHORT
toast.setGravity(Gravity.CENTER_HORIZONTAL or Gravity.BOTTOM, 0, 5.toPx)
@Suppress("DEPRECATION")
toast.view =
binding.root // FIXME Find an alternative using default Toasts since custom toasts are deprecated and won't appear with api30 set as minSDK version.
currentToast = toast
toast.show()
} catch (e: Exception) {
logError(e)
}
}
/**
* Set locale
* @param languageTag shall a IETF BCP 47 conformant tag.
* Check [com.lagradost.cloudstream3.utils.SubtitleHelper].
*
* See locales on:
* https://github.com/unicode-org/cldr-json/blob/main/cldr-json/cldr-core/availableLocales.json
* https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry
* https://android.googlesource.com/platform/frameworks/base/+/android-16.0.0_r2/core/res/res/values/locale_config.xml
* https://iso639-3.sil.org/code_tables/639/data/all
*/
fun setLocale(context: Context?, languageTag: String?) {
if (context == null || languageTag == null) return
val locale = Locale.forLanguageTag(languageTag)
val resources: Resources = context.resources
val config = resources.configuration
Locale.setDefault(locale)
config.setLocale(locale)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
context.createConfigurationContext(config)
@Suppress("DEPRECATION")
resources.updateConfiguration(
config,
resources.displayMetrics
) // FIXME this should be replaced
}
fun Context.updateLocale() {
val settingsManager = PreferenceManager.getDefaultSharedPreferences(this)
val localeCode = settingsManager.getString(getString(R.string.locale_key), null)
setLocale(this, localeCode)
}
fun init(act: Activity) {
setActivityInstance(act)
ioSafe { Torrent.deleteAllFiles() }
val componentActivity = activity as? ComponentActivity ?: return
componentActivity.updateLocale()
componentActivity.updateTv()
AccountManager.initMainAPI()
NewPipe.init(DownloaderTestImpl.getInstance())
MainActivity.activityResultLauncher =
componentActivity.registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == AppCompatActivity.RESULT_OK) {
val actionUid =
getKey("last_click_action") ?: return@registerForActivityResult
Log.d(TAG, "Loading action $actionUid result handler")
val action = VideoClickActionHolder.getByUniqueId(actionUid) as? OpenInAppAction
?: return@registerForActivityResult
action.onResultSafe(act, result.data)
removeKey("last_click_action")
removeKey("last_opened")
}
}
// Ask for notification permissions on Android 13
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
ContextCompat.checkSelfPermission(
componentActivity,
Manifest.permission.POST_NOTIFICATIONS
) != PackageManager.PERMISSION_GRANTED
) {
val requestPermissionLauncher = componentActivity.registerForActivityResult(
ActivityResultContracts.RequestPermission()
) { isGranted: Boolean ->
Log.d(TAG, "Notification permission: $isGranted")
}
requestPermissionLauncher.launch(
Manifest.permission.POST_NOTIFICATIONS
)
}
}
/** Enters pip mode if it is both possible and desired to do so*/
private fun Activity.enterPIPMode() {
if (!isPipDesired || !this.isPIPPossible()) return
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
try {
enterPictureInPictureMode(PictureInPictureParams.Builder().build())
} catch (_: Exception) {
// Use fallback just in case
@Suppress("DEPRECATION")
enterPictureInPictureMode()
}
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
@Suppress("DEPRECATION")
enterPictureInPictureMode()
}
}
} catch (e: Exception) {
logError(e)
}
}
fun onUserLeaveHint(act: Activity) {
// On Android 12 and later we use setAutoEnterEnabled() instead.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) return
act.enterPIPMode()
}
fun updateTheme(act: Activity) {
val settingsManager = PreferenceManager.getDefaultSharedPreferences(act)
if (settingsManager
.getString(act.getString(R.string.app_theme_key), "AmoledLight") == "System"
&& Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q
) {
loadThemes(act)
}
}
private fun mapSystemTheme(act: Activity): Int {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val currentNightMode =
act.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
return when (currentNightMode) {
Configuration.UI_MODE_NIGHT_NO -> R.style.LightMode // Night mode is not active, we're using the light theme
else -> R.style.AppTheme // Night mode is active, we're using dark theme
}
} else {
return R.style.AppTheme
}
}
fun loadThemes(act: Activity?) {
if (act == null) return
val settingsManager = PreferenceManager.getDefaultSharedPreferences(act)
val currentTheme =
when (settingsManager.getString(act.getString(R.string.app_theme_key), "AmoledLight")) {
"System" -> mapSystemTheme(act)
"Black" -> R.style.AppTheme
"Light" -> R.style.LightMode
"Amoled" -> R.style.AmoledMode
"AmoledLight" -> R.style.AmoledModeLight
"Monet" -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S)
R.style.MonetMode else R.style.AppTheme
"Dracula" -> R.style.DraculaMode
"Lavender" -> R.style.LavenderMode
"SilentBlue" -> R.style.SilentBlueMode
else -> R.style.AppTheme
}
val currentOverlayTheme =
when (settingsManager.getString(act.getString(R.string.primary_color_key), "Normal")) {
"Normal" -> R.style.OverlayPrimaryColorNormal
"DandelionYellow" -> R.style.OverlayPrimaryColorDandelionYellow
"CarnationPink" -> R.style.OverlayPrimaryColorCarnationPink
"Orange" -> R.style.OverlayPrimaryColorOrange
"DarkGreen" -> R.style.OverlayPrimaryColorDarkGreen
"Maroon" -> R.style.OverlayPrimaryColorMaroon
"NavyBlue" -> R.style.OverlayPrimaryColorNavyBlue
"Grey" -> R.style.OverlayPrimaryColorGrey
"White" -> R.style.OverlayPrimaryColorWhite
"CoolBlue" -> R.style.OverlayPrimaryColorCoolBlue
"Brown" -> R.style.OverlayPrimaryColorBrown
"Purple" -> R.style.OverlayPrimaryColorPurple
"Green" -> R.style.OverlayPrimaryColorGreen
"GreenApple" -> R.style.OverlayPrimaryColorGreenApple
"Red" -> R.style.OverlayPrimaryColorRed
"Banana" -> R.style.OverlayPrimaryColorBanana
"Party" -> R.style.OverlayPrimaryColorParty
"Pink" -> R.style.OverlayPrimaryColorPink
"Lavender" -> R.style.OverlayPrimaryColorLavender
"Monet" -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S)
R.style.OverlayPrimaryColorMonet else R.style.OverlayPrimaryColorNormal
"Monet2" -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S)
R.style.OverlayPrimaryColorMonetTwo else R.style.OverlayPrimaryColorNormal
else -> R.style.OverlayPrimaryColorNormal
}
act.theme.applyStyle(currentTheme, true)
act.theme.applyStyle(currentOverlayTheme, true)
appliedTheme = currentTheme
appliedColor = currentOverlayTheme
act.updateTv()
if (isLayout(TV)) act.theme.applyStyle(R.style.AppThemeTvOverlay, true)
act.theme.applyStyle(
R.style.LoadedStyle,
true
) // THEME IS SET BEFORE VIEW IS CREATED TO APPLY THE THEME TO THE MAIN VIEW
}
/** because we want closes find, aka when multiple have the same id, we go to parent
until the correct one is found */
private fun localLook(from: View, id: Int): View? {
if (id == NO_ID) return null
var currentLook: View = from
// limit to 15 look depth
for (i in 0..15) {
currentLook.findViewById(id)?.let { return it }
currentLook = (currentLook.parent as? View) ?: break
}
return null
}
/*var currentLook: View = view
while (true) {
val tmpNext = currentLook.findViewById(nextId)
if (tmpNext != null) {
next = tmpNext
break
}
currentLook = currentLook.parent as? View ?: break
}*/
private fun View.hasContent(): Boolean {
return isShown && when (this) {
is ViewGroup -> this.isNotEmpty()
else -> true
}
}
/** skips the initial stage of searching for an id using the view, see getNextFocus for specification */
fun continueGetNextFocus(
root: Any?,
view: View,
direction: FocusDirection,
nextId: Int,
depth: Int = 0
): View? {
if (nextId == NO_ID) return null
// do an initial search for the view, in case the localLook is too deep we can use this as
// an early break and backup view
var next =
when (root) {
is Activity -> root.findViewById(nextId)
is View -> root.rootView.findViewById(nextId)
else -> null
} ?: return null
next = localLook(view, nextId) ?: next
val shown = next.hasContent()
// if cant focus but visible then break and let android decide
// the exception if is the view is a parent and has children that wants focus
val hasChildrenThatWantsFocus = (next as? ViewGroup)?.let { parent ->
parent.descendantFocusability == ViewGroup.FOCUS_AFTER_DESCENDANTS && parent.isNotEmpty()
} ?: false
if (!next.isFocusable && shown && !hasChildrenThatWantsFocus) return null
// if not shown then continue because we will "skip" over views to get to a replacement
if (!shown) {
// we don't want a while true loop, so we let android decide if we find a recursive view
if (next == view) return null
return getNextFocus(root, next, direction, depth + 1)
}
(when (next) {
is ChipGroup -> {
next.children.firstOrNull { it.isFocusable && it.isShown }
}
is NavigationRailView -> {
next.findViewById(next.selectedItemId) ?: next.findViewById(R.id.navigation_home)
}
else -> null
})?.let {
return it
}
// nothing wrong with the view found, return it
return next
}
/** recursively looks for a next focus up to a depth of 10,
* this is used to override the normal shit focus system
* because this application has a lot of invisible views that messes with some tv devices*/
fun getNextFocus(
root: Any?,
view: View?,
direction: FocusDirection,
depth: Int = 0
): View? {
// if input is invalid let android decide + depth test to not crash if loop is found
if (view == null || depth >= 10 || root == null) {
return null
}
var nextId = when (direction) {
FocusDirection.Start -> {
if (view.isRtl())
view.nextFocusRightId
else
view.nextFocusLeftId
}
FocusDirection.Up -> {
view.nextFocusUpId
}
FocusDirection.End -> {
if (view.isRtl())
view.nextFocusLeftId
else
view.nextFocusRightId
}
FocusDirection.Down -> {
view.nextFocusDownId
}
}
if (nextId == NO_ID) {
// if not specified then use forward id
nextId = view.nextFocusForwardId
// if view is still not found to next focus then return and let android decide
if (nextId == NO_ID)
return null
}
return continueGetNextFocus(root, view, direction, nextId, depth)
}
fun onKeyDown(act: Activity?, keyCode: Int, event: KeyEvent?): Boolean? {
// 149 keycode_numpad 5
val playerEvent = when (keyCode) {
KeyEvent.KEYCODE_FORWARD, KeyEvent.KEYCODE_D, KeyEvent.KEYCODE_MEDIA_SKIP_FORWARD, KeyEvent.KEYCODE_MEDIA_FAST_FORWARD -> {
PlayerEventType.SeekForward
}
KeyEvent.KEYCODE_A, KeyEvent.KEYCODE_MEDIA_SKIP_BACKWARD, KeyEvent.KEYCODE_MEDIA_REWIND -> {
PlayerEventType.SeekBack
}
KeyEvent.KEYCODE_MEDIA_NEXT, KeyEvent.KEYCODE_BUTTON_R1, KeyEvent.KEYCODE_N, KeyEvent.KEYCODE_NUMPAD_2, KeyEvent.KEYCODE_CHANNEL_UP -> {
PlayerEventType.NextEpisode
}
KeyEvent.KEYCODE_MEDIA_PREVIOUS, KeyEvent.KEYCODE_BUTTON_L1, KeyEvent.KEYCODE_B, KeyEvent.KEYCODE_NUMPAD_1, KeyEvent.KEYCODE_CHANNEL_DOWN -> {
PlayerEventType.PrevEpisode
}
KeyEvent.KEYCODE_MEDIA_PAUSE -> {
PlayerEventType.Pause
}
KeyEvent.KEYCODE_MEDIA_PLAY, KeyEvent.KEYCODE_BUTTON_START -> {
PlayerEventType.Play
}
KeyEvent.KEYCODE_L, KeyEvent.KEYCODE_NUMPAD_7, KeyEvent.KEYCODE_7 -> {
PlayerEventType.Lock
}
KeyEvent.KEYCODE_H, KeyEvent.KEYCODE_MENU -> {
PlayerEventType.ToggleHide
}
KeyEvent.KEYCODE_M, KeyEvent.KEYCODE_VOLUME_MUTE -> {
PlayerEventType.ToggleMute
}
KeyEvent.KEYCODE_S, KeyEvent.KEYCODE_NUMPAD_9, KeyEvent.KEYCODE_9 -> {
PlayerEventType.ShowMirrors
}
// OpenSubtitles shortcut
KeyEvent.KEYCODE_O, KeyEvent.KEYCODE_NUMPAD_8, KeyEvent.KEYCODE_8 -> {
PlayerEventType.SearchSubtitlesOnline
}
KeyEvent.KEYCODE_E, KeyEvent.KEYCODE_NUMPAD_3, KeyEvent.KEYCODE_3 -> {
PlayerEventType.ShowSpeed
}
KeyEvent.KEYCODE_R, KeyEvent.KEYCODE_NUMPAD_0, KeyEvent.KEYCODE_0 -> {
PlayerEventType.Resize
}
KeyEvent.KEYCODE_C, KeyEvent.KEYCODE_NUMPAD_4, KeyEvent.KEYCODE_4 -> {
PlayerEventType.SkipOp
}
KeyEvent.KEYCODE_V, KeyEvent.KEYCODE_NUMPAD_5, KeyEvent.KEYCODE_5 -> {
PlayerEventType.SkipCurrentChapter
}
KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE, KeyEvent.KEYCODE_P, KeyEvent.KEYCODE_SPACE, KeyEvent.KEYCODE_NUMPAD_ENTER, KeyEvent.KEYCODE_ENTER -> { // space is not captured due to navigation
PlayerEventType.PlayPauseToggle
}
else -> return null
}
val listener = playerEventListener
if (listener != null) {
listener.invoke(playerEvent)
return true
}
return null
//when (keyCode) {
// KeyEvent.KEYCODE_DPAD_CENTER -> {
// println("DPAD PRESSED")
// }
//}
}
/** overrides focus and custom key events */
fun dispatchKeyEvent(act: Activity?, event: KeyEvent?): Boolean? {
if (act == null) return null
val currentFocus = act.currentFocus
event?.keyCode?.let { keyCode ->
if (currentFocus == null || event.action != KeyEvent.ACTION_DOWN) return@let
val nextView = when (keyCode) {
KeyEvent.KEYCODE_DPAD_LEFT -> getNextFocus(
act,
currentFocus,
FocusDirection.Start
)
KeyEvent.KEYCODE_DPAD_RIGHT -> getNextFocus(
act,
currentFocus,
FocusDirection.End
)
KeyEvent.KEYCODE_DPAD_UP -> getNextFocus(
act,
currentFocus,
FocusDirection.Up
)
KeyEvent.KEYCODE_DPAD_DOWN -> getNextFocus(
act,
currentFocus,
FocusDirection.Down
)
else -> null
}
// println("NEXT FOCUS : $nextView")
if (nextView != null) {
nextView.requestFocus()
keyEventListener?.invoke(Pair(event, true))
return true
}
// TODO: Figure out why removing the check for SearchAutoComplete seems
// to break focus on TV as it shouldn't need to be used.
@SuppressLint("RestrictedApi")
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER &&
(act.currentFocus is SearchView || act.currentFocus is SearchView.SearchAutoComplete)
) {
showInputMethod(act.currentFocus?.findFocus())
}
//println("Keycode: $keyCode")
//showToast(
// this,
// "Got Keycode $keyCode | ${KeyEvent.keyCodeToString(keyCode)} \n ${event?.action}",
// Toast.LENGTH_LONG
//)
}
// if someone else want to override the focus then don't handle the event as it is already
// consumed. used in video player
if (keyEventListener?.invoke(Pair(event, false)) == true) {
return true
}
return null
}
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/DownloaderTestImpl.kt
================================================
package com.lagradost.cloudstream3
import okhttp3.OkHttpClient
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import org.schabi.newpipe.extractor.downloader.Downloader
import org.schabi.newpipe.extractor.downloader.Request
import org.schabi.newpipe.extractor.downloader.Response
import org.schabi.newpipe.extractor.exceptions.ReCaptchaException
import java.util.concurrent.TimeUnit
class DownloaderTestImpl private constructor(builder: OkHttpClient.Builder) : Downloader() {
private val client: OkHttpClient = builder.readTimeout(30, TimeUnit.SECONDS).build()
override fun execute(request: Request): Response {
val httpMethod: String = request.httpMethod()
val url: String = request.url()
val headers: Map> = request.headers()
val dataToSend: ByteArray? = request.dataToSend()
var requestBody: RequestBody? = null
if (dataToSend != null) {
requestBody = dataToSend.toRequestBody(null, 0, dataToSend.size)
}
val requestBuilder: okhttp3.Request.Builder = okhttp3.Request.Builder()
.method(httpMethod, requestBody).url(url)
.addHeader("User-Agent", USER_AGENT)
for ((headerName, headerValueList) in headers) {
if (headerValueList.size > 1) {
requestBuilder.removeHeader(headerName)
for (headerValue in headerValueList) {
requestBuilder.addHeader(headerName, headerValue)
}
} else if (headerValueList.size == 1) {
requestBuilder.header(headerName, headerValueList[0])
}
}
val response = client.newCall(requestBuilder.build()).execute()
if (response.code == 429) {
response.close()
throw ReCaptchaException("reCaptcha Challenge requested", url)
}
val body = response.body
val responseBodyToReturn: String = body.string()
val latestUrl = response.request.url.toString()
return Response(
response.code, response.message, response.headers.toMultimap(),
responseBodyToReturn, latestUrl
)
}
companion object {
private const val USER_AGENT =
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36"
private var instance: DownloaderTestImpl? = null
/**
* It's recommended to call exactly once in the entire lifetime of the application.
*
* @param builder if null, default builder will be used
* @return a new instance of [DownloaderTestImpl]
*/
fun init(builder: OkHttpClient.Builder?): DownloaderTestImpl? {
instance = DownloaderTestImpl(
builder ?: OkHttpClient.Builder()
)
return instance
}
fun getInstance(): DownloaderTestImpl? {
if (instance == null) {
init(null)
}
return instance
}
}
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/MainActivity.kt
================================================
package com.lagradost.cloudstream3
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.content.res.ColorStateList
import android.content.res.Configuration
import android.graphics.Rect
import android.os.Bundle
import android.util.AttributeSet
import android.util.Log
import android.view.Gravity
import android.view.KeyEvent
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.CheckBox
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.annotation.IdRes
import androidx.annotation.MainThread
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.cardview.widget.CardView
import androidx.core.content.edit
import androidx.core.net.toUri
import androidx.core.view.children
import androidx.core.view.get
import androidx.core.view.isGone
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import androidx.core.view.marginStart
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.NavController
import androidx.navigation.NavDestination
import androidx.navigation.NavDestination.Companion.hierarchy
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.NavOptions
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.setupWithNavController
import androidx.preference.PreferenceManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSnapHelper
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.google.android.gms.cast.framework.CastContext
import com.google.android.gms.cast.framework.Session
import com.google.android.gms.cast.framework.SessionManager
import com.google.android.gms.cast.framework.SessionManagerListener
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.navigationrail.NavigationRailView
import com.google.android.material.snackbar.Snackbar
import com.google.common.collect.Comparators.min
import com.jaredrummler.android.colorpicker.ColorPickerDialogListener
import com.lagradost.cloudstream3.APIHolder.allProviders
import com.lagradost.cloudstream3.APIHolder.apis
import com.lagradost.cloudstream3.APIHolder.initAll
import com.lagradost.cloudstream3.CloudStreamApp.Companion.getKey
import com.lagradost.cloudstream3.CloudStreamApp.Companion.removeKey
import com.lagradost.cloudstream3.CloudStreamApp.Companion.setKey
import com.lagradost.cloudstream3.CommonActivity.loadThemes
import com.lagradost.cloudstream3.CommonActivity.onColorSelectedEvent
import com.lagradost.cloudstream3.CommonActivity.onDialogDismissedEvent
import com.lagradost.cloudstream3.CommonActivity.onUserLeaveHint
import com.lagradost.cloudstream3.CommonActivity.screenHeight
import com.lagradost.cloudstream3.CommonActivity.setActivityInstance
import com.lagradost.cloudstream3.CommonActivity.showToast
import com.lagradost.cloudstream3.CommonActivity.updateLocale
import com.lagradost.cloudstream3.CommonActivity.updateTheme
import com.lagradost.cloudstream3.actions.temp.fcast.FcastManager
import com.lagradost.cloudstream3.databinding.ActivityMainBinding
import com.lagradost.cloudstream3.databinding.ActivityMainTvBinding
import com.lagradost.cloudstream3.databinding.BottomResultviewPreviewBinding
import com.lagradost.cloudstream3.mvvm.Resource
import com.lagradost.cloudstream3.mvvm.logError
import com.lagradost.cloudstream3.mvvm.safe
import com.lagradost.cloudstream3.mvvm.observe
import com.lagradost.cloudstream3.mvvm.observeNullable
import com.lagradost.cloudstream3.network.initClient
import com.lagradost.cloudstream3.plugins.PluginManager
import com.lagradost.cloudstream3.plugins.PluginManager.___DO_NOT_CALL_FROM_A_PLUGIN_loadAllOnlinePlugins
import com.lagradost.cloudstream3.plugins.PluginManager.loadSinglePlugin
import com.lagradost.cloudstream3.receivers.VideoDownloadRestartReceiver
import com.lagradost.cloudstream3.services.SubscriptionWorkManager
import com.lagradost.cloudstream3.syncproviders.AccountManager
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.APP_STRING
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.APP_STRING_PLAYER
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.APP_STRING_REPO
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.APP_STRING_RESUME_WATCHING
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.APP_STRING_SEARCH
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.APP_STRING_SHARE
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.localListApi
import com.lagradost.cloudstream3.syncproviders.SyncAPI
import com.lagradost.cloudstream3.ui.APIRepository
import com.lagradost.cloudstream3.ui.SyncWatchType
import com.lagradost.cloudstream3.ui.WatchType
import com.lagradost.cloudstream3.ui.account.AccountHelper.showAccountSelectLinear
import com.lagradost.cloudstream3.ui.download.DOWNLOAD_NAVIGATE_TO
import com.lagradost.cloudstream3.ui.home.HomeViewModel
import com.lagradost.cloudstream3.ui.library.LibraryViewModel
import com.lagradost.cloudstream3.ui.player.BasicLink
import com.lagradost.cloudstream3.ui.player.GeneratorPlayer
import com.lagradost.cloudstream3.ui.player.LinkGenerator
import com.lagradost.cloudstream3.ui.result.LinearListLayout
import com.lagradost.cloudstream3.ui.result.ResultViewModel2
import com.lagradost.cloudstream3.ui.result.START_ACTION_RESUME_LATEST
import com.lagradost.cloudstream3.ui.result.SyncViewModel
import com.lagradost.cloudstream3.ui.search.SearchFragment
import com.lagradost.cloudstream3.ui.search.SearchResultBuilder
import com.lagradost.cloudstream3.ui.settings.Globals.EMULATOR
import com.lagradost.cloudstream3.ui.settings.Globals.PHONE
import com.lagradost.cloudstream3.ui.settings.Globals.TV
import com.lagradost.cloudstream3.ui.settings.Globals.isLandscape
import com.lagradost.cloudstream3.ui.settings.Globals.isLayout
import com.lagradost.cloudstream3.ui.settings.Globals.updateTv
import com.lagradost.cloudstream3.ui.settings.SettingsGeneral
import com.lagradost.cloudstream3.ui.setup.HAS_DONE_SETUP_KEY
import com.lagradost.cloudstream3.ui.setup.SetupFragmentExtensions
import com.lagradost.cloudstream3.utils.ApkInstaller
import com.lagradost.cloudstream3.utils.AppContextUtils.getApiDubstatusSettings
import com.lagradost.cloudstream3.utils.AppContextUtils.html
import com.lagradost.cloudstream3.utils.AppContextUtils.isCastApiAvailable
import com.lagradost.cloudstream3.utils.AppContextUtils.isLtr
import com.lagradost.cloudstream3.utils.AppContextUtils.isNetworkAvailable
import com.lagradost.cloudstream3.utils.AppContextUtils.isRtl
import com.lagradost.cloudstream3.utils.AppContextUtils.loadCache
import com.lagradost.cloudstream3.utils.AppContextUtils.loadRepository
import com.lagradost.cloudstream3.utils.AppContextUtils.loadResult
import com.lagradost.cloudstream3.utils.AppContextUtils.loadSearchResult
import com.lagradost.cloudstream3.utils.AppContextUtils.setDefaultFocus
import com.lagradost.cloudstream3.utils.AppContextUtils.updateHasTrailers
import com.lagradost.cloudstream3.utils.BackPressedCallbackHelper.attachBackPressedCallback
import com.lagradost.cloudstream3.utils.BackPressedCallbackHelper.detachBackPressedCallback
import com.lagradost.cloudstream3.utils.BackupUtils.backup
import com.lagradost.cloudstream3.utils.BackupUtils.setUpBackup
import com.lagradost.cloudstream3.utils.BiometricAuthenticator.BiometricCallback
import com.lagradost.cloudstream3.utils.BiometricAuthenticator.biometricPrompt
import com.lagradost.cloudstream3.utils.BiometricAuthenticator.deviceHasPasswordPinLock
import com.lagradost.cloudstream3.utils.BiometricAuthenticator.isAuthEnabled
import com.lagradost.cloudstream3.utils.BiometricAuthenticator.promptInfo
import com.lagradost.cloudstream3.utils.BiometricAuthenticator.startBiometricAuthentication
import com.lagradost.cloudstream3.utils.Coroutines.ioSafe
import com.lagradost.cloudstream3.utils.Coroutines.main
import com.lagradost.cloudstream3.utils.DataStore.getKey
import com.lagradost.cloudstream3.utils.DataStore.setKey
import com.lagradost.cloudstream3.utils.DataStoreHelper
import com.lagradost.cloudstream3.utils.DataStoreHelper.accounts
import com.lagradost.cloudstream3.utils.DataStoreHelper.migrateResumeWatching
import com.lagradost.cloudstream3.utils.Event
import com.lagradost.cloudstream3.utils.ImageLoader.loadImage
import com.lagradost.cloudstream3.utils.InAppUpdater.runAutoUpdate
import com.lagradost.cloudstream3.utils.SingleSelectionHelper.showBottomDialog
import com.lagradost.cloudstream3.utils.SnackbarHelper.showSnackbar
import com.lagradost.cloudstream3.utils.TvChannelUtils
import com.lagradost.cloudstream3.utils.UIHelper.changeStatusBarState
import com.lagradost.cloudstream3.utils.UIHelper.checkWrite
import com.lagradost.cloudstream3.utils.UIHelper.dismissSafe
import com.lagradost.cloudstream3.utils.UIHelper.enableEdgeToEdgeCompat
import com.lagradost.cloudstream3.utils.UIHelper.fixSystemBarsPadding
import com.lagradost.cloudstream3.utils.UIHelper.getResourceColor
import com.lagradost.cloudstream3.utils.UIHelper.hideKeyboard
import com.lagradost.cloudstream3.utils.UIHelper.navigate
import com.lagradost.cloudstream3.utils.UIHelper.requestRW
import com.lagradost.cloudstream3.utils.UIHelper.setNavigationBarColorCompat
import com.lagradost.cloudstream3.utils.UIHelper.toPx
import com.lagradost.cloudstream3.utils.USER_PROVIDER_API
import com.lagradost.cloudstream3.utils.USER_SELECTED_HOMEPAGE_API
import com.lagradost.cloudstream3.utils.setText
import com.lagradost.cloudstream3.utils.setTextHtml
import com.lagradost.cloudstream3.utils.txt
import com.lagradost.safefile.SafeFile
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import java.io.File
import java.lang.ref.WeakReference
import java.net.URI
import java.net.URLDecoder
import java.nio.charset.Charset
import kotlin.math.abs
import kotlin.math.absoluteValue
import kotlin.system.exitProcess
import com.lagradost.cloudstream3.utils.downloader.DownloadQueueManager
class MainActivity : AppCompatActivity(), ColorPickerDialogListener, BiometricCallback {
companion object {
var activityResultLauncher: ActivityResultLauncher? = null
const val TAG = "MAINACT"
const val ANIMATED_OUTLINE: Boolean = false
var lastError: String? = null
/** Update lastError variable based on error file, to check if app crashed.
* Can be called multiple times without changing the lastError variable changing.
**/
fun setLastError(context: Context) {
if (lastError != null) return
val errorFile = context.filesDir.resolve("last_error")
if (errorFile.exists() && errorFile.isFile) {
lastError = errorFile.readText(Charset.defaultCharset())
errorFile.delete()
} else {
lastError = null
}
}
private const val FILE_DELETE_KEY = "FILES_TO_DELETE_KEY"
const val API_NAME_EXTRA_KEY = "API_NAME_EXTRA_KEY"
/**
* Transient files to delete on application exit.
* Deletes files on onDestroy().
*/
private var filesToDelete: Set
// This needs to be persistent because the application may exit without calling onDestroy.
get() = getKey>(FILE_DELETE_KEY) ?: setOf()
private set(value) = setKey(FILE_DELETE_KEY, value)
/**
* Add file to delete on Exit.
*/
fun deleteFileOnExit(file: File) {
filesToDelete = filesToDelete + file.path
}
/**
* Setting this will automatically enter the query in the search
* next time the search fragment is opened.
* This variable will clear itself after one use. Null does nothing.
*
* This is a very bad solution but I was unable to find a better one.
**/
var nextSearchQuery: String? = null
/**
* Fires every time a new batch of plugins have been loaded, no guarantee about how often this is run and on which thread
* Boolean signifies if stuff should be force reloaded (true if force reload, false if reload when necessary).
*
* The force reloading are used for plugin development to instantly reload the page on deployWithAdb
* */
val afterPluginsLoadedEvent = Event()
val mainPluginsLoadedEvent =
Event() // homepage api, used to speed up time to load for homepage
val afterRepositoryLoadedEvent = Event()
// kinda shitty solution, but cant com main->home otherwise for popups
val bookmarksUpdatedEvent = Event()
/**
* Used by DataStoreHelper to fully reload home when switching accounts
*/
val reloadHomeEvent = Event()
/**
* Used by DataStoreHelper to fully reload library when switching accounts
*/
val reloadLibraryEvent = Event()
/**
* Used by DataStoreHelper to fully reload Navigation Rail header picture
*/
val reloadAccountEvent = Event()
/**
* @return true if the str has launched an app task (be it successful or not)
* @param isWebview does not handle providers and opening download page if true. Can still add repos and login.
* */
@Suppress("DEPRECATION_ERROR")
fun handleAppIntentUrl(
activity: FragmentActivity?,
str: String?,
isWebview: Boolean,
extraArgs: Bundle? = null
): Boolean =
with(activity) {
// TODO MUCH BETTER HANDLING
// Invalid URIs can crash
fun safeURI(uri: String) = safe { URI(uri) }
if (str != null && this != null) {
if (str.startsWith("https://cs.repo")) {
val realUrl = "https://" + str.substringAfter("?")
println("Repository url: $realUrl")
loadRepository(realUrl)
return true
} else if (str.contains(APP_STRING)) {
for (api in AccountManager.allApis) {
if (api.isValidRedirectUrl(str)) {
ioSafe {
Log.i(TAG, "handleAppIntent $str")
try {
val isSuccessful = api.login(str)
if (isSuccessful) {
Log.i(TAG, "authenticated ${api.name}")
} else {
Log.i(TAG, "failed to authenticate ${api.name}")
}
showToast(
if (isSuccessful) {
txt(R.string.authenticated_user, api.name)
} else {
txt(R.string.authenticated_user_fail, api.name)
}
)
} catch (t: Throwable) {
logError(t)
showToast(
txt(R.string.authenticated_user_fail, api.name)
)
}
}
return true
}
}
// This specific intent is used for the gradle deployWithAdb
// https://github.com/recloudstream/gradle/blob/master/src/main/kotlin/com/lagradost/cloudstream3/gradle/tasks/DeployWithAdbTask.kt#L46
if (str == "$APP_STRING:") {
ioSafe {
PluginManager.___DO_NOT_CALL_FROM_A_PLUGIN_hotReloadAllLocalPlugins(
activity
)
}
}
} else if (safeURI(str)?.scheme == APP_STRING_REPO) {
val url = str.replaceFirst(APP_STRING_REPO, "https")
loadRepository(url)
return true
} else if (safeURI(str)?.scheme == APP_STRING_SEARCH) {
val query = str.substringAfter("$APP_STRING_SEARCH://")
nextSearchQuery =
try {
URLDecoder.decode(query, "UTF-8")
} catch (t: Throwable) {
logError(t)
query
}
// Use both navigation views to support both layouts.
// It might be better to use the QuickSearch.
activity?.findViewById(R.id.nav_view)?.selectedItemId =
R.id.navigation_search
activity?.findViewById(R.id.nav_rail_view)?.selectedItemId =
R.id.navigation_search
} else if (safeURI(str)?.scheme == APP_STRING_PLAYER) {
val uri = str.toUri()
val name = uri.getQueryParameter("name")
val url = URLDecoder.decode(uri.authority, "UTF-8")
navigate(
R.id.global_to_navigation_player,
GeneratorPlayer.newInstance(
LinkGenerator(
listOf(BasicLink(url, name)),
extract = true,
)
)
)
} else if (safeURI(str)?.scheme == APP_STRING_RESUME_WATCHING) {
val id =
str.substringAfter("$APP_STRING_RESUME_WATCHING://").toIntOrNull()
?: return false
ioSafe {
val resumeWatchingCard =
HomeViewModel.getResumeWatching()?.firstOrNull { it.id == id }
?: return@ioSafe
activity.loadSearchResult(
resumeWatchingCard,
START_ACTION_RESUME_LATEST
)
}
} else if (str.startsWith(APP_STRING_SHARE)) {
try {
val data = str.substringAfter("$APP_STRING_SHARE:")
val parts = data.split("?", limit = 2)
loadResult(
String(base64DecodeArray(parts[1]), Charsets.UTF_8),
String(base64DecodeArray(parts[0]), Charsets.UTF_8),
""
)
return true
} catch (e: Exception) {
showToast("Invalid Uri", Toast.LENGTH_SHORT)
return false
}
} else if (!isWebview) {
if (str.startsWith(DOWNLOAD_NAVIGATE_TO)) {
this.navigate(R.id.navigation_downloads)
return true
} else {
val apiName = extraArgs?.getString(API_NAME_EXTRA_KEY)
?.takeIf { it.isNotBlank() }
// if provided, try to match the api name instead of the api url
// this is in order to also support providers that use JSON dataUrls
// for example
if (apiName != null) {
loadResult(str, apiName, "")
return true
}
synchronized(apis) {
for (api in apis) {
if (str.startsWith(api.mainUrl)) {
loadResult(str, api.name, "")
return true
}
}
}
}
}
}
return false
}
fun centerView(view: View?) {
if (view == null) return
try {
Log.v(TAG, "centerView: $view")
val r = Rect(0, 0, 0, 0)
view.getDrawingRect(r)
val x = r.centerX()
val y = r.centerY()
val dx = r.width() / 2 //screenWidth / 2
val dy = screenHeight / 2
val r2 = Rect(x - dx, y - dy, x + dx, y + dy)
view.requestRectangleOnScreen(r2, false)
// TvFocus.current =TvFocus.current.copy(y=y.toFloat())
} catch (_: Throwable) {
}
}
}
var lastPopup: SearchResponse? = null
fun loadPopup(result: SearchResponse, load: Boolean = true) {
lastPopup = result
val syncName = syncViewModel.syncName(result.apiName)
// based on apiName we decide on if it is a local list or not, this is because
// we want to show a bit of extra UI to sync apis
if (result is SyncAPI.LibraryItem && syncName != null) {
isLocalList = false
syncViewModel.setSync(syncName, result.syncId)
syncViewModel.updateMetaAndUser()
} else {
isLocalList = true
syncViewModel.clear()
}
if (load) {
viewModel.load(
this, result.url, result.apiName, false, if (getApiDubstatusSettings()
.contains(DubStatus.Dubbed)
) DubStatus.Dubbed else DubStatus.Subbed, null
)
} else {
viewModel.loadSmall(result)
}
}
override fun onColorSelected(dialogId: Int, color: Int) {
onColorSelectedEvent.invoke(Pair(dialogId, color))
}
override fun onDialogDismissed(dialogId: Int) {
onDialogDismissedEvent.invoke(dialogId)
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
updateLocale() // android fucks me by chaining lang when rotating the phone
updateTheme(this) // Update if system theme
val navHostFragment =
supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
navHostFragment.navController.currentDestination?.let { updateNavBar(it) }
}
private fun updateNavBar(destination: NavDestination) {
this.hideKeyboard()
// Fucks up anime info layout since that has its own layout
binding?.castMiniControllerHolder?.isVisible =
!listOf(
R.id.navigation_results_phone,
R.id.navigation_results_tv,
R.id.navigation_player
).contains(destination.id)
val isNavVisible = listOf(
R.id.navigation_home,
R.id.navigation_search,
R.id.navigation_library,
R.id.navigation_downloads,
R.id.navigation_settings,
R.id.navigation_download_child,
R.id.navigation_download_queue,
R.id.navigation_subtitles,
R.id.navigation_chrome_subtitles,
R.id.navigation_settings_player,
R.id.navigation_settings_updates,
R.id.navigation_settings_ui,
R.id.navigation_settings_account,
R.id.navigation_settings_providers,
R.id.navigation_settings_general,
R.id.navigation_settings_extensions,
R.id.navigation_settings_plugins,
R.id.navigation_test_providers,
).contains(destination.id)
/*val dontPush = listOf(
R.id.navigation_home,
R.id.navigation_search,
R.id.navigation_results_phone,
R.id.navigation_results_tv,
R.id.navigation_player,
R.id.navigation_quick_search,
).contains(destination.id)
binding?.navHostFragment?.apply {
val params = layoutParams as ConstraintLayout.LayoutParams
val push =
if (!dontPush && isLayout(TV or EMULATOR)) resources.getDimensionPixelSize(R.dimen.navbar_width) else 0
if (!this.isLtr()) {
params.setMargins(
params.leftMargin,
params.topMargin,
push,
params.bottomMargin
)
} else {
params.setMargins(
push,
params.topMargin,
params.rightMargin,
params.bottomMargin
)
}
layoutParams = params
}*/
binding?.apply {
navRailView.isVisible = isNavVisible && isLandscape()
navView.isVisible = isNavVisible && !isLandscape()
navHostFragment.apply {
val marginPx = resources.getDimensionPixelSize(R.dimen.nav_rail_view_width)
layoutParams = (navHostFragment.layoutParams as ViewGroup.MarginLayoutParams).apply {
marginStart = if (isNavVisible && isLandscape() && isLayout(TV or EMULATOR)) marginPx else 0
}
}
/**
* We need to make sure if we return to a sub-fragment,
* the correct navigation item is selected so that it does not
* highlight the wrong one in UI.
*/
when (destination.id) {
in listOf(R.id.navigation_downloads, R.id.navigation_download_child, R.id.navigation_download_queue) -> {
navRailView.menu.findItem(R.id.navigation_downloads).isChecked = true
navView.menu.findItem(R.id.navigation_downloads).isChecked = true
}
in listOf(
R.id.navigation_settings,
R.id.navigation_subtitles,
R.id.navigation_chrome_subtitles,
R.id.navigation_settings_player,
R.id.navigation_settings_updates,
R.id.navigation_settings_ui,
R.id.navigation_settings_account,
R.id.navigation_settings_providers,
R.id.navigation_settings_general,
R.id.navigation_settings_extensions,
R.id.navigation_settings_plugins,
R.id.navigation_test_providers
) -> {
navRailView.menu.findItem(R.id.navigation_settings).isChecked = true
navView.menu.findItem(R.id.navigation_settings).isChecked = true
}
}
}
}
//private var mCastSession: CastSession? = null
var mSessionManager: SessionManager? = null
private val mSessionManagerListener: SessionManagerListener by lazy { SessionManagerListenerImpl() }
private inner class SessionManagerListenerImpl : SessionManagerListener {
override fun onSessionStarting(session: Session) {
}
override fun onSessionStarted(session: Session, sessionId: String) {
invalidateOptionsMenu()
}
override fun onSessionStartFailed(session: Session, i: Int) {
}
override fun onSessionEnding(session: Session) {
}
override fun onSessionResumed(session: Session, wasSuspended: Boolean) {
invalidateOptionsMenu()
}
override fun onSessionResumeFailed(session: Session, i: Int) {
}
override fun onSessionSuspended(session: Session, i: Int) {
}
override fun onSessionEnded(session: Session, error: Int) {
}
override fun onSessionResuming(session: Session, s: String) {
}
}
override fun onResume() {
super.onResume()
afterPluginsLoadedEvent += ::onAllPluginsLoaded
setActivityInstance(this)
try {
if (isCastApiAvailable()) {
mSessionManager?.addSessionManagerListener(mSessionManagerListener)
}
} catch (e: Exception) {
logError(e)
}
}
override fun onPause() {
super.onPause()
// Start any delayed updates
if (ApkInstaller.delayedInstaller?.startInstallation() == true) {
Toast.makeText(this, R.string.update_started, Toast.LENGTH_LONG).show()
}
try {
if (isCastApiAvailable()) {
mSessionManager?.removeSessionManagerListener(mSessionManagerListener)
//mCastSession = null
}
} catch (e: Exception) {
logError(e)
}
}
override fun dispatchKeyEvent(event: KeyEvent): Boolean =
CommonActivity.dispatchKeyEvent(this, event) ?: super.dispatchKeyEvent(event)
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean =
CommonActivity.onKeyDown(this, keyCode, event) ?: super.onKeyDown(keyCode, event)
override fun onUserLeaveHint() {
super.onUserLeaveHint()
onUserLeaveHint(this)
}
@SuppressLint("ApplySharedPref") // commit since the op needs to be synchronous
private fun showConfirmExitDialog(settingsManager: SharedPreferences) {
val confirmBeforeExit = settingsManager.getInt(getString(R.string.confirm_exit_key), -1)
if (confirmBeforeExit == 1 || (confirmBeforeExit == -1 && isLayout(PHONE))) {
// finish() causes a bug on some TVs where player
// may keep playing after closing the app.
if (isLayout(TV)) exitProcess(0) else finish()
return
}
val dialogView = layoutInflater.inflate(R.layout.confirm_exit_dialog, null)
val dontShowAgainCheck: CheckBox = dialogView.findViewById(R.id.checkboxDontShowAgain)
val builder: AlertDialog.Builder = AlertDialog.Builder(this)
builder.setView(dialogView)
.setTitle(R.string.confirm_exit_dialog)
.setNegativeButton(R.string.no) { _, _ -> /*NO-OP*/ }
.setPositiveButton(R.string.yes) { _, _ ->
if (dontShowAgainCheck.isChecked) {
settingsManager.edit(commit = true) {
putInt(getString(R.string.confirm_exit_key), 1)
}
}
// finish() causes a bug on some TVs where player
// may keep playing after closing the app.
if (isLayout(TV)) exitProcess(0) else finish()
}
builder.show().setDefaultFocus()
}
override fun onDestroy() {
filesToDelete.forEach { path ->
val result = File(path).deleteRecursively()
if (result) {
Log.d(TAG, "Deleted temporary file: $path")
} else {
Log.d(TAG, "Failed to delete temporary file: $path")
}
}
filesToDelete = setOf()
val broadcastIntent = Intent()
broadcastIntent.action = "restart_service"
broadcastIntent.setClass(this, VideoDownloadRestartReceiver::class.java)
this.sendBroadcast(broadcastIntent)
afterPluginsLoadedEvent -= ::onAllPluginsLoaded
detachBackPressedCallback("MainActivityDefault")
super.onDestroy()
}
override fun onNewIntent(intent: Intent) {
handleAppIntent(intent)
super.onNewIntent(intent)
}
private fun handleAppIntent(intent: Intent?) {
if (intent == null) return
val str = intent.dataString
loadCache()
handleAppIntentUrl(this, str, false, intent.extras)
}
private fun NavDestination.matchDestination(@IdRes destId: Int): Boolean =
hierarchy.any { it.id == destId }
private var lastNavTime = 0L
private fun onNavDestinationSelected(item: MenuItem, navController: NavController): Boolean {
val currentTime = System.currentTimeMillis()
// safeDebounce: Check if a previous tap happened within the last 400ms
if (currentTime - lastNavTime < 400) return false
lastNavTime = currentTime
val destinationId = item.itemId
// Check if we are already at the selected destination
if (navController.currentDestination?.id == destinationId) return false
// Make all nav buttons focus on this specific view when nextFocusRightId
val targetView = when (destinationId) {
// Please note that if R.id.navigation_home is readded, then it will only take affect when
// navigation to home for the second time as onNavDestinationSelected will not get called
// when first loading up the app
// R.id.navigation_home -> R.id.home_preview_change_api
R.id.navigation_search -> R.id.main_search
R.id.navigation_library -> R.id.main_search
R.id.navigation_downloads -> R.id.download_appbar
else -> null
}
if (targetView != null && isLayout(TV or EMULATOR)) {
val fromView = binding?.navRailView
if (fromView != null) {
fromView.nextFocusRightId = targetView
for (focusView in arrayOf(
R.id.navigation_downloads,
R.id.navigation_home,
R.id.navigation_search,
R.id.navigation_library,
R.id.navigation_settings,
)) {
fromView.findViewById(focusView)?.nextFocusRightId = targetView
}
}
}
val builder = NavOptions.Builder().setLaunchSingleTop(true).setRestoreState(true)
.setEnterAnim(R.anim.enter_anim)
.setExitAnim(R.anim.exit_anim)
.setPopEnterAnim(R.anim.pop_enter)
.setPopExitAnim(R.anim.pop_exit)
if (item.order and Menu.CATEGORY_SECONDARY == 0) {
builder.setPopUpTo(
navController.graph.findStartDestination().id,
inclusive = false,
saveState = true
)
}
return try {
navController.navigate(destinationId, null, builder.build())
navController.currentDestination?.matchDestination(destinationId) == true
} catch (e: IllegalArgumentException) {
Log.e("NavigationError", "Failed to navigate: ${e.message}")
false
}
}
private val pluginsLock = Mutex()
private fun onAllPluginsLoaded(success: Boolean = false) {
ioSafe {
pluginsLock.withLock {
synchronized(allProviders) {
// Load cloned sites after plugins have been loaded since clones depend on plugins.
try {
getKey>(USER_PROVIDER_API)?.let { list ->
list.forEach { custom ->
allProviders.firstOrNull { it.javaClass.simpleName == custom.parentJavaClass }
?.let {
allProviders.add(
it.javaClass.getDeclaredConstructor().newInstance()
.apply {
name = custom.name
lang = custom.lang
mainUrl = custom.url.trimEnd('/')
canBeOverridden = false
})
}
}
}
// it.hashCode() is not enough to make sure they are distinct
apis =
allProviders.distinctBy { it.lang + it.name + it.mainUrl + it.javaClass.name }
APIHolder.apiMap = null
} catch (e: Exception) {
logError(e)
}
}
}
}
}
lateinit var viewModel: ResultViewModel2
lateinit var syncViewModel: SyncViewModel
private var libraryViewModel: LibraryViewModel? = null
/** kinda dirty, however it signals that we should use the watch status as sync or not*/
var isLocalList: Boolean = false
override fun onCreateView(name: String, context: Context, attrs: AttributeSet): View? {
viewModel = ViewModelProvider(this)[ResultViewModel2::class.java]
syncViewModel = ViewModelProvider(this)[SyncViewModel::class.java]
return super.onCreateView(name, context, attrs)
}
private fun hidePreviewPopupDialog() {
bottomPreviewPopup.dismissSafe(this)
bottomPreviewPopup = null
bottomPreviewBinding = null
}
private var bottomPreviewPopup: Dialog? = null
private var bottomPreviewBinding: BottomResultviewPreviewBinding? = null
private fun showPreviewPopupDialog(): BottomResultviewPreviewBinding {
val ret = (bottomPreviewBinding ?: run {
val builder: Dialog
val layout: Int
if (isLayout(PHONE)) {
builder =
BottomSheetDialog(this)
layout = R.layout.bottom_resultview_preview
} else {
builder =
Dialog(this, R.style.DialogHalfFullscreen)
layout = R.layout.bottom_resultview_preview_tv
// No way to do this in styles :(
builder.window?.setGravity(Gravity.CENTER_VERTICAL or Gravity.END)
}
val root = layoutInflater.inflate(layout, null, false)
val binding = BottomResultviewPreviewBinding.bind(root)
bottomPreviewBinding = binding
builder.setContentView(root)
builder.setOnDismissListener {
bottomPreviewPopup = null
bottomPreviewBinding = null
viewModel.clear()
}
builder.setCanceledOnTouchOutside(true)
builder.show()
bottomPreviewPopup = builder
binding
})
return ret
}
var binding: ActivityMainBinding? = null
object TvFocus {
data class FocusTarget(
val width: Int,
val height: Int,
val x: Float,
val y: Float,
) {
companion object {
fun lerp(a: FocusTarget, b: FocusTarget, lerp: Float): FocusTarget {
val ilerp = 1 - lerp
return FocusTarget(
width = (a.width * ilerp + b.width * lerp).toInt(),
height = (a.height * ilerp + b.height * lerp).toInt(),
x = a.x * ilerp + b.x * lerp,
y = a.y * ilerp + b.y * lerp
)
}
}
}
var last: FocusTarget = FocusTarget(0, 0, 0.0f, 0.0f)
var current: FocusTarget = FocusTarget(0, 0, 0.0f, 0.0f)
var focusOutline: WeakReference = WeakReference(null)
var lastFocus: WeakReference = WeakReference(null)
private val layoutListener: View.OnLayoutChangeListener =
View.OnLayoutChangeListener { _, _, _, _, _, _, _, _, _ ->
// shitty fix for layouts
lastFocus.get()?.apply {
updateFocusView(
this, same = true
)
postDelayed({
updateFocusView(
lastFocus.get(), same = false
)
}, 300)
}
}
private val attachListener: View.OnAttachStateChangeListener =
object : View.OnAttachStateChangeListener {
override fun onViewAttachedToWindow(v: View) {
updateFocusView(v)
}
override fun onViewDetachedFromWindow(v: View) {
// removes the focus view but not the listener as updateFocusView(null) will remove the listener
focusOutline.get()?.isVisible = false
}
}
/*private val scrollListener = object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
current = current.copy(x = current.x + dx, y = current.y + dy)
setTargetPosition(current)
}
}*/
private fun setTargetPosition(target: FocusTarget) {
focusOutline.get()?.apply {
layoutParams = layoutParams?.apply {
width = target.width
height = target.height
}
translationX = target.x
translationY = target.y
bringToFront()
}
}
private var animator: ValueAnimator? = null
/** if this is enabled it will keep the focus unmoving
* during listview move */
private const val NO_MOVE_LIST: Boolean = false
/** If this is enabled then it will try to move the
* listview focus to the left instead of center */
private const val LEFTMOST_MOVE_LIST: Boolean = true
private val reflectedScroll by lazy {
try {
RecyclerView::class.java.declaredMethods.firstOrNull {
it.name == "scrollStep"
}?.also { it.isAccessible = true }
} catch (t: Throwable) {
null
}
}
@MainThread
fun updateFocusView(newFocus: View?, same: Boolean = false) {
val focusOutline = focusOutline.get() ?: return
val lastView = lastFocus.get()
val exactlyTheSame = lastView == newFocus && newFocus != null
if (!exactlyTheSame) {
lastView?.removeOnLayoutChangeListener(layoutListener)
lastView?.removeOnAttachStateChangeListener(attachListener)
(lastView?.parent as? RecyclerView)?.apply {
removeOnLayoutChangeListener(layoutListener)
//removeOnScrollListener(scrollListener)
}
}
val wasGone = focusOutline.isGone
val visible =
newFocus != null && newFocus.measuredHeight > 0 && newFocus.measuredWidth > 0 && newFocus.isShown && newFocus.tag != "tv_no_focus_tag"
focusOutline.isVisible = visible
if (newFocus != null) {
lastFocus = WeakReference(newFocus)
val parent = newFocus.parent
var targetDx = 0
if (parent is RecyclerView) {
val layoutManager = parent.layoutManager
if (layoutManager is LinearListLayout && layoutManager.orientation == LinearLayoutManager.HORIZONTAL) {
val dx =
LinearSnapHelper().calculateDistanceToFinalSnap(layoutManager, newFocus)
?.get(0)
if (dx != null) {
val rdx = if (LEFTMOST_MOVE_LIST) {
// this makes the item the leftmost in ltr, instead of center
val diff =
((layoutManager.width - layoutManager.paddingStart - newFocus.measuredWidth) / 2) - newFocus.marginStart
dx + if (parent.isRtl()) {
-diff
} else {
diff
}
} else {
if (dx > 0) dx else 0
}
if (!NO_MOVE_LIST) {
parent.smoothScrollBy(rdx, 0)
} else {
val smoothScroll = reflectedScroll
if (smoothScroll == null) {
parent.smoothScrollBy(rdx, 0)
} else {
try {
// this is very fucked but because it is a protected method to
// be able to compute the scroll I use reflection, scroll, then
// scroll back, then smooth scroll and set the no move
val out = IntArray(2)
smoothScroll.invoke(parent, rdx, 0, out)
val scrolledX = out[0]
if (abs(scrolledX) <= 0) { // newFocus.measuredWidth*2
smoothScroll.invoke(parent, -rdx, 0, out)
parent.smoothScrollBy(scrolledX, 0)
if (NO_MOVE_LIST) targetDx = scrolledX
}
} catch (t: Throwable) {
parent.smoothScrollBy(rdx, 0)
}
}
}
}
}
}
val out = IntArray(2)
newFocus.getLocationInWindow(out)
val (screenX, screenY) = out
var (x, y) = screenX.toFloat() to screenY.toFloat()
val (currentX, currentY) = focusOutline.translationX to focusOutline.translationY
if (!newFocus.isLtr()) {
x = x - focusOutline.rootView.width + newFocus.measuredWidth
}
x -= targetDx
// out of bounds = 0,0
if (screenX == 0 && screenY == 0) {
focusOutline.isVisible = false
}
if (!exactlyTheSame) {
(newFocus.parent as? RecyclerView)?.apply {
addOnLayoutChangeListener(layoutListener)
//addOnScrollListener(scrollListener)
}
newFocus.addOnLayoutChangeListener(layoutListener)
newFocus.addOnAttachStateChangeListener(attachListener)
}
val start = FocusTarget(
x = currentX,
y = currentY,
width = focusOutline.measuredWidth,
height = focusOutline.measuredHeight
)
val end = FocusTarget(
x = x,
y = y,
width = newFocus.measuredWidth,
height = newFocus.measuredHeight
)
// if they are the same within then snap, aka scrolling
val deltaMinX = min(end.width / 2, 60.toPx)
val deltaMinY = min(end.height / 2, 60.toPx)
if (start.width == end.width && start.height == end.height && (start.x - end.x).absoluteValue < deltaMinX && (start.y - end.y).absoluteValue < deltaMinY) {
animator?.cancel()
last = start
current = end
setTargetPosition(end)
return
}
// if running then "reuse"
if (animator?.isRunning == true) {
current = end
return
} else {
animator?.cancel()
}
last = start
current = end
// if previously gone, then tp
if (wasGone) {
setTargetPosition(current)
return
}
// animate between a and b
animator = ValueAnimator.ofFloat(0.0f, 1.0f).apply {
startDelay = 0
duration = 200
addUpdateListener { animation ->
val animatedValue = animation.animatedValue as Float
val target = FocusTarget.lerp(last, current, minOf(animatedValue, 1.0f))
setTargetPosition(target)
}
start()
}
// post check
if (!same) {
newFocus.postDelayed({
updateFocusView(lastFocus.get(), same = true)
}, 200)
}
/*
the following is working, but somewhat bad code code
if (!wasGone) {
(focusOutline.parent as? ViewGroup)?.let {
TransitionManager.endTransitions(it)
TransitionManager.beginDelayedTransition(
it,
TransitionSet().addTransition(ChangeBounds())
.addTransition(ChangeTransform())
.setDuration(100)
)
}
}
focusOutline.layoutParams = focusOutline.layoutParams?.apply {
width = newFocus.measuredWidth
height = newFocus.measuredHeight
}
focusOutline.translationX = x.toFloat()
focusOutline.translationY = y.toFloat()*/
}
}
}
@Suppress("DEPRECATION_ERROR")
override fun onCreate(savedInstanceState: Bundle?) {
app.initClient(this)
val settingsManager = PreferenceManager.getDefaultSharedPreferences(this)
setLastError(this)
val settingsForProvider = SettingsJson()
settingsForProvider.enableAdult =
settingsManager.getBoolean(getString(R.string.enable_nsfw_on_providers_key), false)
MainAPI.settingsForProvider = settingsForProvider
loadThemes(this)
enableEdgeToEdgeCompat()
setNavigationBarColorCompat(R.attr.primaryGrayBackground)
updateLocale()
super.onCreate(savedInstanceState)
try {
if (isCastApiAvailable()) {
CastContext.getSharedInstance(this) { it.run() }
.addOnSuccessListener { mSessionManager = it.sessionManager }
}
} catch (t: Throwable) {
logError(t)
}
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
updateTv()
// backup when we update the app, I don't trust myself to not boot lock users, might want to make this a setting?
safe {
val appVer = BuildConfig.VERSION_NAME
val lastAppAutoBackup: String = getKey("VERSION_NAME") ?: ""
if (appVer != lastAppAutoBackup) {
setKey("VERSION_NAME", BuildConfig.VERSION_NAME)
if (lastAppAutoBackup.isEmpty()) return@safe
safe {
backup(this)
}
safe {
// Recompile oat on new version
PluginManager.deleteAllOatFiles(this)
}
}
}
// just in case, MAIN SHOULD *NEVER* BOOT LOOP CRASH
binding = try {
if (isLayout(TV or EMULATOR)) {
val newLocalBinding = ActivityMainTvBinding.inflate(layoutInflater, null, false)
setContentView(newLocalBinding.root)
if (isLayout(TV) && ANIMATED_OUTLINE) {
TvFocus.focusOutline = WeakReference(newLocalBinding.focusOutline)
newLocalBinding.root.viewTreeObserver.addOnScrollChangedListener {
TvFocus.updateFocusView(TvFocus.lastFocus.get(), same = true)
}
newLocalBinding.root.viewTreeObserver.addOnGlobalFocusChangeListener { _, newFocus ->
TvFocus.updateFocusView(newFocus)
}
} else {
newLocalBinding.focusOutline.isVisible = false
}
if (isLayout(TV)) {
// Put here any button you don't want focusing it to center the view
val exceptionButtons = listOf(
//R.id.home_preview_play_btt,
R.id.home_preview_info_btt,
R.id.home_preview_hidden_next_focus,
R.id.home_preview_hidden_prev_focus,
R.id.result_play_movie_button,
R.id.result_play_series_button,
R.id.result_resume_series_button,
R.id.result_play_trailer_button,
R.id.result_bookmark_Button,
R.id.result_favorite_Button,
R.id.result_subscribe_Button,
R.id.result_search_Button,
R.id.result_episodes_show_button,
)
newLocalBinding.root.viewTreeObserver.addOnGlobalFocusChangeListener { _, newFocus ->
if (exceptionButtons.contains(newFocus?.id)) return@addOnGlobalFocusChangeListener
centerView(newFocus)
}
}
ActivityMainBinding.bind(newLocalBinding.root) // this may crash
} else {
val newLocalBinding = ActivityMainBinding.inflate(layoutInflater, null, false)
setContentView(newLocalBinding.root)
newLocalBinding
}
} catch (t: Throwable) {
showToast(txt(R.string.unable_to_inflate, t.message ?: ""), Toast.LENGTH_LONG)
null
}
binding?.apply {
fixSystemBarsPadding(
navView,
heightResId = R.dimen.nav_view_height,
padTop = false,
overlayCutout = false
)
fixSystemBarsPadding(
navRailView,
widthResId = R.dimen.nav_rail_view_width,
padRight = false,
padTop = false
)
}
// overscan
val padding = settingsManager.getInt(getString(R.string.overscan_key), 0).toPx
binding?.homeRoot?.setPadding(padding, padding, padding, padding)
changeStatusBarState(isLayout(EMULATOR))
/** Biometric stuff for users without accounts **/
val noAccounts = settingsManager.getBoolean(
getString(R.string.skip_startup_account_select_key),
false
) || accounts.count() <= 1
if (isLayout(PHONE) && isAuthEnabled(this) && noAccounts) {
if (deviceHasPasswordPinLock(this)) {
startBiometricAuthentication(this, R.string.biometric_authentication_title, false)
promptInfo?.let { prompt ->
biometricPrompt?.authenticate(prompt)
}
// hide background while authenticating, Sorry moms & dads 🙏
binding?.navHostFragment?.isInvisible = true
}
}
// Automatically enable jsdelivr if cant connect to raw.githubusercontent.com
if (this.getKey(getString(R.string.jsdelivr_proxy_key)) == null && isNetworkAvailable()) {
main {
if (checkGithubConnectivity()) {
this.setKey(getString(R.string.jsdelivr_proxy_key), false)
} else {
this.setKey(getString(R.string.jsdelivr_proxy_key), true)
showSnackbar(
this@MainActivity,
R.string.jsdelivr_enabled,
Snackbar.LENGTH_LONG,
R.string.revert
) { setKey(getString(R.string.jsdelivr_proxy_key), false) }
}
}
}
ioSafe { SafeFile.check(this@MainActivity) }
if (PluginManager.checkSafeModeFile()) {
safe {
showToast(R.string.safe_mode_file, Toast.LENGTH_LONG)
}
} else if (lastError == null) {
ioSafe {
DataStoreHelper.currentHomePage?.let { homeApi ->
mainPluginsLoadedEvent.invoke(loadSinglePlugin(this@MainActivity, homeApi))
} ?: run {
mainPluginsLoadedEvent.invoke(false)
}
ioSafe {
if (settingsManager.getBoolean(
getString(R.string.auto_update_plugins_key),
true
)
) {
PluginManager.___DO_NOT_CALL_FROM_A_PLUGIN_updateAllOnlinePluginsAndLoadThem(
this@MainActivity
)
} else {
___DO_NOT_CALL_FROM_A_PLUGIN_loadAllOnlinePlugins(this@MainActivity)
}
//Automatically download not existing plugins, using mode specified.
val autoDownloadPlugin = AutoDownloadMode.getEnum(
settingsManager.getInt(
getString(R.string.auto_download_plugins_key),
0
)
) ?: AutoDownloadMode.Disable
if (autoDownloadPlugin != AutoDownloadMode.Disable) {
PluginManager.___DO_NOT_CALL_FROM_A_PLUGIN_downloadNotExistingPluginsAndLoad(
this@MainActivity,
autoDownloadPlugin
)
}
}
ioSafe {
PluginManager.___DO_NOT_CALL_FROM_A_PLUGIN_loadAllLocalPlugins(
this@MainActivity,
false
)
}
// Add your channel creation here
}
} else {
val builder: AlertDialog.Builder = AlertDialog.Builder(this)
builder.setTitle(R.string.safe_mode_title)
builder.setMessage(R.string.safe_mode_description)
builder.apply {
setPositiveButton(R.string.safe_mode_crash_info) { _, _ ->
val tbBuilder: AlertDialog.Builder = AlertDialog.Builder(context)
tbBuilder.setTitle(R.string.safe_mode_title)
tbBuilder.setMessage(lastError)
tbBuilder.show()
}
setNegativeButton("Ok") { _, _ -> }
}
builder.show().setDefaultFocus()
}
fun setUserData(status: Resource?) {
if (isLocalList) return
bottomPreviewBinding?.apply {
when (status) {
is Resource.Success -> {
resultviewPreviewBookmark.isEnabled = true
resultviewPreviewBookmark.setText(status.value.status.stringRes)
resultviewPreviewBookmark.setIconResource(status.value.status.iconRes)
}
is Resource.Failure -> {
resultviewPreviewBookmark.isEnabled = false
resultviewPreviewBookmark.setIconResource(R.drawable.ic_baseline_bookmark_border_24)
resultviewPreviewBookmark.text = status.errorString
}
else -> {
resultviewPreviewBookmark.isEnabled = false
resultviewPreviewBookmark.setIconResource(R.drawable.ic_baseline_bookmark_border_24)
resultviewPreviewBookmark.setText(R.string.loading)
}
}
}
}
fun setWatchStatus(state: WatchType?) {
if (!isLocalList || state == null) return
bottomPreviewBinding?.resultviewPreviewBookmark?.apply {
setIconResource(state.iconRes)
setText(state.stringRes)
}
}
fun setSubscribeStatus(state: Boolean?) {
bottomPreviewBinding?.resultviewPreviewSubscribe?.apply {
if (state != null) {
val drawable = if (state) {
R.drawable.ic_baseline_notifications_active_24
} else {
R.drawable.baseline_notifications_none_24
}
setImageResource(drawable)
}
isVisible = state != null
setOnClickListener {
viewModel.toggleSubscriptionStatus(context) { newStatus: Boolean? ->
if (newStatus == null) return@toggleSubscriptionStatus
val message = if (newStatus) {
// Kinda icky to have this here, but it works.
SubscriptionWorkManager.enqueuePeriodicWork(context)
R.string.subscription_new
} else {
R.string.subscription_deleted
}
val name = (viewModel.page.value as? Resource.Success)?.value?.title
?: txt(R.string.no_data).asStringNull(context) ?: ""
showToast(txt(message, name), Toast.LENGTH_SHORT)
}
}
}
}
observe(viewModel.watchStatus, ::setWatchStatus)
observe(syncViewModel.userData, ::setUserData)
observeNullable(viewModel.subscribeStatus, ::setSubscribeStatus)
observeNullable(viewModel.page) { resource ->
if (resource == null) {
hidePreviewPopupDialog()
return@observeNullable
}
when (resource) {
is Resource.Failure -> {
showToast(R.string.error)
viewModel.clear()
hidePreviewPopupDialog()
}
is Resource.Loading -> {
showPreviewPopupDialog().apply {
resultviewPreviewLoading.isVisible = true
resultviewPreviewResult.isVisible = false
resultviewPreviewLoadingShimmer.startShimmer()
}
}
is Resource.Success -> {
val d = resource.value
showPreviewPopupDialog().apply {
resultviewPreviewLoading.isVisible = false
resultviewPreviewResult.isVisible = true
resultviewPreviewLoadingShimmer.stopShimmer()
resultviewPreviewTitle.text = d.title
resultviewPreviewMetaType.setText(d.typeText)
resultviewPreviewMetaYear.setText(d.yearText)
resultviewPreviewMetaDuration.setText(d.durationText)
resultviewPreviewMetaRating.setText(d.ratingText)
resultviewPreviewDescription.setTextHtml(d.plotText)
if (isLayout(PHONE)) {
resultviewPreviewPoster.loadImage(
d.posterImage ?: d.posterBackgroundImage,
headers = d.posterHeaders
)
} else {
resultviewPreviewPoster.loadImage(
d.posterBackgroundImage ?: d.posterImage,
headers = d.posterHeaders
)
}
setUserData(syncViewModel.userData.value)
setWatchStatus(viewModel.watchStatus.value)
setSubscribeStatus(viewModel.subscribeStatus.value)
resultviewPreviewBookmark.setOnClickListener {
//viewModel.updateWatchStatus(WatchType.PLANTOWATCH)
if (isLocalList) {
val value = viewModel.watchStatus.value ?: WatchType.NONE
this@MainActivity.showBottomDialog(
WatchType.entries.map { getString(it.stringRes) }.toList(),
value.ordinal,
this@MainActivity.getString(R.string.action_add_to_bookmarks),
showApply = false,
{}) {
viewModel.updateWatchStatus(
WatchType.entries[it],
this@MainActivity
)
}
} else {
val value =
(syncViewModel.userData.value as? Resource.Success)?.value?.status
?: SyncWatchType.NONE
this@MainActivity.showBottomDialog(
SyncWatchType.entries.map { getString(it.stringRes) }.toList(),
value.ordinal,
this@MainActivity.getString(R.string.action_add_to_bookmarks),
showApply = false,
{}) {
syncViewModel.setStatus(SyncWatchType.entries[it].internalId)
syncViewModel.publishUserData()
}
}
}
observeNullable(viewModel.favoriteStatus) observeFavoriteStatus@{ isFavorite ->
resultviewPreviewFavorite.isVisible = isFavorite != null
if (isFavorite == null) return@observeFavoriteStatus
val drawable = if (isFavorite) {
R.drawable.ic_baseline_favorite_24
} else {
R.drawable.ic_baseline_favorite_border_24
}
resultviewPreviewFavorite.setImageResource(drawable)
}
resultviewPreviewFavorite.setOnClickListener {
viewModel.toggleFavoriteStatus(this@MainActivity) { newStatus: Boolean? ->
if (newStatus == null) return@toggleFavoriteStatus
val message = if (newStatus) {
R.string.favorite_added
} else {
R.string.favorite_removed
}
val name = (viewModel.page.value as? Resource.Success)?.value?.title
?: txt(R.string.no_data).asStringNull(this@MainActivity) ?: ""
showToast(txt(message, name), Toast.LENGTH_SHORT)
}
}
if (isLayout(PHONE)) // dont want this clickable on tv layout
resultviewPreviewDescription.setOnClickListener { view ->
view.context?.let { ctx ->
val builder: AlertDialog.Builder =
AlertDialog.Builder(ctx, R.style.AlertDialogCustom)
builder.setMessage(d.plotText.asString(ctx).html())
.setTitle(d.plotHeaderText.asString(ctx))
.show()
}
}
resultviewPreviewMoreInfo.setOnClickListener {
viewModel.clear()
hidePreviewPopupDialog()
lastPopup?.let {
loadSearchResult(it)
}
}
}
}
}
}
// ioSafe {
// val plugins =
// RepositoryParser.getRepoPlugins("https://raw.githubusercontent.com/recloudstream/TestPlugin/master/repo.json")
// ?: emptyList()
// plugins.map {
// println("Load plugin: ${it.name} ${it.url}")
// RepositoryParser.loadSiteTemp(applicationContext, it.url, it.name)
// }
// }
// init accounts
ioSafe {
// we need to run this after we init all apis, otherwise currentSyncApi will fuck itself
this@MainActivity.runOnUiThread {
// Change library icon with logo of current api in sync
libraryViewModel =
ViewModelProvider(this@MainActivity)[LibraryViewModel::class.java]
libraryViewModel?.currentApiName?.observe(this@MainActivity) {
val syncAPI = libraryViewModel?.currentSyncApi
Log.i("SYNC_API", "${syncAPI?.name}, ${syncAPI?.idPrefix}")
val icon = if (syncAPI?.idPrefix == localListApi.idPrefix) {
R.drawable.library_icon_selector
} else {
syncAPI?.icon ?: R.drawable.library_icon_selector
}
binding?.apply {
navRailView.menu.findItem(R.id.navigation_library)?.setIcon(icon)
navView.menu.findItem(R.id.navigation_library)?.setIcon(icon)
}
}
}
}
SearchResultBuilder.updateCache(this)
ioSafe {
initAll()
// No duplicates (which can happen by registerMainAPI)
apis = synchronized(allProviders) {
allProviders.distinctBy { it }
}
}
// val navView: BottomNavigationView = findViewById(R.id.nav_view)
setUpBackup()
CommonActivity.init(this)
val navHostFragment =
supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
val navController = navHostFragment.navController
navController.addOnDestinationChangedListener { _: NavController, navDestination: NavDestination, bundle: Bundle? ->
// Intercept search and add a query
updateNavBar(navDestination)
if (navDestination.matchDestination(R.id.navigation_search) && !nextSearchQuery.isNullOrBlank()) {
bundle?.apply {
this.putString(SearchFragment.SEARCH_QUERY, nextSearchQuery)
}
}
if (navDestination.matchDestination(R.id.navigation_home)) {
attachBackPressedCallback("MainActivity") {
showConfirmExitDialog(settingsManager)
}
} else detachBackPressedCallback("MainActivity")
}
//val navController = findNavController(R.id.nav_host_fragment)
/*navOptions = NavOptions.Builder()
.setLaunchSingleTop(true)
.setEnterAnim(R.anim.nav_enter_anim)
.setExitAnim(R.anim.nav_exit_anim)
.setPopEnterAnim(R.anim.nav_pop_enter)
.setPopExitAnim(R.anim.nav_pop_exit)
.setPopUpTo(navController.graph.startDestination, false)
.build()*/
val rippleColor = ColorStateList.valueOf(getResourceColor(R.attr.colorPrimary, 0.1f))
binding?.navView?.apply {
itemRippleColor = rippleColor
itemActiveIndicatorColor = rippleColor
setupWithNavController(navController)
setOnItemSelectedListener { item ->
onNavDestinationSelected(
item,
navController
)
}
}
binding?.navRailView?.apply {
if (isLayout(PHONE)) {
itemRippleColor = rippleColor
itemActiveIndicatorColor = rippleColor
} else {
val rippleColor = ColorStateList.valueOf(getResourceColor(R.attr.textColor, 1.0f))
val rippleColorTransparent =
ColorStateList.valueOf(getResourceColor(R.attr.textColor, 0.2f))
itemSpacing = 12.toPx // expandedItemSpacing does not have an attr
itemRippleColor = rippleColorTransparent
itemActiveIndicatorColor = rippleColor
}
setupWithNavController(navController)
/*if (isLayout(TV or EMULATOR)) {
background?.alpha = 200
} else {
background?.alpha = 255
}*/
setOnItemSelectedListener { item ->
onNavDestinationSelected(
item,
navController
)
}
fun noFocus(view: View) {
view.tag = view.context.getString(R.string.tv_no_focus_tag)
(view as? ViewGroup)?.let {
for (child in it.children) {
noFocus(child)
}
}
}
//noFocus(this)
val navProfileRoot = findViewById(R.id.nav_footer_root)
if (isLayout(TV or EMULATOR)) {
val navProfilePic = findViewById(R.id.nav_footer_profile_pic)
val navProfileCard = findViewById(R.id.nav_footer_profile_card)
navProfileCard?.setOnClickListener {
showAccountSelectLinear()
}
val homeViewModel =
ViewModelProvider(this@MainActivity)[HomeViewModel::class.java]
observe(homeViewModel.currentAccount) { currentAccount ->
if (currentAccount != null) {
navProfilePic?.loadImage(
currentAccount.image
)
navProfileRoot.isVisible = true
} else {
navProfileRoot.isGone = true
}
}
} else {
navProfileRoot.isGone = true
}
}
val rail = binding?.navRailView
if (rail != null) {
binding?.navRailView?.labelVisibilityMode =
NavigationRailView.LABEL_VISIBILITY_UNLABELED
//val focus = mutableSetOf()
var prevId: Int? = null
var prevView: View? = null
// The genius engineers at google did not actually
// write a nextFocus for the navrail
rail.findViewById(R.id.navigation_settings)?.nextFocusDownId =
R.id.nav_footer_profile_card
for (id in arrayOf(
R.id.navigation_home,
R.id.navigation_search,
R.id.navigation_library,
R.id.navigation_downloads,
R.id.navigation_settings
)) {
val view = rail.findViewById(id) ?: continue
prevId?.let { view.nextFocusUpId = it }
prevView?.nextFocusDownId = id
prevView = view
prevId = id
// Uncomment for focus expand
/*if (!isLayout(TV)) {
view.onFocusChangeListener = null
} else {
view.onFocusChangeListener =
View.OnFocusChangeListener { v, hasFocus ->
if (hasFocus) {
focus += id
binding?.navRailView?.labelVisibilityMode =
NavigationRailView.LABEL_VISIBILITY_LABELED
binding?.navRailView?.expand()
} else {
focus -= id
v.post {
if (focus.isEmpty()) {
binding?.navRailView?.labelVisibilityMode =
NavigationRailView.LABEL_VISIBILITY_UNLABELED
binding?.navRailView?.collapse()
}
}
}
}
}*/
}
}
// Navigation button long click functionality to scroll to top
for (view in listOf(binding?.navView, binding?.navRailView)) {
view?.findViewById(R.id.navigation_home)?.setOnLongClickListener {
val recycler = binding?.root?.findViewById(R.id.home_master_recycler)
recycler?.smoothScrollToPosition(0)
return@setOnLongClickListener recycler != null
}
view?.findViewById(R.id.navigation_library)?.setOnLongClickListener {
val viewPager = binding?.root?.findViewById(R.id.viewpager)
?: return@setOnLongClickListener false
try {
val children = (viewPager[0] as? RecyclerView)?.children
?: return@setOnLongClickListener false
for (child in children) {
child.findViewById(R.id.page_recyclerview)
?.smoothScrollToPosition(0)
}
} catch (_: IndexOutOfBoundsException) {
} catch (t: Throwable) {
logError(t)
}
return@setOnLongClickListener true
}
view?.findViewById(R.id.navigation_search)?.setOnLongClickListener {
for (recyclerId in arrayOf(
R.id.search_master_recycler,
R.id.search_autofit_results,
R.id.search_history_recycler
)) {
val recycler = binding?.root?.findViewById(recyclerId)
?: return@setOnLongClickListener false
recycler.smoothScrollToPosition(0)
}
return@setOnLongClickListener true
}
view?.findViewById(R.id.navigation_downloads)?.setOnLongClickListener {
val recycler: RecyclerView? = binding?.root?.findViewById(R.id.download_list)
?: binding?.root?.findViewById(R.id.download_child_list)
recycler?.smoothScrollToPosition(0)
return@setOnLongClickListener recycler != null
}
}
loadCache()
updateHasTrailers()
/*nav_view.setOnNavigationItemSelectedListener { item ->
when (item.itemId) {
R.id.navigation_home -> {
navController.navigate(R.id.navigation_home, null, navOptions)
}
R.id.navigation_search -> {
navController.navigate(R.id.navigation_search, null, navOptions)
}
R.id.navigation_downloads -> {
navController.navigate(R.id.navigation_downloads, null, navOptions)
}
R.id.navigation_settings -> {
navController.navigate(R.id.navigation_settings, null, navOptions)
}
}
true
}*/
if (!checkWrite()) {
requestRW()
if (checkWrite()) return
}
//CastButtonFactory.setUpMediaRouteButton(this, media_route_button)
// THIS IS CURRENTLY REMOVED BECAUSE HIGHER VERS OF ANDROID NEEDS A NOTIFICATION
//if (!VideoDownloadManager.isMyServiceRunning(this, VideoDownloadKeepAliveService::class.java)) {
// val mYourService = VideoDownloadKeepAliveService()
// val mServiceIntent = Intent(this, mYourService::class.java).putExtra(START_VALUE_KEY, RESTART_ALL_DOWNLOADS_AND_QUEUE)
// this.startService(mServiceIntent)
//}
//settingsManager.getBoolean("disable_automatic_data_downloads", true) &&
// TODO RETURN TO TRUE
/*
if (isUsingMobileData()) {
Toast.makeText(this, "Downloads not resumed on mobile data", Toast.LENGTH_LONG).show()
} else {
val keys = getKeys(VideoDownloadManager.KEY_RESUME_PACKAGES)
val resumePkg = keys.mapNotNull { k -> getKey(k) }
// To remove a bug where this is permanent
removeKeys(VideoDownloadManager.KEY_RESUME_PACKAGES)
for (pkg in resumePkg) { // ADD ALL CURRENT DOWNLOADS
VideoDownloadManager.downloadFromResume(this, pkg, false)
}
// ADD QUEUE
// array needed because List gets cast exception to linkedList for some unknown reason
val resumeQueue =
getKey>(VideoDownloadManager.KEY_RESUME_QUEUE_PACKAGES)
resumeQueue?.sortedBy { it.index }?.forEach {
VideoDownloadManager.downloadFromResume(this, it.pkg)
}
}*/
/*
val castContext = CastContext.getSharedInstance(applicationContext)
fun buildMediaQueueItem(video: String): MediaQueueItem {
// val movieMetadata = MediaMetadata(MediaMetadata.MEDIA_TYPE_PHOTO)
//movieMetadata.putString(MediaMetadata.KEY_TITLE, "CloudStream")
val mediaInfo = MediaInfo.Builder(video.toUri().toString())
.setStreamType(MediaInfo.STREAM_TYPE_NONE)
.setContentType(MimeTypes.IMAGE_JPEG)
// .setMetadata(movieMetadata).build()
.build()
return MediaQueueItem.Builder(mediaInfo).build()
}*/
/*
castContext.addCastStateListener { state ->
if (state == CastState.CONNECTED) {
println("TESTING")
val isCasting = castContext?.sessionManager?.currentCastSession?.remoteMediaClient?.currentItem != null
if(!isCasting) {
val castPlayer = CastPlayer(castContext)
println("LOAD ITEM")
castPlayer.loadItem(buildMediaQueueItem("https://cdn.discordapp.com/attachments/551382684560261121/730169809408622702/ChromecastLogo6.png"),0)
}
}
}*/
/*thread {
createISO()
}*/
if (BuildConfig.DEBUG) {
var providersAndroidManifestString = "Current androidmanifest should be:\n"
synchronized(allProviders) {
for (api in allProviders) {
providersAndroidManifestString += "\n"
}
}
println(providersAndroidManifestString)
}
handleAppIntent(intent)
ioSafe {
runAutoUpdate()
}
FcastManager().init(this, false)
APIRepository.dubStatusActive = getApiDubstatusSettings()
try {
// this ensures that no unnecessary space is taken
loadCache()
File(filesDir, "exoplayer").deleteRecursively() // old cache
deleteFileOnExit(File(cacheDir, "exoplayer")) // current cache
} catch (e: Exception) {
logError(e)
}
println("Loaded everything")
ioSafe {
migrateResumeWatching()
}
main {
val channelId =
TvChannelUtils.getChannelId(this@MainActivity, getString(R.string.app_name))
if (channelId == null) {
Log.d("TvChannel", "Channel not found, creating")
TvChannelUtils.createTvChannel(this@MainActivity)
} else {
Log.d("TvChannel", "Channel ID: $channelId")
}
}
getKey(USER_SELECTED_HOMEPAGE_API)?.let { homepage ->
DataStoreHelper.currentHomePage = homepage
removeKey(USER_SELECTED_HOMEPAGE_API)
}
try {
if (getKey(HAS_DONE_SETUP_KEY, false) != true) {
navController.navigate(R.id.navigation_setup_language)
// If no plugins bring up extensions screen
} else if (PluginManager.getPluginsOnline().isEmpty()
&& PluginManager.getPluginsLocal().isEmpty()
// && PREBUILT_REPOSITORIES.isNotEmpty()
) {
navController.navigate(
R.id.navigation_setup_extensions,
SetupFragmentExtensions.newInstance(false)
)
}
} catch (e: Exception) {
logError(e)
}
// Used to check current focus for TV
// main {
// while (true) {
// delay(5000)
// println("Current focus: $currentFocus")
// showToast(this, currentFocus.toString(), Toast.LENGTH_LONG)
// }
// }
attachBackPressedCallback("MainActivityDefault") {
setNavigationBarColorCompat(R.attr.primaryGrayBackground)
updateLocale()
runDefault()
}
// Start the download queue
DownloadQueueManager.init(this)
}
/** Biometric stuff **/
override fun onAuthenticationSuccess() {
// make background (nav host fragment) visible again
binding?.navHostFragment?.isInvisible = false
}
override fun onAuthenticationError() {
finish()
}
suspend fun checkGithubConnectivity(): Boolean {
return try {
app.get(
"https://raw.githubusercontent.com/recloudstream/.github/master/connectivitycheck",
timeout = 5
).text.trim() == "ok"
} catch (t: Throwable) {
false
}
}
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/actions/AlwaysAskAction.kt
================================================
package com.lagradost.cloudstream3.actions
import android.content.Context
import com.lagradost.cloudstream3.R
import com.lagradost.cloudstream3.ui.result.LinkLoadingResult
import com.lagradost.cloudstream3.ui.result.ResultEpisode
import com.lagradost.cloudstream3.utils.txt
class AlwaysAskAction : VideoClickAction() {
override val name = txt(R.string.player_settings_always_ask)
override val isPlayer = true
// Only show in settings, not on a video
override fun shouldShow(context: Context?, video: ResultEpisode?): Boolean = video == null
override suspend fun runAction(
context: Context?,
video: ResultEpisode,
result: LinkLoadingResult,
index: Int?
) {
// This is handled specially in ResultViewModel2.kt by detecting the AlwaysAskAction
// and showing the player selection dialog instead of executing the action directly
throw NotImplementedError("AlwaysAskAction is handled specially by the calling code")
}
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/actions/OpenInAppAction.kt
================================================
package com.lagradost.cloudstream3.actions
import android.app.Activity
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import androidx.core.content.FileProvider
import androidx.core.net.toUri
import com.lagradost.cloudstream3.CloudStreamApp.Companion.getKey
import com.lagradost.cloudstream3.CloudStreamApp.Companion.setKey
import com.lagradost.cloudstream3.R
import com.lagradost.cloudstream3.mvvm.logError
import com.lagradost.cloudstream3.ui.result.LinkLoadingResult
import com.lagradost.cloudstream3.ui.result.ResultEpisode
import com.lagradost.cloudstream3.ui.result.ResultFragment
import com.lagradost.cloudstream3.utils.UiText
import com.lagradost.cloudstream3.utils.txt
import com.lagradost.cloudstream3.utils.AppContextUtils.isAppInstalled
import com.lagradost.cloudstream3.utils.DataStoreHelper
import java.io.File
fun updateDurationAndPosition(position: Long, duration: Long) {
if (position <= 0 || duration <= 0) return
val episode = getKey("last_opened") ?: return
DataStoreHelper.setViewPosAndResume(episode.id, position, duration, episode, null)
ResultFragment.updateUI()
}
/**
* Util method that may be helpful for creating intents for apps that support m3u8 files.
* All sources are written to a temporary m3u8 file, which is then sent to the app.
*/
fun makeTempM3U8Intent(
context: Context,
intent: Intent,
result: LinkLoadingResult
) {
if (result.links.size == 1) {
intent.setDataAndType(result.links.first().url.toUri(), "video/*")
return
}
intent.apply {
addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION)
addFlags(Intent.FLAG_GRANT_PREFIX_URI_PERMISSION)
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
}
val outputFile = File.createTempFile("mirrorlist", ".m3u8", context.cacheDir)
var text = "#EXTM3U\n#EXT-X-VERSION:3"
result.links.forEach { link ->
text += "\n#EXTINF:0,${link.name}\n${link.url}"
}
//With subtitles it doesn't work for no reason :(
/*for (sub in result.subs) {
val normalizedName = sub.name.replace("[^a-zA-Z0-9 ]".toRegex(), "")
text += "\n#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID=\"subs\",NAME=\"${normalizedName}\",DEFAULT=NO,AUTOSELECT=NO,FORCED=NO,LANGUAGE=\"${sub.languageCode}\",URI=\"${sub.url}\""
}*/
text += "\n#EXT-X-ENDLIST"
outputFile.writeText(text)
intent.setDataAndType(
FileProvider.getUriForFile(
context,
context.applicationContext.packageName + ".provider",
outputFile
), "application/x-mpegURL"
)
}
abstract class OpenInAppAction(
open val appName: UiText,
open val packageName: String,
private val intentClass: String? = null,
private val action: String = Intent.ACTION_VIEW
) : VideoClickAction() {
override val name: UiText
get() = txt(R.string.episode_action_play_in_format, appName)
override val isPlayer = true
override fun shouldShow(context: Context?, video: ResultEpisode?) =
context?.isAppInstalled(packageName) != false
override suspend fun runAction(
context: Context?,
video: ResultEpisode,
result: LinkLoadingResult,
index: Int?
) {
if (context == null) return
val intent = Intent(action)
intent.setPackage(packageName)
if (intentClass != null) {
intent.component = ComponentName(packageName, intentClass)
}
putExtra(context, intent, video, result, index)
setKey("last_opened", video)
launchResult(intent)
}
/**
* Before intent is sent, this function is called to put extra data into the intent.
* @see VideoClickAction.runAction
* */
@Throws
abstract suspend fun putExtra(
context: Context,
intent: Intent,
video: ResultEpisode,
result: LinkLoadingResult,
index: Int?
)
/**
* This function is called when the app is opened again after the intent was sent.
* You can use it to for example update duration and position.
* @see updateDurationAndPosition
*/
@Throws
abstract fun onResult(activity: Activity, intent: Intent?)
/** Safe version of onResult, we don't trust extension devs to not crash the app */
fun onResultSafe(activity: Activity, intent: Intent?) {
try {
onResult(activity, intent)
} catch (t: Throwable) {
logError(t)
}
}
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/actions/VideoClickAction.kt
================================================
package com.lagradost.cloudstream3.actions
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.core.app.ActivityOptionsCompat
import com.lagradost.api.Log
import com.lagradost.cloudstream3.CommonActivity
import com.lagradost.cloudstream3.ErrorLoadingException
import com.lagradost.cloudstream3.MainActivity
import com.lagradost.cloudstream3.R
import com.lagradost.cloudstream3.actions.temp.BiglyBTPackage
import com.lagradost.cloudstream3.actions.temp.CopyClipboardAction
import com.lagradost.cloudstream3.actions.temp.JustPlayerPackage
import com.lagradost.cloudstream3.actions.temp.LibreTorrentPackage
import com.lagradost.cloudstream3.actions.temp.MpvExPackage
import com.lagradost.cloudstream3.actions.temp.MpvKtPackage
import com.lagradost.cloudstream3.actions.temp.MpvKtPreviewPackage
import com.lagradost.cloudstream3.actions.temp.MpvPackage
import com.lagradost.cloudstream3.actions.temp.MpvYTDLPackage
import com.lagradost.cloudstream3.actions.temp.NextPlayerPackage
import com.lagradost.cloudstream3.actions.temp.PlayInBrowserAction
import com.lagradost.cloudstream3.actions.temp.PlayMirrorAction
import com.lagradost.cloudstream3.actions.temp.ViewM3U8Action
import com.lagradost.cloudstream3.actions.temp.VlcNightlyPackage
import com.lagradost.cloudstream3.actions.temp.VlcPackage
import com.lagradost.cloudstream3.actions.temp.WebVideoCastPackage
import com.lagradost.cloudstream3.actions.temp.fcast.FcastAction
import com.lagradost.cloudstream3.mvvm.logError
import com.lagradost.cloudstream3.ui.result.LinkLoadingResult
import com.lagradost.cloudstream3.ui.result.ResultEpisode
import com.lagradost.cloudstream3.utils.Coroutines.ioSafe
import com.lagradost.cloudstream3.utils.Coroutines.threadSafeListOf
import com.lagradost.cloudstream3.utils.ExtractorLinkType
import com.lagradost.cloudstream3.utils.UiText
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.util.concurrent.Callable
import java.util.concurrent.FutureTask
import kotlin.reflect.jvm.jvmName
object VideoClickActionHolder {
val allVideoClickActions = threadSafeListOf(
// Default
PlayInBrowserAction(),
CopyClipboardAction(),
ViewM3U8Action(),
PlayMirrorAction(),
// main support external apps
VlcPackage(),
MpvPackage(),
MpvExPackage(),
NextPlayerPackage(),
JustPlayerPackage(),
FcastAction(),
LibreTorrentPackage(),
BiglyBTPackage(),
// forks/backup apps
VlcNightlyPackage(),
WebVideoCastPackage(),
MpvYTDLPackage(),
MpvKtPackage(),
MpvKtPreviewPackage(),
// Always Ask option
AlwaysAskAction(),
// added by plugins
// ...
)
init {
Log.d("VideoClickActionHolder", "allVideoClickActions: ${allVideoClickActions.map { it.uniqueId() }}")
}
private const val ACTION_ID_OFFSET = 1000
fun makeOptionMap(activity: Activity?, video: ResultEpisode) = allVideoClickActions
// We need to have index before filtering
.mapIndexed { id, it -> it to id + ACTION_ID_OFFSET }
.filter { it.first.shouldShowSafe(activity, video) }
.map { it.first.name to it.second }
fun getActionById(id: Int): VideoClickAction? = allVideoClickActions.getOrNull(id - ACTION_ID_OFFSET)
fun getByUniqueId(uniqueId: String): VideoClickAction? = allVideoClickActions.firstOrNull { it.uniqueId() == uniqueId }
fun uniqueIdToId(uniqueId: String?): Int? {
if (uniqueId == null) return null
return allVideoClickActions
.mapIndexed { id, it -> it to id + ACTION_ID_OFFSET }
.firstOrNull { it.first.uniqueId() == uniqueId }
?.second
}
fun getPlayers(activity: Activity? = null) = allVideoClickActions.filter { it.isPlayer && it.shouldShowSafe(activity, null) }
}
abstract class VideoClickAction {
abstract val name: UiText
/** if true, the app will show dialog to select source - result.links[index] */
open val oneSource : Boolean = false
/** if true, this action could be selected as default player (one press action) in settings */
open val isPlayer: Boolean = false
/** Which type of sources this action can handle. */
open val sourceTypes: Set = ExtractorLinkType.entries.toSet()
/** Determines which plugin a given provider is from. This is the full path to the plugin. */
var sourcePlugin: String? = null
/** Even if VideoClickAction should not run any UI code, startActivity requires it,
* this is a wrapper for runOnUiThread in a suspended safe context that bubble up exceptions */
@Throws
suspend fun uiThread(callable : Callable) : T? {
val future = FutureTask{
try {
Result.success(callable.call())
} catch (t : Throwable) {
Result.failure(t)
}
}
CommonActivity.activity?.runOnUiThread(future) ?: throw ErrorLoadingException("No UI Activity, this should never happened")
val result = withContext(Dispatchers.IO) {
return@withContext future.get()
}
return result.getOrThrow()
}
/** Internally uses activityResultLauncher,
* use this when the activity has a result like watched position */
@Throws
suspend fun launchResult(intent : Intent?, options : ActivityOptionsCompat? = null) {
if (intent == null) {
return
}
uiThread {
MainActivity.activityResultLauncher?.launch(intent,options)
}
}
/** Internally uses startActivity, use this when you don't
* have any result that needs to be stored when exiting the activity */
@Throws
suspend fun launch(intent : Intent?, bundle : Bundle? = null) {
if (intent == null) {
return
}
uiThread {
CommonActivity.activity?.startActivity(intent, bundle)
}
}
fun uniqueId() = "$sourcePlugin:${this::class.jvmName}"
@Throws
abstract fun shouldShow(context: Context?, video: ResultEpisode?): Boolean
/** Safe version of shouldShow, as we don't trust extension devs to handle exceptions,
* however no dev *should* throw in shouldShow */
fun shouldShowSafe(context: Context?, video: ResultEpisode?): Boolean {
return try {
shouldShow(context,video)
} catch (t : Throwable) {
logError(t)
false
}
}
/**
* This function is called when the action is clicked.
* @param context The current activity
* @param video The episode/movie that was clicked
* @param result The result of the link loading, contains video & subtitle links
* @param index if oneSource is true, this is the index of the selected source
*/
@Throws
abstract suspend fun runAction(context: Context?, video: ResultEpisode, result: LinkLoadingResult, index: Int?)
/** Safe version of runAction, as we don't trust extension devs to handle exceptions */
fun runActionSafe(context: Context?, video: ResultEpisode, result: LinkLoadingResult, index: Int?) = ioSafe {
try {
runAction(context, video, result, index)
} catch (_ : NotImplementedError) {
CommonActivity.showToast("runAction has not been implemented for ${name.asStringNull(context)}, please contact the extension developer of $sourcePlugin", Toast.LENGTH_LONG)
} catch (error : ErrorLoadingException) {
CommonActivity.showToast(error.message, Toast.LENGTH_LONG)
} catch (_: ActivityNotFoundException) {
CommonActivity.showToast(R.string.app_not_found_error, Toast.LENGTH_LONG)
} catch (t : Throwable) {
logError(t)
CommonActivity.showToast(t.toString(), Toast.LENGTH_LONG)
}
}
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/actions/temp/Aria2Package.kt
================================================
package com.lagradost.cloudstream3.actions.temp
import android.app.Activity
import android.content.Context
import android.content.Intent
import com.lagradost.cloudstream3.actions.OpenInAppAction
import com.lagradost.cloudstream3.ui.result.LinkLoadingResult
import com.lagradost.cloudstream3.ui.result.ResultEpisode
import com.lagradost.cloudstream3.utils.txt
/** https://github.com/devgianlu/Aria2Android */
@Suppress("unused")
class Aria2Package : OpenInAppAction(
appName = txt("Aria2"),
packageName = "com.gianlu.aria2android",
intentClass = "com.gianlu.aria2android.MainActivity"
) {
override val oneSource: Boolean = true
override suspend fun putExtra(
context: Context,
intent: Intent,
video: ResultEpisode,
result: LinkLoadingResult,
index: Int?
) {
throw NotImplementedError("Aria2Android is missing getIntent, and onNewIntent, meaning it cant handle intents")
}
override fun onResult(activity: Activity, intent: Intent?) = Unit
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/actions/temp/BiglyBTPackage.kt
================================================
package com.lagradost.cloudstream3.actions.temp
import android.app.Activity
import android.content.Context
import android.content.Intent
import androidx.core.net.toUri
import com.lagradost.cloudstream3.actions.OpenInAppAction
import com.lagradost.cloudstream3.ui.result.LinkLoadingResult
import com.lagradost.cloudstream3.ui.result.ResultEpisode
import com.lagradost.cloudstream3.utils.ExtractorLinkType
import com.lagradost.cloudstream3.utils.txt
/** https://github.com/BiglySoftware/BiglyBT-Android */
class BiglyBTPackage : OpenInAppAction(
appName = txt("BiglyBT"),
packageName = "com.biglybt.android.client",
intentClass = "com.biglybt.android.client.activity.IntentHandler"
) {
// Only torrents are supported by the app
override val sourceTypes: Set =
setOf(ExtractorLinkType.MAGNET, ExtractorLinkType.TORRENT)
override val oneSource: Boolean = true
override suspend fun putExtra(
context: Context,
intent: Intent,
video: ResultEpisode,
result: LinkLoadingResult,
index: Int?
) {
intent.data = result.links[index!!].url.toUri()
}
override fun onResult(activity: Activity, intent: Intent?) = Unit
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/actions/temp/CloudStreamPackage.kt
================================================
package com.lagradost.cloudstream3.actions.temp
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import com.fasterxml.jackson.annotation.JsonProperty
import com.lagradost.cloudstream3.actions.OpenInAppAction
import com.lagradost.cloudstream3.BuildConfig
import com.lagradost.cloudstream3.ui.player.ExtractorUri
import com.lagradost.cloudstream3.ui.player.SubtitleData
import com.lagradost.cloudstream3.ui.player.SubtitleOrigin
import com.lagradost.cloudstream3.ui.result.LinkLoadingResult
import com.lagradost.cloudstream3.ui.result.ResultEpisode
import com.lagradost.cloudstream3.utils.AppUtils.toJson
import com.lagradost.cloudstream3.utils.DataStoreHelper.getViewPos
import com.lagradost.cloudstream3.utils.DrmExtractorLink
import com.lagradost.cloudstream3.utils.ExtractorLink
import com.lagradost.cloudstream3.utils.ExtractorLinkPlayList
import com.lagradost.cloudstream3.utils.ExtractorLinkType
import com.lagradost.cloudstream3.utils.newExtractorLink
import com.lagradost.cloudstream3.utils.Qualities
import com.lagradost.cloudstream3.utils.SubtitleHelper.fromCodeToLangTagIETF
import com.lagradost.cloudstream3.utils.SubtitleHelper.fromLanguageToTagIETF
import com.lagradost.cloudstream3.utils.txt
/**
* If you want to support CloudStream 3 as an external player, then this shows how to play any video link
* For basic interactions, just `intent.data = uri` works
*
* However for more advanced use, CloudStream 3 also supports playlists of MinimalVideoLink and MinimalSubtitleLink with a `String[]` of JSON
* These are passed as LINKS_EXTRA and SUBTITLE_EXTRA respectively
*/
@Suppress("Unused")
class CloudStreamPackage : OpenInAppAction(
appName = txt("CloudStream"),
packageName = BuildConfig.APPLICATION_ID, //"com.lagradost.cloudstream3" or "com.lagradost.cloudstream3.prerelease"
intentClass = "com.lagradost.cloudstream3.ui.player.DownloadedPlayerActivity"
) {
override val oneSource: Boolean = false
companion object {
const val SUBTITLE_EXTRA: String = "subs" // Json of an array of MinimalVideoLink
const val LINKS_EXTRA: String = "links" // Json of an array of MinimalSubtitleLink
const val TITLE_EXTRA: String = "title" // Unused (String)
const val ID_EXTRA: String =
"id" // Identification number for the video(s), used to store start time (Int)
const val POSITION_EXTRA: String = "pos" // Start time in MS (Long)
const val DURATION_EXTRA: String = "dur" // Duration time in MS (Long)
}
data class MinimalVideoLink(
@JsonProperty("uri")
val uri: Uri?,
@JsonProperty("url")
val url: String?,
@JsonProperty("mimeType")
val mimeType: String = "video/mp4",
@JsonProperty("name")
val name: String?,
@JsonProperty("headers")
var headers: Map = mapOf(),
@JsonProperty("quality")
val quality: Int?,
) {
companion object {
fun fromExtractor(link: ExtractorLink): MinimalVideoLink = MinimalVideoLink(
uri = null,
url = link.url,
name = link.name,
mimeType = link.type.getMimeType(),
headers = if (link.referer.isBlank()) emptyMap() else mapOf("referer" to link.referer) + link.headers,
quality = link.quality
)
}
suspend fun toExtractorLink(): Pair =
url?.let { url ->
newExtractorLink(
source = "NONE",
name = name ?: "Unknown",
url = url,
type = ExtractorLinkType.entries.firstOrNull { ty -> ty.getMimeType() == mimeType }
?: ExtractorLinkType.VIDEO) {
this@newExtractorLink.headers =
this@MinimalVideoLink.headers
this@newExtractorLink.quality =
this@MinimalVideoLink.quality ?: Qualities.Unknown.value
}
} to uri?.let { uri ->
ExtractorUri(
uri = uri,
name = name ?: "Unknown",
)
}
}
data class MinimalSubtitleLink(
@JsonProperty("url")
val url: String,
@JsonProperty("mimeType")
val mimeType: String = "text/vtt",
@JsonProperty("name")
val name: String?,
@JsonProperty("headers")
var headers: Map = mapOf(),
) {
companion object {
fun fromSubtitle(sub: SubtitleData): MinimalSubtitleLink = MinimalSubtitleLink(
url = sub.url,
mimeType = sub.mimeType,
name = sub.originalName,
headers = sub.headers,
)
}
fun toSubtitleData(): SubtitleData = SubtitleData(
url = url,
nameSuffix = "",
mimeType = mimeType,
originalName = name ?: "Unknown",
headers = headers,
origin = SubtitleOrigin.URL,
languageCode = fromCodeToLangTagIETF(name) ?:
fromLanguageToTagIETF(name, true) ?:
name,
)
}
override suspend fun putExtra(
context: Context,
intent: Intent,
video: ResultEpisode,
result: LinkLoadingResult,
index: Int?
) {
intent.apply {
val position = getViewPos(video.id)?.position
if (position != null)
putExtra(POSITION_EXTRA, position)
putExtra(ID_EXTRA, video.id)
putExtra(TITLE_EXTRA, video.name)
putExtra(
SUBTITLE_EXTRA,
result.subs.map { MinimalSubtitleLink.fromSubtitle(it).toJson() }.toTypedArray()
)
putExtra(
LINKS_EXTRA,
result.links.filter { it !is ExtractorLinkPlayList && it !is DrmExtractorLink }
.map { MinimalVideoLink.fromExtractor(it).toJson() }.toTypedArray()
)
}
}
override fun onResult(activity: Activity, intent: Intent?) {
// No results yet
}
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/actions/temp/CopyClipboardAction.kt
================================================
package com.lagradost.cloudstream3.actions.temp
import android.content.Context
import com.lagradost.cloudstream3.actions.VideoClickAction
import com.lagradost.cloudstream3.ui.result.LinkLoadingResult
import com.lagradost.cloudstream3.ui.result.ResultEpisode
import com.lagradost.cloudstream3.utils.txt
import com.lagradost.cloudstream3.utils.UIHelper.clipboardHelper
class CopyClipboardAction: VideoClickAction() {
override val name = txt("Copy to clipboard")
override val oneSource = true
override fun shouldShow(context: Context?, video: ResultEpisode?) = true
override suspend fun runAction(
context: Context?,
video: ResultEpisode,
result: LinkLoadingResult,
index: Int?
) {
if (index == null) return
val link = result.links.getOrNull(index) ?: return
clipboardHelper(txt(link.name), link.url)
}
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/actions/temp/JustPlayerPackage.kt
================================================
package com.lagradost.cloudstream3.actions.temp
import android.app.Activity
import android.content.Context
import android.content.Intent
import androidx.core.net.toUri
import com.lagradost.cloudstream3.actions.OpenInAppAction
import com.lagradost.cloudstream3.ui.result.LinkLoadingResult
import com.lagradost.cloudstream3.ui.result.ResultEpisode
import com.lagradost.cloudstream3.utils.ExtractorLinkType
import com.lagradost.cloudstream3.utils.txt
/** https://github.com/moneytoo/Player/ */
class JustPlayerPackage : OpenInAppAction(
appName = txt("JustPlayer"),
packageName = "com.brouken.player",
intentClass = "com.brouken.player.PlayerActivity"
) {
override val sourceTypes: Set =
setOf(ExtractorLinkType.VIDEO, ExtractorLinkType.M3U8, ExtractorLinkType.DASH)
override val oneSource: Boolean = true
override suspend fun putExtra(
context: Context,
intent: Intent,
video: ResultEpisode,
result: LinkLoadingResult,
index: Int?
) {
// While JustPlayer has support for subs, it cant add both subs and links at the same time
// See https://github.com/moneytoo/Player/blob/49d80eb8de7a7bfc662393fdf114788fed1ebb2e/app/src/main/java/com/brouken/player/PlayerActivity.java#L794
intent.data = result.links[index!!].url.toUri()
}
override fun onResult(activity: Activity, intent: Intent?) = Unit
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/actions/temp/LibreTorrentPackage.kt
================================================
package com.lagradost.cloudstream3.actions.temp
import android.app.Activity
import android.content.Context
import android.content.Intent
import androidx.core.net.toUri
import com.lagradost.cloudstream3.actions.OpenInAppAction
import com.lagradost.cloudstream3.ui.result.LinkLoadingResult
import com.lagradost.cloudstream3.ui.result.ResultEpisode
import com.lagradost.cloudstream3.utils.ExtractorLinkType
import com.lagradost.cloudstream3.utils.txt
/** https://github.com/proninyaroslav/libretorrent */
class LibreTorrentPackage : OpenInAppAction(
appName = txt("LibreTorrent"),
packageName = "org.proninyaroslav.libretorrent",
intentClass = "org.proninyaroslav.libretorrent.ui.addtorrent.AddTorrentActivity"
) {
// Only torrents are supported by the app
override val sourceTypes: Set =
setOf(ExtractorLinkType.MAGNET, ExtractorLinkType.TORRENT)
override val oneSource: Boolean = true
override suspend fun putExtra(
context: Context,
intent: Intent,
video: ResultEpisode,
result: LinkLoadingResult,
index: Int?
) {
intent.data = result.links[index!!].url.toUri()
}
override fun onResult(activity: Activity, intent: Intent?) = Unit
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/actions/temp/MpvKtPackage.kt
================================================
package com.lagradost.cloudstream3.actions.temp
import android.app.Activity
import android.content.Context
import android.content.Intent
import androidx.core.net.toUri
import com.lagradost.cloudstream3.actions.OpenInAppAction
import com.lagradost.cloudstream3.actions.updateDurationAndPosition
import com.lagradost.cloudstream3.ui.result.LinkLoadingResult
import com.lagradost.cloudstream3.ui.result.ResultEpisode
import com.lagradost.cloudstream3.utils.txt
import com.lagradost.cloudstream3.utils.DataStoreHelper.getViewPos
import com.lagradost.cloudstream3.utils.ExtractorLinkType
class MpvKtPreviewPackage: MpvKtPackage(
appName = "mpvKt Preview",
packageName = "live.mehiz.mpvkt.preview",
)
open class MpvKtPackage(
appName: String = "mpvKt",
packageName: String = "live.mehiz.mpvkt",
): OpenInAppAction(
appName = txt(appName),
packageName = packageName,
intentClass = "live.mehiz.mpvkt.ui.player.PlayerActivity"
) {
override val oneSource = true
override val sourceTypes = setOf(
ExtractorLinkType.VIDEO,
ExtractorLinkType.DASH,
ExtractorLinkType.M3U8
)
override suspend fun putExtra(
context: Context,
intent: Intent,
video: ResultEpisode,
result: LinkLoadingResult,
index: Int?
) {
val link = result.links.getOrNull(index ?: 0) ?: return
intent.apply {
putExtra("subs", result.subs.map { it.url.toUri() }.toTypedArray())
setDataAndType(link.url.toUri(), "video/*")
// m3u8 plays, but changing sources feature is not available
// makeTempM3U8Intent(activity, this, result)
//putExtra("headers", link.headers.flatMap { listOf(it.key, it.value) }.toTypedArray())
val position = getViewPos(video.id)?.position
if (position != null)
putExtra("position", position.toInt())
putExtra("secure_uri", true)
}
}
override fun onResult(activity: Activity, intent: Intent?) {
val position = intent?.getIntExtra("position", -1)?.toLong() ?: -1
val duration = intent?.getIntExtra("duration", -1)?.toLong() ?: -1
updateDurationAndPosition(position, duration)
}
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/actions/temp/MpvPackage.kt
================================================
package com.lagradost.cloudstream3.actions.temp
import android.app.Activity
import android.content.Context
import android.content.Intent
import androidx.core.net.toUri
import com.lagradost.api.Log
import com.lagradost.cloudstream3.actions.OpenInAppAction
import com.lagradost.cloudstream3.actions.makeTempM3U8Intent
import com.lagradost.cloudstream3.actions.updateDurationAndPosition
import com.lagradost.cloudstream3.ui.result.LinkLoadingResult
import com.lagradost.cloudstream3.ui.result.ResultEpisode
import com.lagradost.cloudstream3.utils.txt
import com.lagradost.cloudstream3.utils.DataStoreHelper.getViewPos
import com.lagradost.cloudstream3.utils.ExtractorLinkType
// https://github.com/mpv-android/mpv-android/blob/0eb3cdc6f1632636b9c30d52ec50e4b017661980/app/src/main/java/is/xyz/mpv/MPVActivity.kt#L904
// https://mpv-android.github.io/mpv-android/intent.html
//https://github.com/marlboro-advance/mpvEx
class MpvExPackage: MpvPackage("mpvEx","app.marlboroadvance.mpvex","app.marlboroadvance.mpvex.ui.player.PlayerActivity")
class MpvYTDLPackage : MpvPackage("MPV YTDL", "is.xyz.mpv.ytdl") {
override val sourceTypes = setOf(
ExtractorLinkType.VIDEO,
ExtractorLinkType.DASH,
ExtractorLinkType.M3U8
)
}
open class MpvPackage(appName: String = "MPV", packageName: String = "is.xyz.mpv",intentClass:String = "is.xyz.mpv.MPVActivity"): OpenInAppAction(
txt(appName),
packageName,
intentClass
) {
override val oneSource = true // mpv has poor playlist support on TV
override suspend fun putExtra(
context: Context,
intent: Intent,
video: ResultEpisode,
result: LinkLoadingResult,
index: Int?
) {
intent.apply {
putExtra("subs", result.subs.map { it.url.toUri() }.toTypedArray())
putExtra("title", video.name)
if (index != null) {
setDataAndType((result.links.getOrNull(index)?.url ?: return).toUri(), "video/*")
} else {
makeTempM3U8Intent(context, this, result)
}
val position = getViewPos(video.id)?.position
if (position != null)
putExtra("position", position.toInt())
putExtra("secure_uri", true)
}
}
override fun onResult(activity: Activity, intent: Intent?) {
val position = intent?.getIntExtra("position", -1) ?: -1
val duration = intent?.getIntExtra("duration", -1) ?: -1
Log.d("MPV", "Position: $position, Duration: $duration")
updateDurationAndPosition(position.toLong(), duration.toLong())
}
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/actions/temp/NextPlayerPackage.kt
================================================
package com.lagradost.cloudstream3.actions.temp
import android.app.Activity
import android.content.Context
import android.content.Intent
import androidx.core.net.toUri
import com.lagradost.cloudstream3.actions.OpenInAppAction
import com.lagradost.cloudstream3.ui.result.LinkLoadingResult
import com.lagradost.cloudstream3.ui.result.ResultEpisode
import com.lagradost.cloudstream3.utils.ExtractorLinkType
import com.lagradost.cloudstream3.utils.txt
/** https://github.com/anilbeesetti/nextplayer */
class NextPlayerPackage : OpenInAppAction(
appName = txt("NextPlayer"),
packageName = "dev.anilbeesetti.nextplayer",
intentClass = "dev.anilbeesetti.nextplayer.feature.player.PlayerActivity"
) {
override val sourceTypes: Set =
setOf(ExtractorLinkType.VIDEO, ExtractorLinkType.M3U8, ExtractorLinkType.DASH)
override val oneSource: Boolean = true
override suspend fun putExtra(
context: Context,
intent: Intent,
video: ResultEpisode,
result: LinkLoadingResult,
index: Int?
) {
intent.data = result.links[index!!].url.toUri()
}
override fun onResult(activity: Activity, intent: Intent?) = Unit
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/actions/temp/PlayInBrowserAction.kt
================================================
package com.lagradost.cloudstream3.actions.temp
import android.content.Context
import android.content.Intent
import androidx.core.net.toUri
import com.lagradost.cloudstream3.R
import com.lagradost.cloudstream3.actions.VideoClickAction
import com.lagradost.cloudstream3.ui.result.LinkLoadingResult
import com.lagradost.cloudstream3.ui.result.ResultEpisode
import com.lagradost.cloudstream3.utils.txt
import com.lagradost.cloudstream3.utils.ExtractorLinkType
class PlayInBrowserAction: VideoClickAction() {
override val name = txt(R.string.episode_action_play_in_format, "Browser")
override val oneSource = true
override val isPlayer = true
override val sourceTypes: Set = setOf(
ExtractorLinkType.VIDEO,
ExtractorLinkType.DASH,
ExtractorLinkType.M3U8
)
override fun shouldShow(context: Context?, video: ResultEpisode?) = true
override suspend fun runAction(
context: Context?,
video: ResultEpisode,
result: LinkLoadingResult,
index: Int?
) {
val link = result.links.getOrNull(index ?: 0) ?: return
val i = Intent(Intent.ACTION_VIEW)
i.data = link.url.toUri()
launch(i)
}
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/actions/temp/PlayMirrorAction.kt
================================================
package com.lagradost.cloudstream3.actions.temp
import android.app.Activity
import android.content.Context
import com.lagradost.cloudstream3.R
import com.lagradost.cloudstream3.actions.VideoClickAction
import com.lagradost.cloudstream3.ui.player.ExtractorUri
import com.lagradost.cloudstream3.ui.player.GeneratorPlayer
import com.lagradost.cloudstream3.ui.player.LOADTYPE_INAPP
import com.lagradost.cloudstream3.ui.player.SubtitleData
import com.lagradost.cloudstream3.ui.player.VideoGenerator
import com.lagradost.cloudstream3.ui.result.LinkLoadingResult
import com.lagradost.cloudstream3.ui.result.ResultEpisode
import com.lagradost.cloudstream3.utils.ExtractorLink
import com.lagradost.cloudstream3.utils.ExtractorLinkType
import com.lagradost.cloudstream3.utils.UIHelper.navigate
import com.lagradost.cloudstream3.utils.txt
class PlayMirrorAction : VideoClickAction() {
override val name = txt(R.string.episode_action_play_mirror)
override val oneSource = true
override val isPlayer = true
override val sourceTypes: Set = LOADTYPE_INAPP
override fun shouldShow(context: Context?, video: ResultEpisode?) = true
override suspend fun runAction(
context: Context?,
video: ResultEpisode,
result: LinkLoadingResult,
index: Int?
) {
//Implemented a generator to handle the single
val activity = context as? Activity ?: return
val generatorMirror = object : VideoGenerator(listOf(video)) {
override val hasCache: Boolean = false
override val canSkipLoading: Boolean = false
override suspend fun generateLinks(
clearCache: Boolean,
sourceTypes: Set,
callback: (Pair) -> Unit,
subtitleCallback: (SubtitleData) -> Unit,
offset: Int,
isCasting: Boolean
): Boolean {
index?.let { callback(result.links[it] to null) }
result.subs.forEach { subtitle -> subtitleCallback(subtitle) }
return true
}
}
activity.navigate(
R.id.global_to_navigation_player,
GeneratorPlayer.newInstance(
generatorMirror, result.syncData
)
)
}
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/actions/temp/ViewM3U8Action.kt
================================================
package com.lagradost.cloudstream3.actions.temp
import android.content.Context
import android.content.Intent
import com.lagradost.cloudstream3.R
import com.lagradost.cloudstream3.actions.VideoClickAction
import com.lagradost.cloudstream3.actions.makeTempM3U8Intent
import com.lagradost.cloudstream3.ui.result.LinkLoadingResult
import com.lagradost.cloudstream3.ui.result.ResultEpisode
import com.lagradost.cloudstream3.utils.txt
class ViewM3U8Action: VideoClickAction() {
override val name = txt(R.string.episode_action_play_in_format, "m3u8 player")
override val isPlayer = true
override fun shouldShow(context: Context?, video: ResultEpisode?) = true
override suspend fun runAction(
context: Context?,
video: ResultEpisode,
result: LinkLoadingResult,
index: Int?
) {
if (context == null) return
val i = Intent(Intent.ACTION_VIEW)
makeTempM3U8Intent(context, i, result)
launch(i)
}
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/actions/temp/VlcPackage.kt
================================================
package com.lagradost.cloudstream3.actions.temp
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.core.net.toUri
import com.lagradost.api.Log
import com.lagradost.cloudstream3.CloudStreamApp.Companion.getKey
import com.lagradost.cloudstream3.actions.OpenInAppAction
import com.lagradost.cloudstream3.actions.makeTempM3U8Intent
import com.lagradost.cloudstream3.actions.updateDurationAndPosition
import com.lagradost.cloudstream3.ui.result.LinkLoadingResult
import com.lagradost.cloudstream3.ui.result.ResultEpisode
import com.lagradost.cloudstream3.utils.txt
import com.lagradost.cloudstream3.ui.subtitles.SUBTITLE_AUTO_SELECT_KEY
import com.lagradost.cloudstream3.utils.DataStoreHelper.getViewPos
// https://github.com/videolan/vlc-android/blob/3706c4be2da6800b3d26344fc04fab03ffa4b860/application/vlc-android/src/org/videolan/vlc/gui/video/VideoPlayerActivity.kt#L1898
// https://wiki.videolan.org/Android_Player_Intents/
class VlcNightlyPackage : VlcPackage() {
override val packageName = "org.videolan.vlc.debug"
override val appName = txt("VLC Nightly")
}
open class VlcPackage: OpenInAppAction(
appName = txt("VLC"),
packageName = "org.videolan.vlc",
intentClass = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
"org.videolan.vlc.gui.video.VideoPlayerActivity"
} else {
null
},
action = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
"org.videolan.vlc.player.result"
} else {
Intent.ACTION_VIEW
}
) {
// while VLC supports multi links, it has poor support, so we disable it for now
override val oneSource = true
override suspend fun putExtra(
context: Context,
intent: Intent,
video: ResultEpisode,
result: LinkLoadingResult,
index: Int?
) {
if (index != null) {
intent.setDataAndType(result.links[index].url.toUri(), "video/*")
} else {
makeTempM3U8Intent(context, intent, result)
}
val position = getViewPos(video.id)?.position ?: 0L
intent.putExtra("from_start", false)
intent.putExtra("position", position)
intent.putExtra("secure_uri", true)
intent.putExtra("title", video.name)
val subsLang = getKey(SUBTITLE_AUTO_SELECT_KEY) ?: "en"
result.subs.firstOrNull {
subsLang == it.languageCode
}?.let {
intent.putExtra("subtitles_location", it.url)
}
}
override fun onResult(activity: Activity, intent: Intent?) {
val position = intent?.getLongExtra("extra_position", -1) ?: -1
val duration = intent?.getLongExtra("extra_duration", -1) ?: -1
Log.d("VLC", "Position: $position, Duration: $duration")
updateDurationAndPosition(position, duration)
}
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/actions/temp/WebVideoCastPackage.kt
================================================
package com.lagradost.cloudstream3.actions.temp
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.core.net.toUri
import com.lagradost.cloudstream3.USER_AGENT
import com.lagradost.cloudstream3.actions.OpenInAppAction
import com.lagradost.cloudstream3.ui.result.LinkLoadingResult
import com.lagradost.cloudstream3.ui.result.ResultEpisode
import com.lagradost.cloudstream3.utils.txt
import com.lagradost.cloudstream3.utils.ExtractorLinkType
// https://www.webvideocaster.com/integrations
class WebVideoCastPackage: OpenInAppAction(
txt("Web Video Cast"),
"com.instantbits.cast.webvideo"
) {
override val oneSource = true
override val sourceTypes = setOf(
ExtractorLinkType.VIDEO,
ExtractorLinkType.DASH,
ExtractorLinkType.M3U8
)
override suspend fun putExtra(
context: Context,
intent: Intent,
video: ResultEpisode,
result: LinkLoadingResult,
index: Int?
) {
val link = result.links[index ?: 0]
intent.apply {
setDataAndType(link.url.toUri(), "video/*")
val title = video.name ?: video.headerName
putExtra("subs", result.subs.map { it.url.toUri() }.toTypedArray())
putExtra("title", title)
video.poster?.let { putExtra("poster", it) }
val headers = Bundle().apply {
if (link.referer.isNotBlank())
putString("Referer", link.referer)
putString("User-Agent", USER_AGENT)
for ((key, value) in link.headers) {
putString(key, value)
}
}
putExtra("android.media.intent.extra.HTTP_HEADERS", headers)
putExtra("secure_uri", true)
}
}
override fun onResult(activity: Activity, intent: Intent?) = Unit
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/actions/temp/fcast/FcastAction.kt
================================================
package com.lagradost.cloudstream3.actions.temp.fcast
import android.content.Context
import com.lagradost.cloudstream3.CloudStreamApp.Companion.getActivity
import com.lagradost.cloudstream3.R
import com.lagradost.cloudstream3.USER_AGENT
import com.lagradost.cloudstream3.actions.VideoClickAction
import com.lagradost.cloudstream3.ui.result.LinkLoadingResult
import com.lagradost.cloudstream3.ui.result.ResultEpisode
import com.lagradost.cloudstream3.utils.txt
import com.lagradost.cloudstream3.utils.DataStoreHelper.getViewPos
import com.lagradost.cloudstream3.utils.ExtractorLink
import com.lagradost.cloudstream3.utils.ExtractorLinkType
import com.lagradost.cloudstream3.utils.SingleSelectionHelper.showBottomDialog
class FcastAction: VideoClickAction() {
override val name = txt("Fcast to device")
override val oneSource = true
override val sourceTypes = setOf(
ExtractorLinkType.VIDEO,
ExtractorLinkType.DASH,
ExtractorLinkType.M3U8
)
override fun shouldShow(context: Context?, video: ResultEpisode?) = FcastManager.currentDevices.isNotEmpty()
override suspend fun runAction(
context: Context?,
video: ResultEpisode,
result: LinkLoadingResult,
index: Int?
) {
val link = result.links.getOrNull(index ?: 0) ?: return
val devices = FcastManager.currentDevices.toList()
uiThread {
context?.getActivity()?.showBottomDialog(
devices.map { it.name },
-1,
txt(R.string.player_settings_select_cast_device).asString(context),
false,
{}) {
val position = getViewPos(video.id)?.position
castTo(devices.getOrNull(it), link, position)
}
}
}
private fun castTo(device: PublicDeviceInfo?, link: ExtractorLink, position: Long?) {
val host = device?.host ?: return
FcastSession(host).use { session ->
session.sendMessage(
Opcode.Play,
PlayMessage(
link.type.getMimeType(),
link.url,
time = position?.let { it / 1000.0 },
headers = mapOf(
"referer" to link.referer,
"user-agent" to USER_AGENT
) + link.headers
)
)
}
}
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/actions/temp/fcast/FcastManager.kt
================================================
package com.lagradost.cloudstream3.actions.temp.fcast
import android.content.Context
import android.net.nsd.NsdManager
import android.net.nsd.NsdManager.ResolveListener
import android.net.nsd.NsdServiceInfo
import android.os.Build
import android.os.ext.SdkExtensions
import android.util.Log
import com.lagradost.cloudstream3.mvvm.safe
import com.lagradost.cloudstream3.utils.Coroutines.ioSafe
class FcastManager {
private var nsdManager: NsdManager? = null
// Used for receiver
private val registrationListenerTcp = DefaultRegistrationListener()
private fun getDeviceName(): String {
return "${Build.MANUFACTURER}-${Build.MODEL}"
}
/**
* Start the fcast service
* @param registerReceiver If true will register the app as a compatible fcast receiver for discovery in other app
*/
fun init(context: Context, registerReceiver: Boolean) = ioSafe {
nsdManager = context.getSystemService(Context.NSD_SERVICE) as NsdManager
val serviceType = "_fcast._tcp"
if (registerReceiver) {
val serviceName = "$APP_PREFIX-${getDeviceName()}"
val serviceInfo = NsdServiceInfo().apply {
this.serviceName = serviceName
this.serviceType = serviceType
this.port = TCP_PORT
}
nsdManager?.registerService(
serviceInfo,
NsdManager.PROTOCOL_DNS_SD,
registrationListenerTcp
)
}
nsdManager?.discoverServices(
serviceType,
NsdManager.PROTOCOL_DNS_SD,
DefaultDiscoveryListener()
)
}
fun stop() {
nsdManager?.unregisterService(registrationListenerTcp)
}
inner class DefaultDiscoveryListener : NsdManager.DiscoveryListener {
val tag = "DiscoveryListener"
override fun onStartDiscoveryFailed(serviceType: String?, errorCode: Int) {
Log.d(tag, "Discovery failed: $serviceType, error code: $errorCode")
}
override fun onStopDiscoveryFailed(serviceType: String?, errorCode: Int) {
Log.d(tag, "Stop discovery failed: $serviceType, error code: $errorCode")
}
override fun onDiscoveryStarted(serviceType: String?) {
Log.d(tag, "Discovery started: $serviceType")
}
override fun onDiscoveryStopped(serviceType: String?) {
Log.d(tag, "Discovery stopped: $serviceType")
}
override fun onServiceFound(serviceInfo: NsdServiceInfo?) {
// Safe here as, java.lang.NoClassDefFoundError: Failed resolution of: Landroid/net/nsd/NsdManager$ServiceInfoCallback
safe {
if (serviceInfo == null) return@safe
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && SdkExtensions.getExtensionVersion(
Build.VERSION_CODES.TIRAMISU
) >= 7
) {
nsdManager?.registerServiceInfoCallback(
serviceInfo,
Runnable::run,
object : NsdManager.ServiceInfoCallback {
override fun onServiceInfoCallbackRegistrationFailed(errorCode: Int) {
Log.e(tag, "Service registration failed: $errorCode")
}
override fun onServiceUpdated(serviceInfo: NsdServiceInfo) {
Log.d(
tag,
"Service updated: ${serviceInfo.serviceName}," +
"Net: ${serviceInfo.hostAddresses.firstOrNull()?.hostAddress}"
)
synchronized(_currentDevices) {
_currentDevices.removeIf { it.rawName == serviceInfo.serviceName }
_currentDevices.add(PublicDeviceInfo(serviceInfo))
}
}
override fun onServiceLost() {
Log.d(tag, "Service lost: ${serviceInfo.serviceName},")
synchronized(_currentDevices) {
_currentDevices.removeIf { it.rawName == serviceInfo.serviceName }
}
}
override fun onServiceInfoCallbackUnregistered() {}
})
} else {
@Suppress("DEPRECATION")
nsdManager?.resolveService(serviceInfo, object : ResolveListener {
override fun onResolveFailed(
serviceInfo: NsdServiceInfo?,
errorCode: Int
) {
}
override fun onServiceResolved(serviceInfo: NsdServiceInfo?) {
if (serviceInfo == null) return
synchronized(_currentDevices) {
_currentDevices.add(PublicDeviceInfo(serviceInfo))
}
Log.d(
tag,
"Service found: ${serviceInfo.serviceName}, Net: ${serviceInfo.host.hostAddress}"
)
}
})
}
}
}
override fun onServiceLost(serviceInfo: NsdServiceInfo?) {
if (serviceInfo == null) return
// May remove duplicates, but net and port is null here, preventing device specific identification
synchronized(_currentDevices) {
_currentDevices.removeAll {
it.rawName == serviceInfo.serviceName
}
}
Log.d(tag, "Service lost: ${serviceInfo.serviceName}")
}
}
companion object {
const val APP_PREFIX = "CloudStream"
private val _currentDevices: MutableList = mutableListOf()
val currentDevices: List = _currentDevices
class DefaultRegistrationListener : NsdManager.RegistrationListener {
val tag = "DiscoveryService"
override fun onServiceRegistered(serviceInfo: NsdServiceInfo) {
Log.d(tag, "Service registered: ${serviceInfo.serviceName}")
}
override fun onRegistrationFailed(serviceInfo: NsdServiceInfo, errorCode: Int) {
Log.e(tag, "Service registration failed: errorCode=$errorCode")
}
override fun onServiceUnregistered(serviceInfo: NsdServiceInfo) {
Log.d(tag, "Service unregistered: ${serviceInfo.serviceName}")
}
override fun onUnregistrationFailed(serviceInfo: NsdServiceInfo, errorCode: Int) {
Log.e(tag, "Service unregistration failed: errorCode=$errorCode")
}
}
const val TCP_PORT = 46899
}
}
class PublicDeviceInfo(serviceInfo: NsdServiceInfo) {
val rawName: String = serviceInfo.serviceName
val host: String? = if (
Build.VERSION.SDK_INT >= Build.VERSION_CODES.R &&
SdkExtensions.getExtensionVersion(
Build.VERSION_CODES.TIRAMISU
) >= 7
) {
serviceInfo.hostAddresses.firstOrNull()?.hostAddress
} else {
@Suppress("DEPRECATION")
serviceInfo.host.hostAddress
}
val name = rawName.replace("-", " ") + host?.let { " $it" }
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/actions/temp/fcast/FcastSession.kt
================================================
package com.lagradost.cloudstream3.actions.temp.fcast
import android.util.Log
import androidx.annotation.WorkerThread
import com.lagradost.cloudstream3.utils.AppUtils.toJson
import com.lagradost.cloudstream3.utils.Coroutines.ioSafe
import com.lagradost.safefile.closeQuietly
import java.io.DataOutputStream
import java.net.Socket
import kotlin.jvm.Throws
class FcastSession(private val hostAddress: String): AutoCloseable {
val tag = "FcastSession"
private var socket: Socket? = null
@Throws
@WorkerThread
fun open(): Socket {
val socket = Socket(hostAddress, FcastManager.TCP_PORT)
this.socket = socket
return socket
}
override fun close() {
socket?.closeQuietly()
socket = null
}
@Throws
private fun acquireSocket(): Socket {
return socket ?: open()
}
fun ping() {
sendMessage(Opcode.Ping, null)
}
fun sendMessage(opcode: Opcode, message: T) {
ioSafe {
val socket = acquireSocket()
val outputStream = DataOutputStream(socket.getOutputStream())
val json = message?.toJson()
val content = json?.toByteArray() ?: ByteArray(0)
// Little endian starting from 1
// https://gitlab.com/futo-org/fcast/-/wikis/Protocol-version-1
val size = content.size + 1
val sizeArray = ByteArray(4) { num ->
(size shr 8 * num and 0xff).toByte()
}
Log.d(tag, "Sending message with size: $size, opcode: $opcode")
outputStream.write(sizeArray)
outputStream.write(ByteArray(1) { opcode.value })
outputStream.write(content)
}
}
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/actions/temp/fcast/Packets.kt
================================================
package com.lagradost.cloudstream3.actions.temp.fcast
// See https://gitlab.com/futo-org/fcast/-/wikis/Protocol-version-1
enum class Opcode(val value: Byte) {
None(0),
Play(1),
Pause(2),
Resume(3),
Stop(4),
Seek(5),
PlaybackUpdate(6),
VolumeUpdate(7),
SetVolume(8),
PlaybackError(9),
SetSpeed(10),
Version(11),
Ping(12),
Pong(13);
}
data class PlayMessage(
val container: String,
val url: String? = null,
val content: String? = null,
val time: Double? = null,
val speed: Double? = null,
val headers: Map? = null
)
data class SeekMessage(
val time: Double
)
data class PlaybackUpdateMessage(
val generationTime: Long,
val time: Double,
val duration: Double,
val state: Int,
val speed: Double
)
data class VolumeUpdateMessage(
val generationTime: Long,
val volume: Double
)
data class PlaybackErrorMessage(
val message: String
)
data class SetSpeedMessage(
val speed: Double
)
data class SetVolumeMessage(
val volume: Double
)
data class VersionMessage(
val version: Long
)
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/mvvm/Lifecycle.kt
================================================
package com.lagradost.cloudstream3.mvvm
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
/** NOTE: Only one observer at a time per value */
fun LifecycleOwner.observe(liveData: LiveData, action: (t: T) -> Unit) {
liveData.removeObservers(this)
liveData.observe(this) { it?.let { t -> action(t) } }
}
/** NOTE: Only one observer at a time per value */
fun LifecycleOwner.observeNullable(liveData: LiveData, action: (t: T) -> Unit) {
liveData.removeObservers(this)
liveData.observe(this) { action(it) }
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/network/CloudflareKiller.kt
================================================
package com.lagradost.cloudstream3.network
import android.util.Log
import android.webkit.CookieManager
import androidx.annotation.AnyThread
import com.lagradost.cloudstream3.app
import com.lagradost.cloudstream3.mvvm.debugWarning
import com.lagradost.cloudstream3.mvvm.safe
import com.lagradost.nicehttp.Requests.Companion.await
import com.lagradost.nicehttp.cookies
import kotlinx.coroutines.runBlocking
import okhttp3.Headers
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import java.net.URI
@AnyThread
class CloudflareKiller : Interceptor {
companion object {
const val TAG = "CloudflareKiller"
private val ERROR_CODES = listOf(403, 503)
private val CLOUDFLARE_SERVERS = listOf("cloudflare-nginx", "cloudflare")
fun parseCookieMap(cookie: String): Map {
return cookie.split(";").associate {
val split = it.split("=")
(split.getOrNull(0)?.trim() ?: "") to (split.getOrNull(1)?.trim() ?: "")
}.filter { it.key.isNotBlank() && it.value.isNotBlank() }
}
}
init {
// Needs to clear cookies between sessions to generate new cookies.
safe {
// This can throw an exception on unsupported devices :(
CookieManager.getInstance().removeAllCookies(null)
}
}
val savedCookies: MutableMap> = mutableMapOf()
/**
* Gets the headers with cookies, webview user agent included!
* */
fun getCookieHeaders(url: String): Headers {
val userAgentHeaders = WebViewResolver.webViewUserAgent?.let {
mapOf("user-agent" to it)
} ?: emptyMap()
return getHeaders(userAgentHeaders, savedCookies[URI(url).host] ?: emptyMap())
}
override fun intercept(chain: Interceptor.Chain): Response = runBlocking {
val request = chain.request()
when (val cookies = savedCookies[request.url.host]) {
null -> {
val response = chain.proceed(request)
if(!(response.header("Server") in CLOUDFLARE_SERVERS && response.code in ERROR_CODES)) {
return@runBlocking response
} else {
response.close()
bypassCloudflare(request)?.let {
Log.d(TAG, "Succeeded bypassing cloudflare: ${request.url}")
return@runBlocking it
}
}
}
else -> {
return@runBlocking proceed(request, cookies)
}
}
debugWarning({ true }) { "Failed cloudflare at: ${request.url}" }
return@runBlocking chain.proceed(request)
}
private fun getWebViewCookie(url: String): String? {
return safe {
CookieManager.getInstance()?.getCookie(url)
}
}
/**
* Returns true if the cf cookies were successfully fetched from the CookieManager
* Also saves the cookies.
* */
private fun trySolveWithSavedCookies(request: Request): Boolean {
// Not sure if this takes expiration into account
return getWebViewCookie(request.url.toString())?.let { cookie ->
cookie.contains("cf_clearance").also { solved ->
if (solved) savedCookies[request.url.host] = parseCookieMap(cookie)
}
} ?: false
}
private suspend fun proceed(request: Request, cookies: Map): Response {
val userAgentMap = WebViewResolver.getWebViewUserAgent()?.let {
mapOf("user-agent" to it)
} ?: emptyMap()
val headers =
getHeaders(request.headers.toMap() + userAgentMap, cookies + request.cookies)
return app.baseClient.newCall(
request.newBuilder()
.headers(headers)
.build()
).await()
}
private suspend fun bypassCloudflare(request: Request): Response? {
val url = request.url.toString()
// If no cookies then try to get them
// Remove this if statement if cookies expire
if (!trySolveWithSavedCookies(request)) {
Log.d(TAG, "Loading webview to solve cloudflare for ${request.url}")
WebViewResolver(
// Never exit based on url
Regex(".^"),
// Cloudflare needs default user agent
userAgent = null,
// Cannot use okhttp (i think intercepting cookies fails which causes the issues)
useOkhttp = false,
// Match every url for the requestCallBack
additionalUrls = listOf(Regex("."))
).resolveUsingWebView(
url
) {
trySolveWithSavedCookies(request)
}
}
val cookies = savedCookies[request.url.host] ?: return null
return proceed(request, cookies)
}
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/network/DdosGuardKiller.kt
================================================
package com.lagradost.cloudstream3.network
import androidx.annotation.AnyThread
import com.lagradost.cloudstream3.app
import com.lagradost.nicehttp.Requests
import com.lagradost.nicehttp.cookies
import kotlinx.coroutines.runBlocking
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
/**
* @param alwaysBypass will pre-emptively fetch ddos guard cookies if true.
* If false it will only try to get cookies when a request returns 403
* */
// As seen in https://github.com/anime-dl/anime-downloader/blob/master/anime_downloader/sites/erairaws.py
@AnyThread
class DdosGuardKiller(private val alwaysBypass: Boolean) : Interceptor {
val savedCookiesMap = mutableMapOf>()
private var ddosBypassPath: String? = null
override fun intercept(chain: Interceptor.Chain): Response = runBlocking {
val request = chain.request()
if (alwaysBypass) return@runBlocking bypassDdosGuard(request)
val response = chain.proceed(request)
return@runBlocking if (response.code == 403) {
bypassDdosGuard(request)
} else response
}
private suspend fun bypassDdosGuard(request: Request): Response {
ddosBypassPath = ddosBypassPath ?: Regex("'(.*?)'").find(
app.get(
"https://check.ddos-guard.net/check.js"
).text
)?.groupValues?.get(1)
val cookies =
savedCookiesMap[request.url.host]
// If no cookies are found fetch and save em.
?: (request.url.scheme + "://" + request.url.host + (ddosBypassPath ?: "")).let {
// Somehow app.get fails
Requests().get(it).cookies.also { cookies ->
savedCookiesMap[request.url.host] = cookies
}
}
val headers = getHeaders(request.headers.toMap(), cookies + request.cookies)
return app.baseClient.newCall(
request.newBuilder()
.headers(headers)
.build()
).execute()
}
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/network/DohProviders.kt
================================================
package com.lagradost.cloudstream3.network
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.OkHttpClient
import okhttp3.dnsoverhttps.DnsOverHttps
import java.net.InetAddress
/**
* Based on https://github.com/tachiyomiorg/tachiyomi/blob/master/app/src/main/java/eu/kanade/tachiyomi/network/DohProviders.kt
*/
fun OkHttpClient.Builder.addGenericDns(url: String, ips: List) = dns(
DnsOverHttps
.Builder()
.client(build())
.url(url.toHttpUrl())
.bootstrapDnsHosts(
ips.map { InetAddress.getByName(it) }
)
.build()
)
fun OkHttpClient.Builder.addGoogleDns() = (
addGenericDns(
"https://dns.google/dns-query",
listOf(
"8.8.4.4",
"8.8.8.8"
)
))
fun OkHttpClient.Builder.addCloudFlareDns() = (
addGenericDns(
"https://cloudflare-dns.com/dns-query",
// https://www.cloudflare.com/ips/
listOf(
"1.1.1.1",
"1.0.0.1",
"2606:4700:4700::1111",
"2606:4700:4700::1001"
)
))
// Commented out as it doesn't work
//fun OkHttpClient.Builder.addOpenDns() = (
// addGenericDns(
// "https://doh.opendns.com/dns-query",
// // https://support.opendns.com/hc/en-us/articles/360038086532-Using-DNS-over-HTTPS-DoH-with-OpenDNS
// listOf(
// "208.67.222.222",
// "208.67.220.220",
// "2620:119:35::35",
// "2620:119:53::53",
// )
// ))
fun OkHttpClient.Builder.addAdGuardDns() = (
addGenericDns(
"https://dns.adguard.com/dns-query",
// https://github.com/AdguardTeam/AdGuardDNS
listOf(
// "Non-filtering"
"94.140.14.140",
"94.140.14.141",
)
))
fun OkHttpClient.Builder.addDNSWatchDns() = (
addGenericDns(
"https://resolver2.dns.watch/dns-query",
// https://dns.watch/
listOf(
"84.200.69.80",
"84.200.70.40",
)
))
fun OkHttpClient.Builder.addQuad9Dns() = (
addGenericDns(
"https://dns.quad9.net/dns-query",
// https://www.quad9.net/service/service-addresses-and-features
listOf(
"9.9.9.9",
"149.112.112.112",
)
))
fun OkHttpClient.Builder.addDnsSbDns() = (
addGenericDns(
"https://doh.dns.sb/dns-query",
//https://dns.sb/guide/
listOf(
"185.222.222.222",
"45.11.45.11",
)
))
fun OkHttpClient.Builder.addCanadianShieldDns() = (
addGenericDns(
"https://private.canadianshield.cira.ca/dns-query",
//https://www.cira.ca/en/canadian-shield/configure/summary-cira-canadian-shield-dns-resolver-addresses/
listOf(
"149.112.121.10",
"149.112.122.10",
)
))
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/network/RequestsHelper.kt
================================================
package com.lagradost.cloudstream3.network
import android.content.Context
import androidx.preference.PreferenceManager
import com.lagradost.cloudstream3.R
import com.lagradost.cloudstream3.USER_AGENT
import com.lagradost.cloudstream3.mvvm.safe
import com.lagradost.nicehttp.Requests
import com.lagradost.nicehttp.ignoreAllSSLErrors
import okhttp3.Cache
import okhttp3.Headers
import okhttp3.Headers.Companion.toHeaders
import okhttp3.OkHttpClient
import org.conscrypt.Conscrypt
import java.io.File
import java.security.Security
fun Requests.initClient(context: Context) {
this.baseClient = buildDefaultClient(context)
}
fun buildDefaultClient(context: Context): OkHttpClient {
safe { Security.insertProviderAt(Conscrypt.newProvider(), 1) }
val settingsManager = PreferenceManager.getDefaultSharedPreferences(context)
val dns = settingsManager.getInt(context.getString(R.string.dns_pref), 0)
val baseClient = OkHttpClient.Builder()
.followRedirects(true)
.followSslRedirects(true)
.ignoreAllSSLErrors()
.cache(
// Note that you need to add a ResponseInterceptor to make this 100% active.
// The server response dictates if and when stuff should be cached.
Cache(
directory = File(context.cacheDir, "http_cache"),
maxSize = 50L * 1024L * 1024L // 50 MiB
)
).apply {
when (dns) {
1 -> addGoogleDns()
2 -> addCloudFlareDns()
// 3 -> addOpenDns()
4 -> addAdGuardDns()
5 -> addDNSWatchDns()
6 -> addQuad9Dns()
7 -> addDnsSbDns()
8 -> addCanadianShieldDns()
}
}
// Needs to be build as otherwise the other builders will change this object
.build()
return baseClient
}
//val Request.cookies: Map
// get() {
// return this.headers.getCookies("Cookie")
// }
private val DEFAULT_HEADERS = mapOf("user-agent" to USER_AGENT)
/**
* Set headers > Set cookies > Default headers > Default Cookies
* TODO REMOVE AND REPLACE WITH NICEHTTP
*/
fun getHeaders(
headers: Map,
cookie: Map
): Headers {
val cookieMap =
if (cookie.isNotEmpty()) mapOf(
"Cookie" to cookie.entries.joinToString(" ") {
"${it.key}=${it.value};"
}) else mapOf()
val tempHeaders = (DEFAULT_HEADERS + headers + cookieMap)
return tempHeaders.toHeaders()
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/plugins/Plugin.kt
================================================
package com.lagradost.cloudstream3.plugins
import android.content.Context
import android.content.res.Resources
import android.util.Log
import com.lagradost.cloudstream3.actions.VideoClickAction
import com.lagradost.cloudstream3.actions.VideoClickActionHolder
import kotlin.Throws
abstract class Plugin : BasePlugin() {
/**
* Called when your Plugin is loaded
* @param context Context
*/
@Throws(Throwable::class)
open fun load(context: Context) {
// If not overridden by an extension then try the cross-platform load()
load()
}
/**
* Used to register VideoClickAction instances
* @param element VideoClickAction you want to register
*/
fun registerVideoClickAction(element: VideoClickAction) {
Log.i(PLUGIN_TAG, "Adding ${element.name} VideoClickAction")
element.sourcePlugin = this.filename
synchronized(VideoClickActionHolder.allVideoClickActions) {
VideoClickActionHolder.allVideoClickActions.add(element)
}
}
/**
* This will contain your resources if you specified requiresResources in gradle
*/
var resources: Resources? = null
/**
* This will add a button in the settings allowing you to add custom settings
*/
var openSettings: ((context: Context) -> Unit)? = null
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/plugins/PluginManager.kt
================================================
package com.lagradost.cloudstream3.plugins
import android.Manifest
import android.app.Activity
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.content.pm.PackageManager
import android.content.res.AssetManager
import android.content.res.Resources
import android.os.Build
import android.os.Environment
import android.util.Log
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.fragment.app.FragmentActivity
import com.fasterxml.jackson.annotation.JsonProperty
import com.lagradost.cloudstream3.APIHolder
import com.lagradost.cloudstream3.APIHolder.removePluginMapping
import com.lagradost.cloudstream3.AllLanguagesName
import com.lagradost.cloudstream3.AutoDownloadMode
import com.lagradost.cloudstream3.CloudStreamApp.Companion.getKey
import com.lagradost.cloudstream3.CloudStreamApp.Companion.removeKey
import com.lagradost.cloudstream3.CloudStreamApp.Companion.setKey
import com.lagradost.cloudstream3.CommonActivity.showToast
import com.lagradost.cloudstream3.MainAPI
import com.lagradost.cloudstream3.MainAPI.Companion.settingsForProvider
import com.lagradost.cloudstream3.MainActivity.Companion.afterPluginsLoadedEvent
import com.lagradost.cloudstream3.MainActivity.Companion.lastError
import com.lagradost.cloudstream3.PROVIDER_STATUS_DOWN
import com.lagradost.cloudstream3.PROVIDER_STATUS_OK
import com.lagradost.cloudstream3.R
import com.lagradost.cloudstream3.TvType
import com.lagradost.cloudstream3.actions.VideoClickAction
import com.lagradost.cloudstream3.actions.VideoClickActionHolder
import com.lagradost.cloudstream3.amap
import com.lagradost.cloudstream3.mvvm.debugPrint
import com.lagradost.cloudstream3.mvvm.logError
import com.lagradost.cloudstream3.mvvm.safe
import com.lagradost.cloudstream3.plugins.RepositoryManager.ONLINE_PLUGINS_FOLDER
import com.lagradost.cloudstream3.plugins.RepositoryManager.PREBUILT_REPOSITORIES
import com.lagradost.cloudstream3.plugins.RepositoryManager.downloadPluginToFile
import com.lagradost.cloudstream3.plugins.RepositoryManager.getRepoPlugins
import com.lagradost.cloudstream3.ui.settings.extensions.REPOSITORIES_KEY
import com.lagradost.cloudstream3.ui.settings.extensions.RepositoryData
import com.lagradost.cloudstream3.utils.AppContextUtils.getApiProviderLangSettings
import com.lagradost.cloudstream3.utils.AppUtils.parseJson
import com.lagradost.cloudstream3.utils.Coroutines.main
import com.lagradost.cloudstream3.utils.ExtractorApi
import com.lagradost.cloudstream3.utils.UIHelper.colorFromAttribute
import com.lagradost.cloudstream3.utils.UiText
import com.lagradost.cloudstream3.utils.downloader.DownloadFileManagement.sanitizeFilename
import com.lagradost.cloudstream3.utils.extractorApis
import com.lagradost.cloudstream3.utils.txt
import dalvik.system.PathClassLoader
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import java.io.File
import java.io.InputStreamReader
// Different keys for local and not since local can be removed at any time without app knowing, hence the local are getting rebuilt on every app start
const val PLUGINS_KEY = "PLUGINS_KEY"
const val PLUGINS_KEY_LOCAL = "PLUGINS_KEY_LOCAL"
const val EXTENSIONS_CHANNEL_ID = "cloudstream3.extensions"
const val EXTENSIONS_CHANNEL_NAME = "Extensions"
const val EXTENSIONS_CHANNEL_DESCRIPT = "Extension notification channel"
// Data class for internal storage
data class PluginData(
@JsonProperty("internalName") val internalName: String,
@JsonProperty("url") val url: String?,
@JsonProperty("isOnline") val isOnline: Boolean,
@JsonProperty("filePath") val filePath: String,
@JsonProperty("version") val version: Int,
) {
fun toSitePlugin(): SitePlugin {
return SitePlugin(
this.filePath,
PROVIDER_STATUS_OK,
maxOf(1, version),
1,
internalName,
internalName,
emptyList(),
File(this.filePath).name,
null,
null,
null,
null,
File(this.filePath).length()
)
}
}
// This is used as a placeholder / not set version
const val PLUGIN_VERSION_NOT_SET = Int.MIN_VALUE
// This always updates
const val PLUGIN_VERSION_ALWAYS_UPDATE = -1
object PluginManager {
// Prevent multiple writes at once
val lock = Mutex()
const val TAG = "PluginManager"
private var hasCreatedNotChanel = false
/**
* Store data about the plugin for fetching later
* */
private suspend fun setPluginData(data: PluginData) {
lock.withLock {
if (data.isOnline) {
val plugins = getPluginsOnline()
val newPlugins = plugins.filter { it.filePath != data.filePath } + data
setKey(PLUGINS_KEY, newPlugins)
} else {
val plugins = getPluginsLocal()
setKey(PLUGINS_KEY_LOCAL, plugins.filter { it.filePath != data.filePath } + data)
}
}
}
private suspend fun deletePluginData(data: PluginData?) {
if (data == null) return
lock.withLock {
if (data.isOnline) {
val plugins = getPluginsOnline().filter { it.url != data.url }
setKey(PLUGINS_KEY, plugins)
} else {
val plugins = getPluginsLocal().filter { it.filePath != data.filePath }
setKey(PLUGINS_KEY_LOCAL, plugins)
}
}
}
suspend fun deleteRepositoryData(repositoryPath: String) {
lock.withLock {
val plugins = getPluginsOnline().filter {
!it.filePath.contains(repositoryPath)
}
val file = File(repositoryPath)
safe {
if (file.exists()) file.deleteRecursively()
}
setKey(PLUGINS_KEY, plugins)
}
}
/**
* Deletes all generated oat files which will force Android to recompile the dex extensions.
* This might fix unrecoverable SIGSEGV exceptions when old oat files are loaded in a new app update.
*/
fun deleteAllOatFiles(context: Context) {
File("${context.filesDir}/${ONLINE_PLUGINS_FOLDER}").listFiles()?.forEach { repo ->
repo.listFiles { file -> file.name == "oat" && file.isDirectory }?.forEach { file ->
val success = file.deleteRecursively()
Log.i(TAG, "Deleted oat directory: ${file.absolutePath} Success=$success")
}
}
}
fun getPluginsOnline(): Array {
return getKey(PLUGINS_KEY) ?: emptyArray()
}
fun getPluginsLocal(): Array {
return getKey(PLUGINS_KEY_LOCAL) ?: emptyArray()
}
private val CLOUD_STREAM_FOLDER =
Environment.getExternalStorageDirectory().absolutePath + "/Cloudstream3/"
private val LOCAL_PLUGINS_PATH = CLOUD_STREAM_FOLDER + "plugins"
var currentlyLoading: String? = null
// Maps filepath to plugin
val plugins: MutableMap =
LinkedHashMap()
// Maps urls to plugin
val urlPlugins: MutableMap =
LinkedHashMap()
private val classLoaders: MutableMap =
HashMap()
var loadedLocalPlugins = false
private set
var loadedOnlinePlugins = false
private set
private suspend fun maybeLoadPlugin(context: Context, file: File) {
val name = file.name
if (file.extension == "zip" || file.extension == "cs3") {
loadPlugin(
context,
file,
PluginData(name, null, false, file.absolutePath, PLUGIN_VERSION_NOT_SET)
)
} else {
Log.i(TAG, "Skipping invalid plugin file: $file")
}
}
// Helper class for updateAllOnlinePluginsAndLoadThem
data class OnlinePluginData(
val savedData: PluginData,
val onlineData: Pair,
) {
val isOutdated =
onlineData.second.version > savedData.version || onlineData.second.version == PLUGIN_VERSION_ALWAYS_UPDATE
val isDisabled = onlineData.second.status == PROVIDER_STATUS_DOWN
fun validOnlineData(context: Context): Boolean {
return getPluginPath(
context,
savedData.internalName,
onlineData.first
).absolutePath == savedData.filePath
}
}
// var allCurrentOutDatedPlugins: Set = emptySet()
suspend fun loadSinglePlugin(context: Context, apiName: String): Boolean {
return (getPluginsOnline().firstOrNull {
// Most of the time the provider ends with Provider which isn't part of the api name
it.internalName.replace("provider", "", ignoreCase = true) == apiName
}
?: getPluginsLocal().firstOrNull {
it.internalName.replace("provider", "", ignoreCase = true) == apiName
})?.let { savedData ->
// OnlinePluginData(savedData, onlineData)
loadPlugin(
context,
File(savedData.filePath),
savedData
)
} ?: false
}
/**
* Needs to be run before other plugin loading because plugin loading can not be overwritten
* 1. Gets all online data about the downloaded plugins
* 2. If disabled do nothing
* 3. If outdated download and load the plugin
* 4. Else load the plugin normally
*
* DO NOT USE THIS IN A PLUGIN! It may case an infinite recursive loop lagging or crashing everyone's devices.
* If you use it from a plugin, do not expect a stable jvmName, SO DO NOT USE IT!
*/
@Suppress("FunctionName", "DEPRECATION_ERROR")
@Deprecated(
"Calling this function from a plugin will lead to crashes, use loadPlugin and unloadPlugin",
replaceWith = ReplaceWith("loadPlugin"),
level = DeprecationLevel.ERROR
)
@Throws
suspend fun ___DO_NOT_CALL_FROM_A_PLUGIN_updateAllOnlinePluginsAndLoadThem(activity: Activity) {
assertNonRecursiveCallstack()
// Load all plugins as fast as possible!
___DO_NOT_CALL_FROM_A_PLUGIN_loadAllOnlinePlugins(activity)
afterPluginsLoadedEvent.invoke(false)
val urls = (getKey>(REPOSITORIES_KEY)
?: emptyArray()) + PREBUILT_REPOSITORIES
val onlinePlugins = urls.toList().amap {
getRepoPlugins(it.url)?.toList() ?: emptyList()
}.flatten().distinctBy { it.second.url }
// Iterates over all offline plugins, compares to remote repo and returns the plugins which are outdated
val outdatedPlugins = getPluginsOnline().map { savedData ->
onlinePlugins
.filter { onlineData -> savedData.internalName == onlineData.second.internalName }
.map { onlineData ->
OnlinePluginData(savedData, onlineData)
}.filter {
it.validOnlineData(activity)
}
}.flatten().distinctBy { it.onlineData.second.url }
debugPrint {
"Outdated plugins: ${outdatedPlugins.filter { it.isOutdated }}"
}
val updatedPlugins = mutableListOf()
outdatedPlugins.amap { pluginData ->
if (pluginData.isDisabled) {
//updatedPlugins.add(activity.getString(R.string.single_plugin_disabled, pluginData.onlineData.second.name))
unloadPlugin(pluginData.savedData.filePath)
} else if (pluginData.isOutdated) {
downloadPlugin(
activity,
pluginData.onlineData.second.url,
pluginData.savedData.internalName,
File(pluginData.savedData.filePath),
true
).let { success ->
if (success)
updatedPlugins.add(pluginData.onlineData.second.name)
}
}
}
main {
val uitext = txt(R.string.plugins_updated, updatedPlugins.size)
createNotification(activity, uitext, updatedPlugins)
/*val navBadge = (activity as MainActivity).binding?.navRailView?.getOrCreateBadge(R.id.navigation_settings)
navBadge?.isVisible = true
navBadge?.number = 5*/
}
// ioSafe {
loadedOnlinePlugins = true
afterPluginsLoadedEvent.invoke(false)
// }
Log.i(TAG, "Plugin update done!")
}
/**
* Automatically download plugins not yet existing on local
* 1. Gets all online data from online plugins repo
* 2. Fetch all not downloaded plugins
* 3. Download them and reload plugins
*
* DO NOT USE THIS IN A PLUGIN! It may case an infinite recursive loop lagging or crashing everyone's devices.
* If you use it from a plugin, do not expect a stable jvmName, SO DO NOT USE IT!
*/
@Suppress("FunctionName", "DEPRECATION_ERROR")
@Deprecated(
"Calling this function from a plugin will lead to crashes, use loadPlugin and unloadPlugin",
replaceWith = ReplaceWith("loadPlugin"),
level = DeprecationLevel.ERROR
)
@Throws
suspend fun ___DO_NOT_CALL_FROM_A_PLUGIN_downloadNotExistingPluginsAndLoad(
activity: Activity,
mode: AutoDownloadMode
) {
assertNonRecursiveCallstack()
val newDownloadPlugins = mutableListOf()
val urls = (getKey>(REPOSITORIES_KEY)
?: emptyArray()) + PREBUILT_REPOSITORIES
val onlinePlugins = urls.toList().amap {
getRepoPlugins(it.url)?.toList() ?: emptyList()
}.flatten().distinctBy { it.second.url }
val providerLang = activity.getApiProviderLangSettings()
//Log.i(TAG, "providerLang => ${providerLang.toJson()}")
// Iterate online repos and returns not downloaded plugins
val notDownloadedPlugins = onlinePlugins.mapNotNull { onlineData ->
val sitePlugin = onlineData.second
val tvtypes = sitePlugin.tvTypes ?: listOf()
//Don't include empty urls
if (sitePlugin.url.isBlank()) {
return@mapNotNull null
}
if (sitePlugin.repositoryUrl.isNullOrBlank()) {
return@mapNotNull null
}
//Omit already existing plugins
if (getPluginPath(activity, sitePlugin.internalName, onlineData.first).exists()) {
Log.i(TAG, "Skip > ${sitePlugin.internalName}")
return@mapNotNull null
}
//Omit non-NSFW if mode is set to NSFW only
if (mode == AutoDownloadMode.NsfwOnly) {
if (!tvtypes.contains(TvType.NSFW.name)) {
return@mapNotNull null
}
}
//Omit NSFW, if disabled
if (!settingsForProvider.enableAdult) {
if (tvtypes.contains(TvType.NSFW.name)) {
return@mapNotNull null
}
}
//Omit lang not selected on language setting
if (mode == AutoDownloadMode.FilterByLang) {
val lang = sitePlugin.language ?: return@mapNotNull null
//If set to 'universal', don't skip any language
if (!providerLang.contains(AllLanguagesName) && !providerLang.contains(lang)) {
return@mapNotNull null
}
//Log.i(TAG, "sitePlugin lang => $lang")
}
val savedData = PluginData(
url = sitePlugin.url,
internalName = sitePlugin.internalName,
isOnline = true,
filePath = "",
version = sitePlugin.version
)
OnlinePluginData(savedData, onlineData)
}
//Log.i(TAG, "notDownloadedPlugins => ${notDownloadedPlugins.toJson()}")
notDownloadedPlugins.amap { pluginData ->
downloadPlugin(
activity,
pluginData.onlineData.second.url,
pluginData.savedData.internalName,
pluginData.onlineData.first,
!pluginData.isDisabled
).let { success ->
if (success)
newDownloadPlugins.add(pluginData.onlineData.second.name)
}
}
main {
val uitext = txt(R.string.plugins_downloaded, newDownloadPlugins.size)
createNotification(activity, uitext, newDownloadPlugins)
}
// ioSafe {
afterPluginsLoadedEvent.invoke(false)
// }
Log.i(TAG, "Plugin download done!")
}
@Throws
private fun assertNonRecursiveCallstack() {
if (Thread.currentThread().stackTrace.any { it.methodName == "loadPlugin" }) {
throw Error("You tried to call a function that will recursively call loadPlugin, this will cause crashes or memory leaks. Do not do this, there is better ways to implement the feature than reloading plugins. Are you sure you read the compile error or docs?")
}
}
/**
* Use updateAllOnlinePluginsAndLoadThem
*
* DO NOT USE THIS IN A PLUGIN! It may case an infinite recursive loop lagging or crashing everyone's devices.
* If you use it from a plugin, do not expect a stable jvmName, SO DO NOT USE IT!
*/
@Suppress("FunctionName", "DEPRECATION_ERROR")
@Deprecated(
"Calling this function from a plugin will lead to crashes, use loadPlugin and unloadPlugin",
replaceWith = ReplaceWith("loadPlugin"),
level = DeprecationLevel.ERROR
)
@Throws
suspend fun ___DO_NOT_CALL_FROM_A_PLUGIN_loadAllOnlinePlugins(context: Context) {
assertNonRecursiveCallstack()
// Load all plugins as fast as possible!
(getPluginsOnline()).toList().amap { pluginData ->
loadPlugin(
context,
File(pluginData.filePath),
pluginData
)
}
}
/**
* Reloads all local plugins and forces a page update, used for hot reloading with deployWithAdb
*
* DO NOT USE THIS IN A PLUGIN! It may case an infinite recursive loop lagging or crashing everyone's devices.
* If you use it from a plugin, do not expect a stable jvmName, SO DO NOT USE IT!
*/
@Suppress("FunctionName", "DEPRECATION_ERROR")
@Throws
@Deprecated(
"Calling this function from a plugin will lead to crashes, use loadPlugin and unloadPlugin",
replaceWith = ReplaceWith("loadPlugin"),
level = DeprecationLevel.ERROR
)
suspend fun ___DO_NOT_CALL_FROM_A_PLUGIN_hotReloadAllLocalPlugins(activity: FragmentActivity?) {
assertNonRecursiveCallstack()
Log.d(TAG, "Reloading all local plugins!")
if (activity == null) return
getPluginsLocal().forEach {
unloadPlugin(it.filePath)
}
___DO_NOT_CALL_FROM_A_PLUGIN_loadAllLocalPlugins(activity, true)
}
/**
* @param forceReload see afterPluginsLoadedEvent, basically a way to load all local plugins
* and reload all pages even if they are previously valid
*
* DO NOT USE THIS IN A PLUGIN! It may case an infinite recursive loop lagging or crashing everyone's devices.
* If you use it from a plugin, do not expect a stable jvmName, SO DO NOT USE IT!
*/
@Suppress("FunctionName", "DEPRECATION_ERROR")
@Deprecated(
"Calling this function from a plugin will lead to crashes, use loadPlugin and unloadPlugin",
replaceWith = ReplaceWith("loadPlugin"),
level = DeprecationLevel.ERROR
)
@Throws
suspend fun ___DO_NOT_CALL_FROM_A_PLUGIN_loadAllLocalPlugins(context: Context, forceReload: Boolean) {
assertNonRecursiveCallstack()
val dir = File(LOCAL_PLUGINS_PATH)
if (!dir.exists()) {
val res = dir.mkdirs()
if (!res) {
Log.w(TAG, "Failed to create local directories")
return
}
}
val sortedPlugins = dir.listFiles()
// Always sort plugins alphabetically for reproducible results
Log.d(TAG, "Files in '${LOCAL_PLUGINS_PATH}' folder: ${sortedPlugins?.size}")
// Use app-specific external files directory and copy the file there.
// We have to do this because on Android 14+, it otherwise gives SecurityException
// due to dex files and setReadOnly seems to have no effect unless it it here.
val pluginDirectory = File(context.getExternalFilesDir(null), "plugins")
if (!pluginDirectory.exists()) {
pluginDirectory.mkdirs() // Ensure the plugins directory exists
}
// Make sure all local plugins are fully refreshed.
removeKey(PLUGINS_KEY_LOCAL)
sortedPlugins?.sortedBy { it.name }?.amap { file ->
try {
val destinationFile = File(pluginDirectory, file.name)
// Only copy the file if the destination file doesn't exist or if it
// has been modified (check file length and modification time).
if (!destinationFile.exists() ||
destinationFile.length() != file.length() ||
destinationFile.lastModified() != file.lastModified()
) {
// Copy the file to the app-specific plugin directory
file.copyTo(destinationFile, overwrite = true)
// After copying, set the destination file's modification time
// to match the source file. We do this for performance so that we
// can check the modification time and not make redundant writes.
destinationFile.setLastModified(file.lastModified())
}
// Load the plugin after it has been copied
maybeLoadPlugin(context, destinationFile)
} catch (t: Throwable) {
Log.e(TAG, "Failed to copy the file")
logError(t)
}
}
loadedLocalPlugins = true
afterPluginsLoadedEvent.invoke(forceReload)
}
/** @return true if safe mode is enabled in any possible way. */
fun isSafeMode(): Boolean {
return checkSafeModeFile() || lastError != null
}
/**
* This can be used to override any extension loading to fix crashes!
* @return true if safe mode file is present
**/
fun checkSafeModeFile(): Boolean {
return safe {
val folder = File(CLOUD_STREAM_FOLDER)
if (!folder.exists()) return@safe false
val files = folder.listFiles { _, name ->
name.equals("safe", ignoreCase = true)
}
files?.any()
} ?: false
}
/**
* @return True if successful, false if not
* */
private suspend fun loadPlugin(context: Context, file: File, data: PluginData): Boolean {
val fileName = file.nameWithoutExtension
val filePath = file.absolutePath
currentlyLoading = fileName
Log.i(TAG, "Loading plugin: $data")
return try {
// In case of Android 14+ then
try {
// Set the file as read-only and log if it fails
if (!file.setReadOnly()) {
Log.e(TAG, "Failed to set read-only on plugin file: ${file.name}")
}
} catch (t: Throwable) {
Log.e(TAG, "Failed to set dex as read-only")
logError(t)
}
val loader = PathClassLoader(filePath, context.classLoader)
var manifest: BasePlugin.Manifest
loader.getResourceAsStream("manifest.json").use { stream ->
if (stream == null) {
Log.e(TAG, "Failed to load plugin $fileName: No manifest found")
return false
}
InputStreamReader(stream).use { reader ->
manifest = parseJson(reader, BasePlugin.Manifest::class.java)
}
}
val name: String = manifest.name ?: "NO NAME".also {
Log.d(TAG, "No manifest name for ${data.internalName}")
}
val version: Int = manifest.version ?: PLUGIN_VERSION_NOT_SET.also {
Log.d(TAG, "No manifest version for ${data.internalName}")
}
@Suppress("UNCHECKED_CAST")
val pluginClass: Class<*> =
loader.loadClass(manifest.pluginClassName) as Class
val pluginInstance: BasePlugin =
pluginClass.getDeclaredConstructor().newInstance() as BasePlugin
// Sets with the proper version
setPluginData(data.copy(version = version))
if (plugins.containsKey(filePath)) {
Log.i(TAG, "Plugin with name $name already exists")
return true
}
pluginInstance.filename = file.absolutePath
if (manifest.requiresResources) {
Log.d(TAG, "Loading resources for ${data.internalName}")
// based on https://stackoverflow.com/questions/7483568/dynamic-resource-loading-from-other-apk
val assets = AssetManager::class.java.getDeclaredConstructor().newInstance()
val addAssetPath =
AssetManager::class.java.getMethod("addAssetPath", String::class.java)
addAssetPath.invoke(assets, file.absolutePath)
@Suppress("DEPRECATION")
(pluginInstance as? Plugin)?.resources = Resources(
assets,
context.resources.displayMetrics,
context.resources.configuration
)
}
plugins[filePath] = pluginInstance
classLoaders[loader] = pluginInstance
urlPlugins[data.url ?: filePath] = pluginInstance
if (pluginInstance is Plugin) {
pluginInstance.load(context)
} else {
pluginInstance.load()
}
Log.i(TAG, "Loaded plugin ${data.internalName} successfully")
currentlyLoading = null
true
} catch (e: Throwable) {
Log.e(TAG, "Failed to load $file: ${Log.getStackTraceString(e)}")
showToast(
// context.getActivity(), // we are not always on the main thread
context.getString(R.string.plugin_load_fail).format(fileName),
Toast.LENGTH_LONG
)
currentlyLoading = null
false
}
}
fun unloadPlugin(absolutePath: String) {
Log.i(TAG, "Unloading plugin: $absolutePath")
val plugin = plugins[absolutePath]
if (plugin == null) {
Log.w(TAG, "Couldn't find plugin $absolutePath")
return
}
try {
plugin.beforeUnload()
} catch (e: Throwable) {
Log.e(TAG, "Failed to run beforeUnload $absolutePath: ${Log.getStackTraceString(e)}")
}
// remove all registered apis
synchronized(APIHolder.apis) {
APIHolder.apis.filter { api -> api.sourcePlugin == plugin.filename }.forEach {
removePluginMapping(it)
}
}
synchronized(APIHolder.allProviders) {
APIHolder.allProviders.removeIf { provider: MainAPI -> provider.sourcePlugin == plugin.filename }
}
extractorApis.removeIf { provider: ExtractorApi -> provider.sourcePlugin == plugin.filename }
synchronized(VideoClickActionHolder.allVideoClickActions) {
VideoClickActionHolder.allVideoClickActions.removeIf { action: VideoClickAction -> action.sourcePlugin == plugin.filename }
}
classLoaders.values.removeIf { v -> v == plugin }
plugins.remove(absolutePath)
urlPlugins.values.removeIf { v -> v == plugin }
}
/**
* Spits out a unique and safe filename based on name.
* Used for repo folders (using repo url) and plugin file names (using internalName)
* */
fun getPluginSanitizedFileName(name: String): String {
return sanitizeFilename(
name,
true
) + "." + name.hashCode()
}
/**
* This should not be changed as it is used to also detect if a plugin is installed!
**/
fun getPluginPath(
context: Context,
internalName: String,
repositoryUrl: String
): File {
val folderName = getPluginSanitizedFileName(repositoryUrl) // Guaranteed unique
val fileName = getPluginSanitizedFileName(internalName)
return File("${context.filesDir}/${ONLINE_PLUGINS_FOLDER}/${folderName}/$fileName.cs3")
}
suspend fun downloadPlugin(
activity: Activity,
pluginUrl: String,
internalName: String,
repositoryUrl: String,
loadPlugin: Boolean
): Boolean {
val file = getPluginPath(activity, internalName, repositoryUrl)
return downloadPlugin(activity, pluginUrl, internalName, file, loadPlugin)
}
suspend fun downloadPlugin(
activity: Activity,
pluginUrl: String,
internalName: String,
file: File,
loadPlugin: Boolean
): Boolean {
try {
Log.d(TAG, "Downloading plugin: $pluginUrl to ${file.absolutePath}")
// The plugin file needs to be salted with the repository url hash as to allow multiple repositories with the same internal plugin names
val newFile = downloadPluginToFile(pluginUrl, file) ?: return false
val data = PluginData(
internalName,
pluginUrl,
true,
newFile.absolutePath,
PLUGIN_VERSION_NOT_SET
)
return if (loadPlugin) {
unloadPlugin(file.absolutePath)
loadPlugin(
activity,
newFile,
data
)
} else {
setPluginData(data)
true
}
} catch (e: Exception) {
logError(e)
return false
}
}
suspend fun deletePlugin(file: File): Boolean {
val list =
(getPluginsLocal() + getPluginsOnline()).filter { it.filePath == file.absolutePath }
return try {
if (File(file.absolutePath).delete()) {
unloadPlugin(file.absolutePath)
list.forEach { deletePluginData(it) }
return true
}
false
} catch (e: Exception) {
false
}
}
/**
* DO NOT USE THIS IN A PLUGIN! It may case an infinite recursive loop lagging or crashing everyone's devices.
* If you use it from a plugin, do not expect a stable jvmName, SO DO NOT USE IT!
*/
@Suppress("FunctionName", "DEPRECATION_ERROR")
@Throws
@Deprecated(
"Calling this function from a plugin will lead to crashes, use loadPlugin and unloadPlugin",
replaceWith = ReplaceWith("loadPlugin"),
level = DeprecationLevel.ERROR
)
suspend fun ___DO_NOT_CALL_FROM_A_PLUGIN_manuallyReloadAndUpdatePlugins(activity: Activity) {
assertNonRecursiveCallstack()
showToast(activity.getString(R.string.starting_plugin_update_manually), Toast.LENGTH_LONG)
___DO_NOT_CALL_FROM_A_PLUGIN_loadAllOnlinePlugins(activity)
afterPluginsLoadedEvent.invoke(false)
val urls = (getKey>(REPOSITORIES_KEY)
?: emptyArray()) + PREBUILT_REPOSITORIES
val onlinePlugins = urls.toList().amap {
getRepoPlugins(it.url)?.toList() ?: emptyList()
}.flatten().distinctBy { it.second.url }
val allPlugins = getPluginsOnline().flatMap { savedData ->
onlinePlugins
.filter { it.second.internalName == savedData.internalName }
.mapNotNull { onlineData ->
OnlinePluginData(savedData, onlineData).takeIf { it.validOnlineData(activity) }
}
}.distinctBy { it.onlineData.second.url }
val updatedPlugins = mutableListOf()
allPlugins.amap { pluginData ->
if (pluginData.isDisabled) {
Log.e(
"PluginManager",
"Unloading disabled plugin: ${pluginData.onlineData.second.name}"
)
unloadPlugin(pluginData.savedData.filePath)
} else {
val existingFile = File(pluginData.savedData.filePath)
if (existingFile.exists()) existingFile.delete()
if (downloadPlugin(
activity,
pluginData.onlineData.second.url,
pluginData.savedData.internalName,
existingFile,
true
)
) {
updatedPlugins.add(pluginData.onlineData.second.name)
}
}
}.also {
main {
val message = if (updatedPlugins.isNotEmpty()) {
activity.getString(R.string.plugins_updated_manually, updatedPlugins.size)
} else {
activity.getString(R.string.no_plugins_updated_manually)
}
showToast(message, Toast.LENGTH_LONG)
val notificationText = UiText.StringResource(
R.string.plugins_updated_manually,
listOf(updatedPlugins.size)
)
createNotification(activity, notificationText, updatedPlugins)
}
}
loadedOnlinePlugins = true
afterPluginsLoadedEvent.invoke(false)
Log.i("PluginManager", "Plugin update done!")
}
private fun Context.createNotificationChannel() {
hasCreatedNotChanel = true
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = EXTENSIONS_CHANNEL_NAME //getString(R.string.channel_name)
val descriptionText =
EXTENSIONS_CHANNEL_DESCRIPT//getString(R.string.channel_description)
val importance = NotificationManager.IMPORTANCE_LOW
val channel = NotificationChannel(EXTENSIONS_CHANNEL_ID, name, importance).apply {
description = descriptionText
}
// Register the channel with the system
val notificationManager: NotificationManager =
this.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
}
private fun createNotification(
context: Context,
uitext: UiText,
extensions: List
): Notification? {
try {
if (extensions.isEmpty()) return null
val content = extensions.joinToString(", ")
// main { // DON'T WANT TO SLOW IT DOWN
val builder = NotificationCompat.Builder(context, EXTENSIONS_CHANNEL_ID)
.setAutoCancel(false)
.setColorized(true)
.setOnlyAlertOnce(true)
.setSilent(true)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setColor(context.colorFromAttribute(R.attr.colorPrimary))
.setContentTitle(uitext.asString(context))
//.setContentTitle(context.getString(title, extensionNames.size))
.setSmallIcon(R.drawable.ic_baseline_extension_24)
.setStyle(
NotificationCompat.BigTextStyle()
.bigText(content)
)
.setContentText(content)
if (!hasCreatedNotChanel) {
context.createNotificationChannel()
}
val notification = builder.build()
// notificationId is a unique int for each notification that you must define
if (ActivityCompat.checkSelfPermission(
context,
Manifest.permission.POST_NOTIFICATIONS
) == PackageManager.PERMISSION_GRANTED
) {
NotificationManagerCompat.from(context)
.notify((System.currentTimeMillis() / 1000).toInt(), notification)
}
return notification
} catch (e: Exception) {
logError(e)
return null
}
}
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/plugins/RepositoryManager.kt
================================================
package com.lagradost.cloudstream3.plugins
import android.content.Context
import com.fasterxml.jackson.annotation.JsonProperty
import com.lagradost.cloudstream3.CloudStreamApp.Companion.context
import com.lagradost.cloudstream3.CloudStreamApp.Companion.getKey
import com.lagradost.cloudstream3.CloudStreamApp.Companion.setKey
import com.lagradost.cloudstream3.R
import com.lagradost.cloudstream3.amap
import com.lagradost.cloudstream3.app
import com.lagradost.cloudstream3.mvvm.logError
import com.lagradost.cloudstream3.mvvm.safe
import com.lagradost.cloudstream3.mvvm.safeAsync
import com.lagradost.cloudstream3.plugins.PluginManager.getPluginSanitizedFileName
import com.lagradost.cloudstream3.plugins.PluginManager.unloadPlugin
import com.lagradost.cloudstream3.ui.settings.extensions.REPOSITORIES_KEY
import com.lagradost.cloudstream3.ui.settings.extensions.RepositoryData
import com.lagradost.cloudstream3.utils.AppUtils.tryParseJson
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import java.io.BufferedInputStream
import java.io.File
import java.io.InputStream
import java.io.OutputStream
/**
* Comes with the app, always available in the app, non removable.
* */
data class Repository(
@JsonProperty("iconUrl") val iconUrl: String?,
@JsonProperty("name") val name: String,
@JsonProperty("description") val description: String?,
@JsonProperty("manifestVersion") val manifestVersion: Int,
@JsonProperty("pluginLists") val pluginLists: List
)
/**
* Status int as the following:
* 0: Down
* 1: Ok
* 2: Slow
* 3: Beta only
* */
data class SitePlugin(
// Url to the .cs3 file
@JsonProperty("url") val url: String,
// Status to remotely disable the provider
@JsonProperty("status") val status: Int,
// Integer over 0, any change of this will trigger an auto update
@JsonProperty("version") val version: Int,
// Unused currently, used to make the api backwards compatible?
// Set to 1
@JsonProperty("apiVersion") val apiVersion: Int,
// Name to be shown in app
@JsonProperty("name") val name: String,
// Name to be referenced internally. Separate to make name and url changes possible
@JsonProperty("internalName") val internalName: String,
@JsonProperty("authors") val authors: List,
@JsonProperty("description") val description: String?,
// Might be used to go directly to the plugin repo in the future
@JsonProperty("repositoryUrl") val repositoryUrl: String?,
// These types are yet to be mapped and used, ignore for now
@JsonProperty("tvTypes") val tvTypes: List?,
// Most often a language tag like "en" or "zh-TW"
@JsonProperty("language") val language: String?,
@JsonProperty("iconUrl") val iconUrl: String?,
// Automatically generated by the gradle plugin
@JsonProperty("fileSize") val fileSize: Long?,
)
object RepositoryManager {
const val ONLINE_PLUGINS_FOLDER = "Extensions"
val PREBUILT_REPOSITORIES: Array by lazy {
getKey("PREBUILT_REPOSITORIES") ?: emptyArray()
}
private val GH_REGEX = Regex("^https://raw.githubusercontent.com/([A-Za-z0-9-]+)/([A-Za-z0-9_.-]+)/(.*)$")
/* Convert raw.githubusercontent.com urls to cdn.jsdelivr.net if enabled in settings */
fun convertRawGitUrl(url: String): String {
if (getKey(context!!.getString(R.string.jsdelivr_proxy_key)) != true) return url
val match = GH_REGEX.find(url) ?: return url
val (user, repo, rest) = match.destructured
return "https://cdn.jsdelivr.net/gh/$user/$repo@$rest"
}
suspend fun parseRepoUrl(url: String): String? {
val fixedUrl = url.trim()
return if (fixedUrl.contains("^https?://".toRegex())) {
fixedUrl
} else if (fixedUrl.contains("^(cloudstreamrepo://)|(https://cs\\.repo/\\??)".toRegex())) {
fixedUrl.replace("^(cloudstreamrepo://)|(https://cs\\.repo/\\??)".toRegex(), "").let {
return@let if (!it.contains("^https?://".toRegex()))
"https://${it}"
else fixedUrl
}
} else if (fixedUrl.matches("^[a-zA-Z0-9!_-]+$".toRegex())) {
safeAsync {
app.get("https://cutt.ly/${fixedUrl}", allowRedirects = false).let { it2 ->
it2.headers["Location"]?.let { url ->
if (url.startsWith("https://cutt.ly/404")) return@safeAsync null
if (url.removeSuffix("/") == "https://cutt.ly") return@safeAsync null
return@safeAsync url
}
}
}
} else null
}
suspend fun parseRepository(url: String): Repository? {
return safeAsync {
// Take manifestVersion and such into account later
app.get(convertRawGitUrl(url)).parsedSafe()
}
}
private suspend fun parsePlugins(pluginUrls: String): List {
// Take manifestVersion and such into account later
return try {
val response = app.get(convertRawGitUrl(pluginUrls))
// Normal parsed function not working?
// return response.parsedSafe()
tryParseJson>(response.text)?.toList() ?: emptyList()
} catch (t: Throwable) {
logError(t)
emptyList()
}
}
/**
* Gets all plugins from repositories and pairs them with the repository url
* */
suspend fun getRepoPlugins(repositoryUrl: String): List>? {
val repo = parseRepository(repositoryUrl) ?: return null
return repo.pluginLists.amap { url ->
parsePlugins(url).map {
repositoryUrl to it
}
}.flatten()
}
suspend fun downloadPluginToFile(
pluginUrl: String,
file: File
): File? {
return safeAsync {
file.mkdirs()
// Overwrite if exists
if (file.exists()) {
file.delete()
}
file.createNewFile()
val body = app.get(convertRawGitUrl(pluginUrl)).okhttpResponse.body
write(body.byteStream(), file.outputStream())
file
}
}
fun getRepositories(): Array {
return getKey(REPOSITORIES_KEY) ?: emptyArray()
}
// Don't want to read before we write in another thread
private val repoLock = Mutex()
suspend fun addRepository(repository: RepositoryData) {
repoLock.withLock {
val currentRepos = getRepositories()
// No duplicates
setKey(REPOSITORIES_KEY, (currentRepos + repository).distinctBy { it.url })
}
}
/**
* Also deletes downloaded repository plugins
* */
suspend fun removeRepository(context: Context, repository: RepositoryData) {
val extensionsDir = File(context.filesDir, ONLINE_PLUGINS_FOLDER)
repoLock.withLock {
val currentRepos = getKey>(REPOSITORIES_KEY) ?: emptyArray()
// No duplicates
val newRepos = currentRepos.filter { it.url != repository.url }
setKey(REPOSITORIES_KEY, newRepos)
}
val file = File(
extensionsDir,
getPluginSanitizedFileName(repository.url)
)
// Unload all plugins, not using deletePlugin since we
// delete all data and files in deleteRepositoryData
safe {
file.listFiles { plugin: File ->
unloadPlugin(plugin.absolutePath)
false
}
}
PluginManager.deleteRepositoryData(file.absolutePath)
}
private fun write(stream: InputStream, output: OutputStream) {
val input = BufferedInputStream(stream)
val dataBuffer = ByteArray(512)
var readBytes: Int
while (input.read(dataBuffer).also { readBytes = it } != -1) {
output.write(dataBuffer, 0, readBytes)
}
}
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/plugins/VotingApi.kt
================================================
package com.lagradost.cloudstream3.plugins
import android.util.Log
import android.widget.Toast
import com.lagradost.cloudstream3.CloudStreamApp.Companion.context
import com.lagradost.cloudstream3.CloudStreamApp.Companion.getKey
import com.lagradost.cloudstream3.CloudStreamApp.Companion.setKey
import com.lagradost.cloudstream3.R
import java.security.MessageDigest
import com.lagradost.cloudstream3.app
import com.lagradost.cloudstream3.utils.Coroutines.main
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
object VotingApi {
private const val LOGKEY = "VotingApi"
private const val API_DOMAIN = "https://api.countify.xyz"
private fun transformUrl(url: String): String =
MessageDigest
.getInstance("SHA-256")
.digest("${url}#funny-salt".toByteArray())
.fold("") { str, it -> str + "%02x".format(it) }
suspend fun SitePlugin.getVotes(): Int = getVotes(url)
fun SitePlugin.hasVoted(): Boolean = hasVoted(url)
suspend fun SitePlugin.vote(): Int = vote(url)
fun SitePlugin.canVote(): Boolean = canVote(this.url)
private val votesCache = mutableMapOf()
private suspend fun readVote(pluginUrl: String): Int {
val id = transformUrl(pluginUrl)
val url = "$API_DOMAIN/get-total/$id"
Log.d(LOGKEY, "Requesting GET: $url")
return app.get(url).parsedSafe()?.count ?: 0
}
private suspend fun writeVote(pluginUrl: String): Boolean {
val id = transformUrl(pluginUrl)
val url = "$API_DOMAIN/increment/$id"
Log.d(LOGKEY, "Requesting POST: $url")
return app.post(url, emptyMap())
.parsedSafe()?.count != null
}
suspend fun getVotes(pluginUrl: String): Int =
votesCache[pluginUrl] ?: readVote(pluginUrl).also {
votesCache[pluginUrl] = it
}
fun hasVoted(pluginUrl: String) =
getKey("cs3-votes/${transformUrl(pluginUrl)}") ?: false
fun canVote(pluginUrl: String): Boolean =
PluginManager.urlPlugins.contains(pluginUrl)
private val voteLock = Mutex()
suspend fun vote(pluginUrl: String): Int {
voteLock.withLock {
if (!canVote(pluginUrl)) {
main {
Toast.makeText(
context,
R.string.extension_install_first,
Toast.LENGTH_SHORT
).show()
}
return getVotes(pluginUrl)
}
if (hasVoted(pluginUrl)) {
main {
Toast.makeText(
context,
R.string.already_voted,
Toast.LENGTH_SHORT
).show()
}
return getVotes(pluginUrl)
}
if (writeVote(pluginUrl)) {
setKey("cs3-votes/${transformUrl(pluginUrl)}", true)
votesCache[pluginUrl] = votesCache[pluginUrl]?.plus(1) ?: 1
}
return getVotes(pluginUrl)
}
}
private data class CountifyResult(
val id: String? = null,
val count: Int? = null
)
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/receivers/VideoDownloadRestartReceiver.kt
================================================
package com.lagradost.cloudstream3.receivers
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
class VideoDownloadRestartReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
Log.i("Broadcast Listened", "Service tried to stop")
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// context?.startForegroundService(Intent(context, VideoDownloadKeepAliveService::class.java).putExtra(START_VALUE_KEY, RESTART_ALL_DOWNLOADS_AND_QUEUE))
// } else {
// context?.startService(Intent(context, VideoDownloadKeepAliveService::class.java).putExtra(START_VALUE_KEY, RESTART_ALL_DOWNLOADS_AND_QUEUE))
// }
}
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/services/BackupWorkManager.kt
================================================
package com.lagradost.cloudstream3.services
import android.content.Context
import android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC
import android.os.Build.VERSION.SDK_INT
import androidx.core.app.NotificationCompat
import androidx.work.Constraints
import androidx.work.CoroutineWorker
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.ForegroundInfo
import androidx.work.PeriodicWorkRequest
import androidx.work.WorkManager
import androidx.work.WorkerParameters
import com.lagradost.cloudstream3.R
import com.lagradost.cloudstream3.utils.AppContextUtils.createNotificationChannel
import com.lagradost.cloudstream3.utils.BackupUtils
import com.lagradost.cloudstream3.utils.UIHelper.colorFromAttribute
import java.util.concurrent.TimeUnit
const val BACKUP_CHANNEL_ID = "cloudstream3.backups"
const val BACKUP_WORK_NAME = "work_backup"
const val BACKUP_CHANNEL_NAME = "Backups"
const val BACKUP_CHANNEL_DESCRIPTION = "Notifications for background backups"
const val BACKUP_NOTIFICATION_ID = 938712898 // Random unique
class BackupWorkManager(val context: Context, workerParams: WorkerParameters) :
CoroutineWorker(context, workerParams) {
companion object {
fun enqueuePeriodicWork(context: Context?, intervalHours: Long) {
if (context == null) return
if (intervalHours == 0L) {
WorkManager.getInstance(context).cancelUniqueWork(BACKUP_WORK_NAME)
return
}
val constraints = Constraints.Builder()
.setRequiresStorageNotLow(true)
.build()
val periodicSyncDataWork =
PeriodicWorkRequest.Builder(
BackupWorkManager::class.java,
intervalHours,
TimeUnit.HOURS
)
.addTag(BACKUP_WORK_NAME)
.setConstraints(constraints)
.build()
WorkManager.getInstance(context).enqueueUniquePeriodicWork(
BACKUP_WORK_NAME,
ExistingPeriodicWorkPolicy.UPDATE,
periodicSyncDataWork
)
// Uncomment below for testing
// val oneTimeBackupWork =
// OneTimeWorkRequest.Builder(BackupWorkManager::class.java)
// .addTag(BACKUP_WORK_NAME)
// .setConstraints(constraints)
// .build()
//
// WorkManager.getInstance(context).enqueue(oneTimeBackupWork)
}
}
private val backupNotificationBuilder =
NotificationCompat.Builder(context, BACKUP_CHANNEL_ID)
.setColorized(true)
.setOnlyAlertOnce(true)
.setSilent(true)
.setAutoCancel(true)
.setContentTitle(context.getString(R.string.pref_category_backup))
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setColor(context.colorFromAttribute(R.attr.colorPrimary))
.setSmallIcon(R.drawable.ic_cloudstream_monochrome_big)
override suspend fun doWork(): Result {
context.createNotificationChannel(
BACKUP_CHANNEL_ID,
BACKUP_CHANNEL_NAME,
BACKUP_CHANNEL_DESCRIPTION
)
val foregroundInfo = if (SDK_INT >= 29)
ForegroundInfo(
BACKUP_NOTIFICATION_ID, backupNotificationBuilder.build(), FOREGROUND_SERVICE_TYPE_DATA_SYNC
) else ForegroundInfo(BACKUP_NOTIFICATION_ID, backupNotificationBuilder.build())
setForeground(foregroundInfo)
BackupUtils.backup(context)
return Result.success()
}
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/services/DownloadQueueService.kt
================================================
package com.lagradost.cloudstream3.services
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC
import android.os.Build.VERSION.SDK_INT
import android.os.IBinder
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.app.PendingIntentCompat
import com.lagradost.cloudstream3.CloudStreamApp.Companion.removeKey
import com.lagradost.cloudstream3.MainActivity
import com.lagradost.cloudstream3.MainActivity.Companion.lastError
import com.lagradost.cloudstream3.MainActivity.Companion.setLastError
import com.lagradost.cloudstream3.R
import com.lagradost.cloudstream3.mvvm.debugAssert
import com.lagradost.cloudstream3.mvvm.debugWarning
import com.lagradost.cloudstream3.mvvm.logError
import com.lagradost.cloudstream3.mvvm.safe
import com.lagradost.cloudstream3.plugins.PluginManager
import com.lagradost.cloudstream3.utils.AppContextUtils.createNotificationChannel
import com.lagradost.cloudstream3.utils.Coroutines.ioSafe
import com.lagradost.cloudstream3.utils.UIHelper.colorFromAttribute
import com.lagradost.cloudstream3.utils.downloader.DownloadQueueManager
import com.lagradost.cloudstream3.utils.downloader.VideoDownloadManager
import com.lagradost.cloudstream3.utils.downloader.VideoDownloadManager.KEY_RESUME_IN_QUEUE
import com.lagradost.cloudstream3.utils.downloader.VideoDownloadManager.KEY_RESUME_PACKAGES
import com.lagradost.cloudstream3.utils.downloader.VideoDownloadManager.downloadEvent
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.takeWhile
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.flow.updateAndGet
import kotlinx.coroutines.withTimeoutOrNull
import kotlin.system.measureTimeMillis
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.seconds
class DownloadQueueService : Service() {
companion object {
const val TAG = "DownloadQueueService"
const val DOWNLOAD_QUEUE_CHANNEL_ID = "cloudstream3.download.queue"
const val DOWNLOAD_QUEUE_CHANNEL_NAME = "Download queue service"
const val DOWNLOAD_QUEUE_CHANNEL_DESCRIPTION = "App download queue notification."
const val DOWNLOAD_QUEUE_NOTIFICATION_ID = 917194232 // Random unique
@Volatile
var isRunning = false
fun getIntent(
context: Context,
): Intent {
return Intent(context, DownloadQueueService::class.java)
}
private val _downloadInstances: MutableStateFlow> =
MutableStateFlow(emptyList())
/** Flow of all active downloads, not queued. May temporarily contain completed or failed EpisodeDownloadInstances.
* Completed or failed instances are automatically removed by the download queue service.
*
*/
val downloadInstances: StateFlow> =
_downloadInstances
private val totalDownloadFlow =
downloadInstances.combine(DownloadQueueManager.queue) { instances, queue ->
instances to queue
}
.combine(VideoDownloadManager.currentDownloads) { (instances, queue), currentDownloads ->
Triple(instances, queue, currentDownloads)
}
}
private val baseNotification by lazy {
val intent = Intent(this, MainActivity::class.java)
val pendingIntent =
PendingIntentCompat.getActivity(this, 0, intent, 0, false)
val activeDownloads = resources.getQuantityString(R.plurals.downloads_active, 0).format(0)
val activeQueue = resources.getQuantityString(R.plurals.downloads_queued, 0).format(0)
NotificationCompat.Builder(this, DOWNLOAD_QUEUE_CHANNEL_ID)
.setOngoing(true) // Make it persistent
.setAutoCancel(false)
.setColorized(false)
.setOnlyAlertOnce(true)
.setSilent(true)
.setShowWhen(false)
// If low priority then the notification might not show :(
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setColor(this.colorFromAttribute(R.attr.colorPrimary))
.setContentText(activeDownloads)
.setSubText(activeQueue)
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.download_icon_load)
}
private fun updateNotification(context: Context, downloads: Int, queued: Int) {
val activeDownloads =
resources.getQuantityString(R.plurals.downloads_active, downloads).format(downloads)
val activeQueue =
resources.getQuantityString(R.plurals.downloads_queued, queued).format(queued)
val newNotification = baseNotification
.setContentText(activeDownloads)
.setSubText(activeQueue)
.build()
safe {
NotificationManagerCompat.from(context)
.notify(DOWNLOAD_QUEUE_NOTIFICATION_ID, newNotification)
}
}
// We always need to listen to events, even before the download is launched.
// Stopping link loading is an event which can trigger before downloading.
val downloadEventListener = { event: Pair ->
when (event.second) {
VideoDownloadManager.DownloadActionType.Stop -> {
removeKey(KEY_RESUME_PACKAGES, event.first.toString())
removeKey(KEY_RESUME_IN_QUEUE, event.first.toString())
DownloadQueueManager.cancelDownload(event.first)
}
else -> {}
}
}
@OptIn(ExperimentalCoroutinesApi::class, FlowPreview::class)
override fun onCreate() {
isRunning = true
val context: Context = this // To make code more readable
Log.d(TAG, "Download queue service started.")
this.createNotificationChannel(
DOWNLOAD_QUEUE_CHANNEL_ID,
DOWNLOAD_QUEUE_CHANNEL_NAME,
DOWNLOAD_QUEUE_CHANNEL_DESCRIPTION
)
if (SDK_INT >= 29) {
startForeground(
DOWNLOAD_QUEUE_NOTIFICATION_ID,
baseNotification.build(),
FOREGROUND_SERVICE_TYPE_DATA_SYNC
)
} else {
startForeground(DOWNLOAD_QUEUE_NOTIFICATION_ID, baseNotification.build())
}
downloadEvent += downloadEventListener
val queueJob = ioSafe {
// Ensure this is up to date to prevent race conditions with MainActivity launches
setLastError(context)
// Early return, to prevent waiting for plugins in safe mode
if (lastError != null) return@ioSafe
// Try to ensure all plugins are loaded before starting the downloader.
// To prevent infinite stalls we use a timeout of 15 seconds, it is judged as long enough
val timeout = 15.seconds
val timeTaken = withTimeoutOrNull(timeout) {
measureTimeMillis {
while (!(PluginManager.loadedOnlinePlugins && PluginManager.loadedLocalPlugins)) {
delay(100.milliseconds)
}
}
}
debugWarning({ timeTaken == null || timeTaken > 3_000 }, {
"Abnormally long downloader startup time of: ${timeTaken ?: timeout.inWholeMilliseconds}ms"
})
debugAssert({ timeTaken == null }, { "Downloader startup should not time out" })
totalDownloadFlow
.takeWhile { (instances, queue) ->
// Stop if destroyed
isRunning
// Run as long as there is a queue to process
&& (instances.isNotEmpty() || queue.isNotEmpty())
// Run as long as there are no app crashes
&& lastError == null
}
.collect { (_, queue, currentDownloads) ->
// Remove completed or failed
val newInstances = _downloadInstances.updateAndGet { currentInstances ->
currentInstances.filterNot { it.isCompleted || it.isFailed || it.isCancelled }
}
val maxDownloads = VideoDownloadManager.maxConcurrentDownloads(context)
val currentInstanceCount = newInstances.size
val newDownloads = minOf(
// Cannot exceed the max downloads
maxOf(0, maxDownloads - currentInstanceCount),
// Cannot start more downloads than the queue size
queue.size
)
// Cant start multiple downloads at once. If this is rerun it may start too many downloads.
if (newDownloads > 0) {
_downloadInstances.update { instances ->
val downloadInstance = DownloadQueueManager.popQueue(context)
if (downloadInstance != null) {
downloadInstance.startDownload()
instances + downloadInstance
} else {
instances
}
}
}
// The downloads actually displayed to the user with a notification
val currentVisualDownloads =
currentDownloads.size + newInstances.count {
currentDownloads.contains(it.downloadQueueWrapper.id)
.not()
}
// Just the queue
val currentVisualQueue = queue.size
updateNotification(context, currentVisualDownloads, currentVisualQueue)
}
}
// Stop self regardless of job outcome
queueJob.invokeOnCompletion { throwable ->
if (throwable != null) {
logError(throwable)
}
safe {
stopSelf()
}
}
}
override fun onDestroy() {
Log.d(TAG, "Download queue service stopped.")
downloadEvent -= downloadEventListener
isRunning = false
super.onDestroy()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
return START_STICKY // We want the service restarted if its killed
}
override fun onBind(intent: Intent?): IBinder? = null
override fun onTimeout(reason: Int) {
stopSelf()
Log.e(TAG, "Service stopped due to timeout: $reason")
}
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/services/PackageInstallerService.kt
================================================
package com.lagradost.cloudstream3.services
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC
import android.os.Build.VERSION.SDK_INT
import android.os.IBinder
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.app.PendingIntentCompat
import com.lagradost.cloudstream3.MainActivity
import com.lagradost.cloudstream3.MainActivity.Companion.deleteFileOnExit
import com.lagradost.cloudstream3.R
import com.lagradost.cloudstream3.app
import com.lagradost.cloudstream3.mvvm.logError
import com.lagradost.cloudstream3.utils.ApkInstaller
import com.lagradost.cloudstream3.utils.AppContextUtils.createNotificationChannel
import com.lagradost.cloudstream3.utils.Coroutines.ioSafe
import com.lagradost.cloudstream3.utils.UIHelper.colorFromAttribute
import kotlinx.coroutines.delay
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlin.math.roundToInt
class PackageInstallerService : Service() {
private var installer: ApkInstaller? = null
private val baseNotification by lazy {
val intent = Intent(this, MainActivity::class.java)
val pendingIntent =
PendingIntentCompat.getActivity(this, 0, intent, 0, false)
NotificationCompat.Builder(this, UPDATE_CHANNEL_ID)
.setAutoCancel(false)
.setColorized(true)
.setOnlyAlertOnce(true)
.setSilent(true)
// If low priority then the notification might not show :(
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setColor(this.colorFromAttribute(R.attr.colorPrimary))
.setContentTitle(getString(R.string.update_notification_downloading))
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.rdload)
}
override fun onCreate() {
this.createNotificationChannel(
UPDATE_CHANNEL_ID,
UPDATE_CHANNEL_NAME,
UPDATE_CHANNEL_DESCRIPTION
)
if (SDK_INT >= 29)
startForeground(UPDATE_NOTIFICATION_ID, baseNotification.build(), FOREGROUND_SERVICE_TYPE_DATA_SYNC)
else startForeground(UPDATE_NOTIFICATION_ID, baseNotification.build())
}
private val updateLock = Mutex()
private suspend fun downloadUpdate(url: String): Boolean {
try {
Log.d("PackageInstallerService", "Downloading update: $url")
// Delete all old updates
ioSafe {
val appUpdateName = "CloudStream"
val appUpdateSuffix = "apk"
this@PackageInstallerService.cacheDir.listFiles()?.filter {
it.name.startsWith(appUpdateName) && it.extension == appUpdateSuffix
}?.forEach {
deleteFileOnExit(it)
}
}
updateLock.withLock {
updateNotificationProgress(
0f,
ApkInstaller.InstallProgressStatus.Downloading
)
val body = app.get(url).body
val inputStream = body.byteStream()
installer = ApkInstaller(this)
val totalSize = body.contentLength()
var currentSize = 0
installer?.installApk(this, inputStream, totalSize, {
currentSize += it
// Prevent div 0
if (totalSize == 0L) return@installApk
val percentage = currentSize / totalSize.toFloat()
updateNotificationProgress(
percentage,
ApkInstaller.InstallProgressStatus.Downloading
)
}) { status ->
updateNotificationProgress(0f, status)
}
}
return true
} catch (e: Exception) {
logError(e)
updateNotificationProgress(0f, ApkInstaller.InstallProgressStatus.Failed)
return false
}
}
private fun updateNotificationProgress(
percentage: Float,
state: ApkInstaller.InstallProgressStatus
) {
// Log.d(LOG_TAG, "Downloading app update progress $percentage | $state")
val text = when (state) {
ApkInstaller.InstallProgressStatus.Installing -> R.string.update_notification_installing
ApkInstaller.InstallProgressStatus.Preparing, ApkInstaller.InstallProgressStatus.Downloading -> R.string.update_notification_downloading
ApkInstaller.InstallProgressStatus.Failed -> R.string.update_notification_failed
}
val newNotification = baseNotification
.setContentTitle(getString(text))
.apply {
if (state == ApkInstaller.InstallProgressStatus.Failed) {
setSmallIcon(R.drawable.rderror)
setAutoCancel(true)
} else {
setProgress(
10000, (10000 * percentage).roundToInt(),
state != ApkInstaller.InstallProgressStatus.Downloading
)
}
}
.build()
val notificationManager =
getSystemService(NOTIFICATION_SERVICE) as NotificationManager
// Persistent notification on failure
val id =
if (state == ApkInstaller.InstallProgressStatus.Failed) UPDATE_NOTIFICATION_ID + 1 else UPDATE_NOTIFICATION_ID
notificationManager.notify(id, newNotification)
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val url = intent?.getStringExtra(EXTRA_URL) ?: return START_NOT_STICKY
ioSafe {
downloadUpdate(url)
// Close the service after the update is done
// If no sleep then the install prompt may not appear and the notification
// will disappear instantly
delay(10_000)
this@PackageInstallerService.stopSelf()
}
return START_NOT_STICKY
}
override fun onDestroy() {
installer?.unregisterInstallActionReceiver()
installer = null
this.stopSelf()
super.onDestroy()
}
override fun onBind(i: Intent?): IBinder? = null
override fun onTimeout(reason: Int) {
stopSelf()
Log.e("PackageInstallerService", "Service stopped due to timeout: $reason")
}
companion object {
private const val EXTRA_URL = "EXTRA_URL"
const val UPDATE_CHANNEL_ID = "cloudstream3.updates"
const val UPDATE_CHANNEL_NAME = "App Updates"
const val UPDATE_CHANNEL_DESCRIPTION = "App updates notification channel"
const val UPDATE_NOTIFICATION_ID = -68454136 // Random unique
fun getIntent(
context: Context,
url: String,
): Intent {
return Intent(context, PackageInstallerService::class.java)
.putExtra(EXTRA_URL, url)
}
}
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/services/SubscriptionWorkManager.kt
================================================
package com.lagradost.cloudstream3.services
import android.app.NotificationManager
import android.content.Context
import android.content.Intent
import android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC
import android.os.Build.VERSION.SDK_INT
import androidx.core.app.NotificationCompat
import androidx.core.app.PendingIntentCompat
import androidx.core.net.toUri
import androidx.work.*
import com.lagradost.cloudstream3.*
import com.lagradost.cloudstream3.APIHolder.getApiFromNameNull
import com.lagradost.cloudstream3.R
import com.lagradost.cloudstream3.mvvm.logError
import com.lagradost.cloudstream3.plugins.PluginManager
import com.lagradost.cloudstream3.utils.txt
import com.lagradost.cloudstream3.utils.AppContextUtils.createNotificationChannel
import com.lagradost.cloudstream3.utils.AppContextUtils.getApiDubstatusSettings
import com.lagradost.cloudstream3.utils.Coroutines.ioWork
import com.lagradost.cloudstream3.utils.DataStoreHelper
import com.lagradost.cloudstream3.utils.DataStoreHelper.getAllSubscriptions
import com.lagradost.cloudstream3.utils.DataStoreHelper.getDub
import com.lagradost.cloudstream3.utils.UIHelper.colorFromAttribute
import com.lagradost.cloudstream3.utils.downloader.DownloadUtils.getImageBitmapFromUrl
import kotlinx.coroutines.withTimeoutOrNull
import java.util.concurrent.TimeUnit
const val SUBSCRIPTION_CHANNEL_ID = "cloudstream3.subscriptions"
const val SUBSCRIPTION_WORK_NAME = "work_subscription"
const val SUBSCRIPTION_CHANNEL_NAME = "Subscriptions"
const val SUBSCRIPTION_CHANNEL_DESCRIPTION = "Notifications for new episodes on subscribed shows"
const val SUBSCRIPTION_NOTIFICATION_ID = 938712897 // Random unique
class SubscriptionWorkManager(val context: Context, workerParams: WorkerParameters) :
CoroutineWorker(context, workerParams) {
companion object {
fun enqueuePeriodicWork(context: Context?) {
if (context == null) return
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val periodicSyncDataWork =
PeriodicWorkRequest.Builder(SubscriptionWorkManager::class.java, 6, TimeUnit.HOURS)
.addTag(SUBSCRIPTION_WORK_NAME)
.setConstraints(constraints)
.build()
WorkManager.getInstance(context).enqueueUniquePeriodicWork(
SUBSCRIPTION_WORK_NAME,
ExistingPeriodicWorkPolicy.KEEP,
periodicSyncDataWork
)
// Uncomment below for testing
// val oneTimeSyncDataWork =
// OneTimeWorkRequest.Builder(SubscriptionWorkManager::class.java)
// .addTag(SUBSCRIPTION_WORK_NAME)
// .setConstraints(constraints)
// .build()
//
// WorkManager.getInstance(context).enqueue(oneTimeSyncDataWork)
}
}
private val progressNotificationBuilder =
NotificationCompat.Builder(context, SUBSCRIPTION_CHANNEL_ID)
.setAutoCancel(false)
.setColorized(true)
.setOnlyAlertOnce(true)
.setSilent(true)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setColor(context.colorFromAttribute(R.attr.colorPrimary))
.setContentTitle(context.getString(R.string.subscription_in_progress_notification))
.setSmallIcon(com.google.android.gms.cast.framework.R.drawable.quantum_ic_refresh_white_24)
.setProgress(0, 0, true)
private val updateNotificationBuilder =
NotificationCompat.Builder(context, SUBSCRIPTION_CHANNEL_ID)
.setColorized(true)
.setOnlyAlertOnce(true)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setColor(context.colorFromAttribute(R.attr.colorPrimary))
.setSmallIcon(R.drawable.ic_cloudstream_monochrome_big)
private val notificationManager: NotificationManager =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
private fun updateProgress(max: Int, progress: Int, indeterminate: Boolean) {
notificationManager.notify(
SUBSCRIPTION_NOTIFICATION_ID, progressNotificationBuilder
.setProgress(max, progress, indeterminate)
.build()
)
}
@Suppress("DEPRECATION_ERROR")
override suspend fun doWork(): Result {
try {
// println("Update subscriptions!")
context.createNotificationChannel(
SUBSCRIPTION_CHANNEL_ID,
SUBSCRIPTION_CHANNEL_NAME,
SUBSCRIPTION_CHANNEL_DESCRIPTION
)
val foregroundInfo = if (SDK_INT >= 29)
ForegroundInfo(
SUBSCRIPTION_NOTIFICATION_ID,
progressNotificationBuilder.build(),
FOREGROUND_SERVICE_TYPE_DATA_SYNC
) else ForegroundInfo(SUBSCRIPTION_NOTIFICATION_ID, progressNotificationBuilder.build(),)
setForeground(foregroundInfo)
val subscriptions = getAllSubscriptions()
if (subscriptions.isEmpty()) {
WorkManager.getInstance(context).cancelWorkById(this.id)
return Result.success()
}
val max = subscriptions.size
var progress = 0
updateProgress(max, progress, true)
// We need all plugins loaded.
PluginManager.___DO_NOT_CALL_FROM_A_PLUGIN_loadAllOnlinePlugins(context)
PluginManager.___DO_NOT_CALL_FROM_A_PLUGIN_loadAllLocalPlugins(context, false)
subscriptions.amap { savedData ->
try {
val id = savedData.id ?: return@amap null
val api = getApiFromNameNull(savedData.apiName) ?: return@amap null
// Reasonable timeout to prevent having this worker run forever.
val response = withTimeoutOrNull(60_000) {
api.load(savedData.url) as? EpisodeResponse
} ?: return@amap null
val dubPreference =
getDub(id) ?: if (
context.getApiDubstatusSettings().contains(DubStatus.Dubbed)
) {
DubStatus.Dubbed
} else {
DubStatus.Subbed
}
val latestEpisodes = response.getLatestEpisodes()
val latestPreferredEpisode = latestEpisodes[dubPreference]
val (shouldUpdate, latestEpisode) = if (latestPreferredEpisode != null) {
val latestSeenEpisode =
savedData.lastSeenEpisodeCount[dubPreference] ?: Int.MIN_VALUE
val shouldUpdate = latestPreferredEpisode > latestSeenEpisode
shouldUpdate to latestPreferredEpisode
} else {
val latestEpisode = latestEpisodes[DubStatus.None] ?: Int.MIN_VALUE
val latestSeenEpisode =
savedData.lastSeenEpisodeCount[DubStatus.None] ?: Int.MIN_VALUE
val shouldUpdate = latestEpisode > latestSeenEpisode
shouldUpdate to latestEpisode
}
DataStoreHelper.updateSubscribedData(
id,
savedData,
response
)
if (shouldUpdate) {
val updateHeader = savedData.name
val updateDescription = txt(
R.string.subscription_episode_released,
latestEpisode,
savedData.name
).asString(context)
val intent = Intent(context, MainActivity::class.java).apply {
data = savedData.url.toUri()
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}.putExtra(MainActivity.API_NAME_EXTRA_KEY, api.name)
val pendingIntent =
PendingIntentCompat.getActivity(context, 0, intent, 0, false)
val poster = ioWork {
savedData.posterUrl?.let { url ->
context.getImageBitmapFromUrl(
url,
savedData.posterHeaders
)
}
}
val updateNotification =
updateNotificationBuilder.setContentTitle(updateHeader)
.setContentText(updateDescription)
.setContentIntent(pendingIntent)
.setLargeIcon(poster)
.build()
notificationManager.notify(id, updateNotification)
}
// You can probably get some issues here since this is async but it does not matter much.
updateProgress(max, ++progress, false)
} catch (t: Throwable) {
logError(t)
}
}
return Result.success()
} catch (t: Throwable) {
logError(t)
// ye, while this is not correct, but because gods know why android just crashes
// and this causes major battery usage as it retries it inf times. This is better, just
// in case android decides to be android and fuck us
return Result.success()
}
}
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/services/VideoDownloadService.kt
================================================
package com.lagradost.cloudstream3.services
import android.app.Service
import android.content.Intent
import android.os.IBinder
import com.lagradost.cloudstream3.utils.downloader.VideoDownloadManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
/** Handle notification actions such as pause/resume downloads */
class VideoDownloadService : Service() {
private val downloadScope = CoroutineScope(Dispatchers.Default)
override fun onBind(intent: Intent?): IBinder? {
return null
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent != null) {
val id = intent.getIntExtra("id", -1)
val type = intent.getStringExtra("type")
if (id != -1 && type != null) {
val state = when (type) {
"resume" -> VideoDownloadManager.DownloadActionType.Resume
"pause" -> VideoDownloadManager.DownloadActionType.Pause
"stop" -> VideoDownloadManager.DownloadActionType.Stop
else -> return START_NOT_STICKY
}
downloadScope.launch {
VideoDownloadManager.downloadEvent.invoke(Pair(id, state))
}
}
}
return START_NOT_STICKY
}
override fun onDestroy() {
downloadScope.coroutineContext.cancel()
super.onDestroy()
}
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/subtitles/AbstractSubProvider.kt
================================================
package com.lagradost.cloudstream3.subtitles
import androidx.core.net.toUri
import com.lagradost.cloudstream3.MainActivity.Companion.deleteFileOnExit
import com.lagradost.cloudstream3.app
import com.lagradost.cloudstream3.ui.player.SubtitleOrigin
import okio.BufferedSource
import okio.buffer
import okio.sink
import okio.source
import java.io.File
import java.util.zip.ZipInputStream
/**
* A builder for subtitle files.
* @see addUrl
* @see addFile
*/
class SubtitleResource {
fun downloadFile(source: BufferedSource): File {
val file = File.createTempFile("temp-subtitle", ".tmp").apply {
deleteFileOnExit(this)
}
val sink = file.sink().buffer()
sink.writeAll(source)
sink.close()
source.close()
return file
}
private fun unzip(file: File): List> {
val entries = mutableListOf>()
ZipInputStream(file.inputStream()).use { zipInputStream ->
var zipEntry = zipInputStream.nextEntry
while (zipEntry != null) {
val tempFile = File.createTempFile("unzipped-subtitle", ".tmp").apply {
deleteFileOnExit(this)
}
entries.add(zipEntry.name to tempFile)
tempFile.sink().buffer().use { buffer ->
buffer.writeAll(zipInputStream.source())
}
zipEntry = zipInputStream.nextEntry
}
}
return entries
}
data class SingleSubtitleResource(
val name: String?,
val url: String,
val origin: SubtitleOrigin
)
private var resources: MutableList = mutableListOf()
fun getSubtitles(): List {
return resources.toList()
}
fun addUrl(url: String?, name: String? = null) {
if (url == null) return
this.resources.add(
SingleSubtitleResource(name, url, SubtitleOrigin.URL)
)
}
fun addFile(file: File, name: String? = null) {
this.resources.add(
SingleSubtitleResource(name, file.toUri().toString(), SubtitleOrigin.DOWNLOADED_FILE)
)
deleteFileOnExit(file)
}
suspend fun addZipUrl(
url: String,
nameGenerator: (String, File) -> String? = { _, _ -> null }
) {
val source = app.get(url).okhttpResponse.body.source()
val zip = downloadFile(source)
val realFiles = unzip(zip)
zip.deleteRecursively()
realFiles.forEach { (name, subtitleFile) ->
addFile(subtitleFile, nameGenerator(name, subtitleFile))
}
}
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/subtitles/AbstractSubtitleEntities.kt
================================================
package com.lagradost.cloudstream3.subtitles
import com.lagradost.cloudstream3.TvType
class AbstractSubtitleEntities {
data class SubtitleEntity(
var idPrefix : String,
var name: String = "", //Title of movie/series. This is the one to be displayed when choosing.
var lang: String = "en",
var data: String = "", //Id or link, depends on provider how to process
var type: TvType = TvType.Movie, //Movie, TV series, etc..
var source: String,
var epNumber: Int? = null,
var seasonNumber: Int? = null,
var year: Int? = null,
var isHearingImpaired: Boolean = false,
var headers: Map = emptyMap()
)
data class SubtitleSearch(
var query: String = "",
var lang: String? = null,
var imdbId: String? = null,
var tmdbId: Int? = null,
var malId: Int? = null,
var aniListId: Int? = null,
var epNumber: Int? = null,
var seasonNumber: Int? = null,
var year: Int? = null
)
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/syncproviders/AccountManager.kt
================================================
package com.lagradost.cloudstream3.syncproviders
import com.lagradost.cloudstream3.CloudStreamApp.Companion.getKey
import com.lagradost.cloudstream3.CloudStreamApp.Companion.setKey
import com.lagradost.cloudstream3.LoadResponse
import com.lagradost.cloudstream3.syncproviders.providers.Addic7ed
import com.lagradost.cloudstream3.syncproviders.providers.AniListApi
import com.lagradost.cloudstream3.syncproviders.providers.KitsuApi
import com.lagradost.cloudstream3.syncproviders.providers.LocalList
import com.lagradost.cloudstream3.syncproviders.providers.MALApi
import com.lagradost.cloudstream3.syncproviders.providers.OpenSubtitlesApi
import com.lagradost.cloudstream3.syncproviders.providers.SimklApi
import com.lagradost.cloudstream3.syncproviders.providers.SubDlApi
import com.lagradost.cloudstream3.syncproviders.providers.SubSourceApi
import com.lagradost.cloudstream3.utils.DataStoreHelper
import java.util.concurrent.TimeUnit
abstract class AccountManager {
companion object {
const val NONE_ID: Int = -1
val malApi = MALApi()
val kitsuApi = KitsuApi()
val aniListApi = AniListApi()
val simklApi = SimklApi()
val localListApi = LocalList()
val openSubtitlesApi = OpenSubtitlesApi()
val addic7ed = Addic7ed()
val subDlApi = SubDlApi()
val subSourceApi = SubSourceApi()
var cachedAccounts: MutableMap>
var cachedAccountIds: MutableMap
const val ACCOUNT_TOKEN = "auth_tokens"
const val ACCOUNT_IDS = "auth_ids"
fun accounts(prefix: String): Array {
require(prefix != "NONE")
return getKey>(
ACCOUNT_TOKEN,
"${prefix}/${DataStoreHelper.currentAccount}"
) ?: arrayOf()
}
fun updateAccounts(prefix: String, array: Array) {
require(prefix != "NONE")
setKey(ACCOUNT_TOKEN, "${prefix}/${DataStoreHelper.currentAccount}", array)
synchronized(cachedAccounts) {
cachedAccounts[prefix] = array
}
}
fun updateAccountsId(prefix: String, id: Int) {
require(prefix != "NONE")
setKey(ACCOUNT_IDS, "${prefix}/${DataStoreHelper.currentAccount}", id)
synchronized(cachedAccountIds) {
cachedAccountIds[prefix] = id
}
}
val allApis = arrayOf(
SyncRepo(malApi),
SyncRepo(kitsuApi),
SyncRepo(aniListApi),
SyncRepo(simklApi),
SyncRepo(localListApi),
SubtitleRepo(openSubtitlesApi),
SubtitleRepo(addic7ed),
SubtitleRepo(subDlApi)
)
fun updateAccountIds() {
val ids = mutableMapOf()
for (api in allApis) {
ids.put(
api.idPrefix,
getKey(
ACCOUNT_IDS,
"${api.idPrefix}/${DataStoreHelper.currentAccount}",
NONE_ID
) ?: NONE_ID
)
}
synchronized(cachedAccountIds) {
cachedAccountIds = ids
}
}
init {
val data = mutableMapOf>()
val ids = mutableMapOf()
for (api in allApis) {
data.put(api.idPrefix, accounts(api.idPrefix))
ids.put(
api.idPrefix,
getKey(
ACCOUNT_IDS,
"${api.idPrefix}/${DataStoreHelper.currentAccount}",
NONE_ID
) ?: NONE_ID
)
}
cachedAccounts = data
cachedAccountIds = ids
}
// I do not want to place this in the init block as JVM initialization order is weird, and it may cause exceptions
// accessing other classes
fun initMainAPI() {
LoadResponse.malIdPrefix = malApi.idPrefix
LoadResponse.kitsuIdPrefix = kitsuApi.idPrefix
LoadResponse.aniListIdPrefix = aniListApi.idPrefix
LoadResponse.simklIdPrefix = simklApi.idPrefix
}
val subtitleProviders = arrayOf(
SubtitleRepo(openSubtitlesApi),
SubtitleRepo(addic7ed),
SubtitleRepo(subDlApi)
)
val syncApis = arrayOf(
SyncRepo(malApi),
SyncRepo(kitsuApi),
SyncRepo(aniListApi),
SyncRepo(simklApi),
SyncRepo(localListApi)
)
const val APP_STRING = "cloudstreamapp"
const val APP_STRING_REPO = "cloudstreamrepo"
const val APP_STRING_PLAYER = "cloudstreamplayer"
// Instantly start the search given a query
const val APP_STRING_SEARCH = "cloudstreamsearch"
// Instantly resume watching a show
const val APP_STRING_RESUME_WATCHING = "cloudstreamcontinuewatching"
const val APP_STRING_SHARE = "csshare"
fun secondsToReadable(seconds: Int, completedValue: String): String {
var secondsLong = seconds.toLong()
val days = TimeUnit.SECONDS
.toDays(secondsLong)
secondsLong -= TimeUnit.DAYS.toSeconds(days)
val hours = TimeUnit.SECONDS
.toHours(secondsLong)
secondsLong -= TimeUnit.HOURS.toSeconds(hours)
val minutes = TimeUnit.SECONDS
.toMinutes(secondsLong)
secondsLong -= TimeUnit.MINUTES.toSeconds(minutes)
if (minutes < 0) {
return completedValue
}
//println("$days $hours $minutes")
return "${if (days != 0L) "$days" + "d " else ""}${if (hours != 0L) "$hours" + "h " else ""}${minutes}m"
}
}
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/syncproviders/AuthAPI.kt
================================================
package com.lagradost.cloudstream3.syncproviders
import android.util.Base64
import androidx.annotation.WorkerThread
import com.fasterxml.jackson.annotation.JsonProperty
import com.lagradost.cloudstream3.APIHolder.unixTime
import com.lagradost.cloudstream3.ActorData
import com.lagradost.cloudstream3.CloudStreamApp.Companion.getKey
import com.lagradost.cloudstream3.CloudStreamApp.Companion.openBrowser
import com.lagradost.cloudstream3.CloudStreamApp.Companion.setKey
import com.lagradost.cloudstream3.CommonActivity.showToast
import com.lagradost.cloudstream3.ErrorLoadingException
import com.lagradost.cloudstream3.LoadResponse
import com.lagradost.cloudstream3.NextAiring
import com.lagradost.cloudstream3.R
import com.lagradost.cloudstream3.Score
import com.lagradost.cloudstream3.SearchQuality
import com.lagradost.cloudstream3.SearchResponse
import com.lagradost.cloudstream3.ShowStatus
import com.lagradost.cloudstream3.TvType
import com.lagradost.cloudstream3.mvvm.Resource
import com.lagradost.cloudstream3.mvvm.logError
import com.lagradost.cloudstream3.mvvm.safe
import com.lagradost.cloudstream3.mvvm.safeApiCall
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.APP_STRING
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.NONE_ID
import com.lagradost.cloudstream3.syncproviders.providers.Addic7ed
import com.lagradost.cloudstream3.syncproviders.providers.AniListApi
import com.lagradost.cloudstream3.syncproviders.providers.LocalList
import com.lagradost.cloudstream3.syncproviders.providers.MALApi
import com.lagradost.cloudstream3.syncproviders.providers.KitsuApi
import com.lagradost.cloudstream3.syncproviders.providers.OpenSubtitlesApi
import com.lagradost.cloudstream3.syncproviders.providers.SimklApi
import com.lagradost.cloudstream3.syncproviders.providers.SubDlApi
import com.lagradost.cloudstream3.syncproviders.providers.SubSourceApi
import com.lagradost.cloudstream3.ui.SyncWatchType
import com.lagradost.cloudstream3.ui.library.ListSorting
import com.lagradost.cloudstream3.utils.AppContextUtils.splitQuery
import com.lagradost.cloudstream3.utils.Coroutines.threadSafeListOf
import com.lagradost.cloudstream3.utils.DataStoreHelper
import com.lagradost.cloudstream3.utils.UiText
import com.lagradost.cloudstream3.utils.txt
import me.xdrop.fuzzywuzzy.FuzzySearch
import java.net.URL
import java.security.SecureRandom
import java.util.Date
import java.util.concurrent.TimeUnit
data class AuthLoginPage(
/** The website to open to authenticate */
val url: String,
/**
* State/control code to verify against the redirectUrl to make sure the request is valid.
* This parameter will be saved, and then used in AuthAPI::login.
* */
val payload: String? = null,
)
data class AuthToken(
/**
* This is the general access tokens/api token representing a logged in user.
*
* `Access tokens are the thing that applications use to make API requests on behalf of a user.`
* */
@JsonProperty("accessToken")
val accessToken: String? = null,
/**
* For OAuth a special refresh token is issues to refresh the access token.
* */
@JsonProperty("refreshToken")
val refreshToken: String? = null,
/** In UnixTime (sec) when it expires */
@JsonProperty("accessTokenLifetime")
val accessTokenLifetime: Long? = null,
/** In UnixTime (sec) when it expires */
@JsonProperty("refreshTokenLifetime")
val refreshTokenLifetime: Long? = null,
/** Sometimes AuthToken needs to be customized to store e.g. username/password,
* this acts as a catch all to store text or JSON data. */
@JsonProperty("payload")
val payload: String? = null,
) {
fun isAccessTokenExpired(marginSec: Long = 10L) =
accessTokenLifetime != null && (System.currentTimeMillis() / 1000) + marginSec >= accessTokenLifetime
fun isRefreshTokenExpired(marginSec: Long = 10L) =
refreshTokenLifetime != null && (System.currentTimeMillis() / 1000) + marginSec >= refreshTokenLifetime
}
data class AuthUser(
/** Account display-name, can also be email if name does not exist */
@JsonProperty("name")
val name: String?,
/** Unique account identifier,
* if a subsequent login is done then it will be refused if another account with the same id exists*/
@JsonProperty("id")
val id: Int,
/** Profile picture URL */
@JsonProperty("profilePicture")
val profilePicture: String? = null,
/** Profile picture Headers of the URL */
@JsonProperty("profilePictureHeader")
val profilePictureHeaders: Map? = null
)
/**
* Stores all information that should be used to authorize access.
* Be aware that token and user may change independently when a refresh is needed,
* and as such there should be no strong pairing between the two.
*
* Any local set/get key should use user.id.toString(),
* as token.accessToken (even hashed) is unsecure, and will rotate.
* */
data class AuthData(
@JsonProperty("user")
val user: AuthUser,
@JsonProperty("token")
val token: AuthToken,
)
data class AuthPinData(
val deviceCode: String,
val userCode: String,
/** QR Code url */
val verificationUrl: String,
/** In seconds */
val expiresIn: Int,
/** Check if the code has been verified interval */
val interval: Int,
)
/** The login field requirements to display to the user */
data class AuthLoginRequirement(
val password: Boolean = false,
val username: Boolean = false,
val email: Boolean = false,
val server: Boolean = false,
)
/** What the user responds to the AuthLoginRequirement */
data class AuthLoginResponse(
@JsonProperty("password")
val password: String?,
@JsonProperty("username")
val username: String?,
@JsonProperty("email")
val email: String?,
@JsonProperty("server")
val server: String?,
)
/** Stateless Authentication class used for all personalized content */
abstract class AuthAPI {
open val name: String = "NONE"
open val idPrefix: String = "NONE"
/** Drawable icon of the service */
open val icon: Int? = null
/** If this service requires an account to use */
open val requiresLogin: Boolean = true
/** Link to a website for creating a new account */
open val createAccountUrl: String? = null
/** The sensitive redirect URL from OAuth should contain "/redirectUrlIdentifier" to trigger the login */
open val redirectUrlIdentifier: String? = null
/** Has OAuth2 login support, including login, loginRequest and refreshToken */
open val hasOAuth2: Boolean = false
/** Has on device pin support, aka login with a QR code */
open val hasPin: Boolean = false
/** Has in app login support, aka login with a dialog */
open val hasInApp: Boolean = false
/** The requirements to login in app */
open val inAppLoginRequirement: AuthLoginRequirement? = null
companion object {
val unixTime: Long
get() = System.currentTimeMillis() / 1000L
val unixTimeMs: Long
get() = System.currentTimeMillis()
fun splitRedirectUrl(redirectUrl: String): Map {
return splitQuery(
URL(
redirectUrl.replace(APP_STRING, "https").replace("/#", "?")
)
)
}
fun generateCodeVerifier(): String {
// It is recommended to use a URL-safe string as code_verifier.
// See section 4 of RFC 7636 for more details.
val secureRandom = SecureRandom()
val codeVerifierBytes = ByteArray(96) // base64 has 6bit per char; (8/6)*96 = 128
secureRandom.nextBytes(codeVerifierBytes)
return Base64.encodeToString(codeVerifierBytes, Base64.DEFAULT).trimEnd('=')
.replace("+", "-")
.replace("/", "_").replace("\n", "")
}
}
/** Is this url a valid redirect url for this service? */
@Throws
open fun isValidRedirectUrl(url: String): Boolean =
redirectUrlIdentifier != null && url.contains("/$redirectUrlIdentifier")
/** OAuth2 login from a valid redirectUrl, and payload given in loginRequest */
@Throws
open suspend fun login(redirectUrl: String, payload: String?): AuthToken? =
throw NotImplementedError()
/** OAuth2 login request, asking the service to provide a url to open in the browser */
@Throws
open fun loginRequest(): AuthLoginPage? = throw NotImplementedError()
/** Pin login request, asking the service to provide an verificationUrl to display with a QR code */
@Throws
open suspend fun pinRequest(): AuthPinData? = throw NotImplementedError()
/** OAuth2 token refresh, this ensures that all token passed to other functions will be valid */
@Throws
open suspend fun refreshToken(token: AuthToken): AuthToken? = throw NotImplementedError()
/** Pin login, this will be called periodically while logging in to check if the pin has been verified by the user */
@Throws
open suspend fun login(payload: AuthPinData): AuthToken? = throw NotImplementedError()
/** In app login */
@Throws
open suspend fun login(form: AuthLoginResponse): AuthToken? = throw NotImplementedError()
/** Get the visible user account */
@Throws
open suspend fun user(token: AuthToken?): AuthUser? = throw NotImplementedError()
/**
* An optional security measure to make sure that even if an attacker gets ahold of the token, it will be invalid.
*
* Note that this will currently only be called *once* on logout,
* and as such any network issues it will fail silently, and the token will not be revoked.
**/
@Throws
open suspend fun invalidateToken(token: AuthToken): Nothing = throw NotImplementedError()
@Throws
@Deprecated("Please use the new API for AuthAPI", level = DeprecationLevel.ERROR)
fun toRepo(): AuthRepo = when (this) {
is SubtitleAPI -> SubtitleRepo(this)
is SyncAPI -> SyncRepo(this)
else -> throw NotImplementedError("Unknown inheritance from AuthAPI")
}
@Suppress("DEPRECATION_ERROR")
@Deprecated("Please use the new API for AuthAPI", level = DeprecationLevel.ERROR)
fun loginInfo(): LoginInfo? {
return this.toRepo().authUser()?.let { user ->
LoginInfo(
profilePicture = user.profilePicture,
name = user.name,
accountIndex = -1,
)
}
}
@Deprecated("Please use the new API for AuthAPI", level = DeprecationLevel.ERROR)
suspend fun getPersonalLibrary(): SyncAPI.LibraryMetadata? {
@Suppress("DEPRECATION_ERROR")
return (this.toRepo() as? SyncRepo)?.library()?.getOrThrow()
}
@Deprecated("Please use the new API for AuthAPI", level = DeprecationLevel.ERROR)
class LoginInfo(
val profilePicture: String? = null,
val name: String?,
val accountIndex: Int,
)
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/syncproviders/AuthRepo.kt
================================================
package com.lagradost.cloudstream3.syncproviders
import com.lagradost.cloudstream3.CloudStreamApp.Companion.openBrowser
import com.lagradost.cloudstream3.CommonActivity.showToast
import com.lagradost.cloudstream3.ErrorLoadingException
import com.lagradost.cloudstream3.R
import com.lagradost.cloudstream3.mvvm.logError
import com.lagradost.cloudstream3.mvvm.safe
import com.lagradost.cloudstream3.syncproviders.AccountManager.Companion.NONE_ID
import com.lagradost.cloudstream3.utils.txt
/** Safe abstraction for AuthAPI that provides both a catching interface, and automatic token management. */
abstract class AuthRepo(open val api: AuthAPI) {
fun isValidRedirectUrl(url: String) = safe { api.isValidRedirectUrl(url) } ?: false
val idPrefix get() = api.idPrefix
val name get() = api.name
val icon get() = api.icon
val requiresLogin get() = api.requiresLogin
val createAccountUrl get() = api.createAccountUrl
val hasOAuth2 get() = api.hasOAuth2
val hasPin get() = api.hasPin
val hasInApp get() = api.hasInApp
val inAppLoginRequirement get() = api.inAppLoginRequirement
val isAvailable get() = !api.requiresLogin || authUser() != null
companion object {
private val oauthPayload: MutableMap = mutableMapOf()
}
@Throws
protected suspend fun freshAuth(): AuthData? {
val data = authData() ?: return null
if (data.token.isAccessTokenExpired()) {
val newToken = api.refreshToken(data.token) ?: return null
val newAuth = AuthData(user = data.user, token = newToken)
refreshUser(newAuth)
return newAuth
}
return data
}
@Throws
fun openOAuth2Page(): Boolean {
val page = api.loginRequest() ?: return false
synchronized(oauthPayload) {
oauthPayload.put(idPrefix, page.payload)
}
openBrowser(page.url)
return true
}
fun openOAuth2PageWithToast() {
try {
if (!openOAuth2Page()) {
showToast(txt(R.string.authenticated_user_fail, api.name))
}
} catch (t: Throwable) {
logError(t)
if (t is ErrorLoadingException && t.message != null) {
showToast(t.message)
return
}
showToast(txt(R.string.authenticated_user_fail, api.name))
}
}
suspend fun logout(from: AuthUser) {
val currentAccounts = AccountManager.accounts(idPrefix)
val (newAccounts, oldAccounts) = currentAccounts.partition { it.user.id != from.id }
if (newAccounts.size < currentAccounts.size) {
AccountManager.updateAccounts(idPrefix, newAccounts.toTypedArray())
AccountManager.updateAccountsId(idPrefix, 0)
}
for (oldAccount in oldAccounts) {
try {
api.invalidateToken(oldAccount.token)
} catch (_: NotImplementedError) {
// no-op
} catch (t: Throwable) {
logError(t)
}
}
}
fun refreshUser(newAuth: AuthData) {
val currentAccounts = AccountManager.accounts(idPrefix)
val newAccounts = currentAccounts.map {
if (it.user.id == newAuth.user.id) {
newAuth
} else {
it
}
}.toTypedArray()
AccountManager.updateAccounts(idPrefix, newAccounts)
}
fun authData(): AuthData? = synchronized(AccountManager.cachedAccountIds) {
AccountManager.cachedAccountIds[idPrefix]?.let { id ->
AccountManager.cachedAccounts[idPrefix]?.firstOrNull { data -> data.user.id == id }
}
}
fun authToken(): AuthToken? = authData()?.token
fun authUser(): AuthUser? = authData()?.user
val accounts
get() = synchronized(AccountManager.cachedAccounts) {
AccountManager.cachedAccounts[idPrefix] ?: emptyArray()
}
var accountId
get() = synchronized(AccountManager.cachedAccountIds) {
AccountManager.cachedAccountIds[idPrefix] ?: NONE_ID
}
set(value) {
AccountManager.updateAccountsId(idPrefix, value)
}
@Throws
suspend fun pinRequest() =
api.pinRequest()
@Throws
private suspend fun setupLogin(token: AuthToken): Boolean {
val user = api.user(token) ?: return false
val newAccount = AuthData(
token = token,
user = user,
)
val currentAccounts = AccountManager.accounts(idPrefix)
if (currentAccounts.any { it.user.id == newAccount.user.id }) {
throw ErrorLoadingException("Already logged into this account")
}
val newAccounts = currentAccounts + newAccount
AccountManager.updateAccounts(idPrefix, newAccounts)
AccountManager.updateAccountsId(idPrefix, user.id)
if (this is SyncRepo) {
requireLibraryRefresh = true
}
return true
}
@Throws
suspend fun login(form: AuthLoginResponse): Boolean {
return setupLogin(api.login(form) ?: return false)
}
@Throws
suspend fun login(payload: AuthPinData): Boolean {
return setupLogin(api.login(payload) ?: return false)
}
@Throws
suspend fun login(redirectUrl: String): Boolean {
return setupLogin(
api.login(
redirectUrl,
synchronized(oauthPayload) { oauthPayload[api.idPrefix] }) ?: return false
)
}
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/syncproviders/BackupAPI.kt
================================================
package com.lagradost.cloudstream3.syncproviders
/** Work in progress */
abstract class BackupAPI : AuthAPI() {
open val filename : String = "cloudstream-backup.json"
/** Get the backup file as a JSON string from the remote storage. Return null if not found/empty */
@Throws
open suspend fun downloadFile(auth: AuthData?) : String? = throw NotImplementedError()
/** Get the backup file as a JSON string from the remote storage. */
@Throws
open suspend fun uploadFile(auth: AuthData?, data : String) : String? = throw NotImplementedError()
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/syncproviders/SubtitleAPI.kt
================================================
package com.lagradost.cloudstream3.syncproviders
import androidx.annotation.WorkerThread
import com.lagradost.cloudstream3.subtitles.AbstractSubtitleEntities.SubtitleEntity
import com.lagradost.cloudstream3.subtitles.AbstractSubtitleEntities.SubtitleSearch
import com.lagradost.cloudstream3.subtitles.SubtitleResource
/**
* Stateless subtitle class for external subtitles.
*
* All non-null `AuthToken` will be non-expired when each function is called.
*/
abstract class SubtitleAPI : AuthAPI() {
@WorkerThread
@Throws
open suspend fun search(auth: AuthData?, query: SubtitleSearch): List? =
throw NotImplementedError()
@WorkerThread
@Throws
open suspend fun load(auth: AuthData?, subtitle: SubtitleEntity): String? =
throw NotImplementedError()
@WorkerThread
@Throws
open suspend fun SubtitleResource.getResources(auth: AuthData?, subtitle: SubtitleEntity) {
this.addUrl(load(auth, subtitle))
}
@WorkerThread
@Throws
suspend fun resource(auth: AuthData?, subtitle: SubtitleEntity): SubtitleResource {
return SubtitleResource().apply {
this.getResources(auth, subtitle)
}
}
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/syncproviders/SubtitleRepo.kt
================================================
package com.lagradost.cloudstream3.syncproviders
import androidx.annotation.WorkerThread
import com.lagradost.cloudstream3.APIHolder.unixTime
import com.lagradost.cloudstream3.ErrorLoadingException
import com.lagradost.cloudstream3.subtitles.AbstractSubtitleEntities.SubtitleEntity
import com.lagradost.cloudstream3.subtitles.AbstractSubtitleEntities.SubtitleSearch
import com.lagradost.cloudstream3.subtitles.SubtitleResource
import com.lagradost.cloudstream3.utils.Coroutines.threadSafeListOf
/** Stateless safe abstraction of SubtitleAPI */
class SubtitleRepo(override val api: SubtitleAPI) : AuthRepo(api) {
companion object {
data class SavedSearchResponse(
val unixTime: Long,
val response: List,
val query: SubtitleSearch
)
data class SavedResourceResponse(
val unixTime: Long,
val response: SubtitleResource,
val query: SubtitleEntity
)
// maybe make this a generic struct? right now there is a lot of boilerplate
private val searchCache = threadSafeListOf()
private var searchCacheIndex: Int = 0
private val resourceCache = threadSafeListOf()
private var resourceCacheIndex: Int = 0
const val CACHE_SIZE = 20
}
@WorkerThread
suspend fun resource(data: SubtitleEntity): Result = runCatching {
synchronized(resourceCache) {
for (item in resourceCache) {
// 20 min save
if (item.query == data && (unixTime - item.unixTime) < 60 * 20) {
return@runCatching item.response
}
}
}
val returnValue = api.resource(freshAuth(), data)
synchronized(resourceCache) {
val add = SavedResourceResponse(unixTime, returnValue, data)
if (resourceCache.size > CACHE_SIZE) {
resourceCache[resourceCacheIndex] = add // rolling cache
resourceCacheIndex = (resourceCacheIndex + 1) % CACHE_SIZE
} else {
resourceCache.add(add)
}
}
returnValue
}
@WorkerThread
suspend fun search(query: SubtitleSearch): Result> {
return runCatching {
synchronized(searchCache) {
for (item in searchCache) {
// 120 min save
if (item.query == query && (unixTime - item.unixTime) < 60 * 120) {
return@runCatching item.response
}
}
}
val returnValue =
api.search(freshAuth(), query) ?: emptyList()
// only cache valid return values
if (returnValue.isNotEmpty()) {
val add = SavedSearchResponse(unixTime, returnValue, query)
synchronized(searchCache) {
if (searchCache.size > CACHE_SIZE) {
searchCache[searchCacheIndex] = add // rolling cache
searchCacheIndex = (searchCacheIndex + 1) % CACHE_SIZE
} else {
searchCache.add(add)
}
}
}
returnValue
}
}
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/syncproviders/SyncAPI.kt
================================================
package com.lagradost.cloudstream3.syncproviders
import androidx.annotation.WorkerThread
import com.lagradost.cloudstream3.ActorData
import com.lagradost.cloudstream3.NextAiring
import com.lagradost.cloudstream3.Score
import com.lagradost.cloudstream3.SearchQuality
import com.lagradost.cloudstream3.SearchResponse
import com.lagradost.cloudstream3.ShowStatus
import com.lagradost.cloudstream3.TvType
import com.lagradost.cloudstream3.ui.SyncWatchType
import com.lagradost.cloudstream3.ui.library.ListSorting
import com.lagradost.cloudstream3.utils.UiText
import me.xdrop.fuzzywuzzy.FuzzySearch
import java.util.Date
/**
* Stateless synchronization class, used for syncing status about a specific movie/show.
*
* All non-null `AuthToken` will be non-expired when each function is called.
*/
abstract class SyncAPI : AuthAPI() {
/**
* Set this to true if the user updates something on the list like watch status or score
**/
open var requireLibraryRefresh: Boolean = true
open val mainUrl: String = "NONE"
/** Currently unused, but will be used to correctly render the UI.
* This should specify what sync watch types can be used with this service. */
open val supportedWatchTypes: Set = SyncWatchType.entries.toSet()
/**
* Allows certain providers to open pages from
* library links.
**/
open val syncIdName: SyncIdName? = null
/** Modify the current status of an item */
@Throws
@WorkerThread
open suspend fun updateStatus(
auth: AuthData?,
id: String,
newStatus: AbstractSyncStatus
): Boolean = throw NotImplementedError()
/** Get the current status of an item */
@Throws
@WorkerThread
open suspend fun status(auth: AuthData?, id: String): AbstractSyncStatus? =
throw NotImplementedError()
/** Get metadata about an item */
@Throws
@WorkerThread
open suspend fun load(auth: AuthData?, id: String): SyncResult? = throw NotImplementedError()
/** Search this service for any results for a given query */
@Throws
@WorkerThread
open suspend fun search(auth: AuthData?, query: String): List? =
throw NotImplementedError()
/** Get the current library/bookmarks of this service */
@Throws
@WorkerThread
open suspend fun library(auth: AuthData?): LibraryMetadata? = throw NotImplementedError()
/** Helper function, may be used in the future */
@Throws
open fun urlToId(url: String): String? = null
data class SyncSearchResult(
override val name: String,
override val apiName: String,
var syncId: String,
override val url: String,
override var posterUrl: String?,
override var type: TvType? = null,
override var quality: SearchQuality? = null,
override var posterHeaders: Map? = null,
override var id: Int? = null,
override var score: Score? = null,
) : SearchResponse
abstract class AbstractSyncStatus {
abstract var status: SyncWatchType
abstract var score: Score?
abstract var watchedEpisodes: Int?
abstract var isFavorite: Boolean?
abstract var maxEpisodes: Int?
}
data class SyncStatus(
override var status: SyncWatchType,
override var score: Score?,
override var watchedEpisodes: Int?,
override var isFavorite: Boolean? = null,
override var maxEpisodes: Int? = null,
) : AbstractSyncStatus()
data class SyncResult(
/**Used to verify*/
var id: String,
var totalEpisodes: Int? = null,
var title: String? = null,
var publicScore: Score? = null,
/**In minutes*/
var duration: Int? = null,
var synopsis: String? = null,
var airStatus: ShowStatus? = null,
var nextAiring: NextAiring? = null,
var studio: List? = null,
var genres: List? = null,
var synonyms: List? = null,
var trailers: List? = null,
var isAdult: Boolean? = null,
var posterUrl: String? = null,
var backgroundPosterUrl: String? = null,
/** In unixtime */
var startDate: Long? = null,
/** In unixtime */
var endDate: Long? = null,
var recommendations: List? = null,
var nextSeason: SyncSearchResult? = null,
var prevSeason: SyncSearchResult? = null,
var actors: List? = null,
)
data class Page(
val title: UiText, var items: List
) {
fun sort(method: ListSorting?, query: String? = null) {
items = when (method) {
ListSorting.Query ->
if (query != null) {
items.sortedBy {
-FuzzySearch.partialRatio(
query.lowercase(), it.name.lowercase()
)
}
} else items
ListSorting.RatingHigh -> items.sortedBy { -(it.personalRating?.toInt(100) ?: 0) }
ListSorting.RatingLow -> items.sortedBy { (it.personalRating?.toInt(100) ?: 0) }
ListSorting.AlphabeticalA -> items.sortedBy { it.name }
ListSorting.AlphabeticalZ -> items.sortedBy { it.name }.reversed()
ListSorting.UpdatedNew -> items.sortedBy { it.lastUpdatedUnixTime?.times(-1) }
ListSorting.UpdatedOld -> items.sortedBy { it.lastUpdatedUnixTime }
ListSorting.ReleaseDateNew -> items.sortedByDescending { it.releaseDate }
ListSorting.ReleaseDateOld -> items.sortedBy { it.releaseDate }
else -> items
}
}
}
data class LibraryMetadata(
val allLibraryLists: List,
val supportedListSorting: Set
)
data class LibraryList(
val name: UiText,
val items: List
)
data class LibraryItem(
override val name: String,
override val url: String,
/**
* Unique unchanging string used for data storage.
* This should be the actual id when you change scores and status
* since score changes from library might get added in the future.
**/
val syncId: String,
val episodesCompleted: Int?,
val episodesTotal: Int?,
val personalRating: Score?,
val lastUpdatedUnixTime: Long?,
override val apiName: String,
override var type: TvType?,
override var posterUrl: String?,
override var posterHeaders: Map?,
override var quality: SearchQuality?,
val releaseDate: Date?,
override var id: Int? = null,
val plot: String? = null,
override var score: Score? = null,
val tags: List? = null
) : SearchResponse
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/syncproviders/SyncRepo.kt
================================================
package com.lagradost.cloudstream3.syncproviders
/** Stateless safe abstraction of SyncAPI */
class SyncRepo(override val api: SyncAPI) : AuthRepo(api) {
val syncIdName = api.syncIdName
var requireLibraryRefresh: Boolean
get() = api.requireLibraryRefresh
set(value) {
api.requireLibraryRefresh = value
}
suspend fun updateStatus(id: String, newStatus: SyncAPI.AbstractSyncStatus): Result =
runCatching {
val status = api.updateStatus(freshAuth() ?: return@runCatching false, id, newStatus)
requireLibraryRefresh = true
status
}
suspend fun status(id: String): Result = runCatching {
api.status(freshAuth(), id)
}
suspend fun load(id: String): Result = runCatching {
api.load(freshAuth(), id)
}
suspend fun library(): Result = runCatching {
api.library(freshAuth())
}
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/syncproviders/providers/Addic7ed.kt
================================================
package com.lagradost.cloudstream3.syncproviders.providers
import com.lagradost.cloudstream3.AllLanguagesName
import com.lagradost.cloudstream3.app
import com.lagradost.cloudstream3.subtitles.AbstractSubtitleEntities.SubtitleEntity
import com.lagradost.cloudstream3.subtitles.AbstractSubtitleEntities.SubtitleSearch
import com.lagradost.cloudstream3.syncproviders.AuthData
import com.lagradost.cloudstream3.syncproviders.SubtitleAPI
import com.lagradost.cloudstream3.TvType
import com.lagradost.cloudstream3.utils.SubtitleHelper.fromTagToEnglishLanguageName
class Addic7ed : SubtitleAPI() {
override val name = "Addic7ed"
override val idPrefix = "addic7ed"
override val requiresLogin = false
companion object {
const val HOST = "https://www.addic7ed.com"
const val TAG = "ADDIC7ED"
}
private fun String.fixUrl(): String {
val url = this
return if (url.startsWith("/")) HOST + url
else if (!url.startsWith("http")) "$HOST/$url"
else url
}
override suspend fun search(
auth: AuthData?,
query: SubtitleSearch
): List? {
val langTagIETF = query.lang ?: AllLanguagesName
val langNumAddic7ed =
langTagIETF2Addic7ed[langTagIETF]?.first ?: 0 // all languages = 0
val langName =
langTagIETF2Addic7ed[langTagIETF]?.second ?:
fromTagToEnglishLanguageName(langTagIETF) ?:
"Completed" // this bypasses language filtering
val title = query.query.trim()
val epNum = query.epNumber ?: 0
val seasonNum = query.seasonNumber ?: 0
val yearNum = query.year ?: 0
val searchQuery = if (seasonNum > 0) "$title $seasonNum $epNum" else title
var downloadPage = ""
fun newSubtitleEntity (
displayName: String?,
link: String?,
isHearingImpaired: Boolean
): SubtitleEntity? {
if (displayName.isNullOrBlank() || link.isNullOrBlank()) return null
return SubtitleEntity(
idPrefix = this.idPrefix,
name = displayName,
lang = langTagIETF,
data = link,
source = this.name,
type = if (seasonNum > 0) TvType.TvSeries else TvType.Movie,
epNumber = epNum,
seasonNumber = seasonNum,
year = yearNum,
headers = mapOf("referer" to "$HOST/"),
isHearingImpaired = isHearingImpaired
)
}
val response = app.get(url = "$HOST/search.php?search=$searchQuery&Submit=Search")
val hostDocument = response.document
// 1st case: found one movie or episode. Redirected to $HOST/movie/1234 or $HOST/serie/show-name/$seasonNum/$epNum/ep-name
if (response.url.contains("/movie/") || response.url.contains("/serie/"))
downloadPage = response.url
// 2nd case: found tv series ep list. Redirected to $HOST/show/1234
else if (response.url.contains("/show/")) {
val showId = response.url.substringAfterLast("/")
val doc = app.get(
"$HOST/ajax_loadShow.php?show=$showId&season=$seasonNum&langs=|$langNumAddic7ed|&hd=0&hi=0",
referer = "$HOST/"
).document
// get direct subtitles links from list
return doc.select("#season tbody tr").mapNotNull { node ->
if (node.select("td:eq(1)").text().toIntOrNull() == epNum)
newSubtitleEntity(
displayName = node.select("td:eq(2)").text() + "\n" + node.select("td:eq(4)").text(),
link = node.selectFirst("a[href~=updated\\/|original\\/]")?.attr("href")?.fixUrl(),
isHearingImpaired = node.select("td:eq(6)").text().isNotEmpty()
)
else null
}
// 3rd case: found several or no results. Still in $HOST/search.php?search=title
} else {// (response.url.contains("/search.php"))
downloadPage = hostDocument.select("table.tabel a").selectFirst({
// tv series
if (seasonNum > 0) "a[href~=serie\\/.+\\/$seasonNum\\/$epNum\\/\\w]"
// movie + year
else if( yearNum > 0) "a[href~=movie\\/]:contains($yearNum)"
// movie
else "a[href~=movie\\/]"
}())?.attr("href")?.fixUrl() ?: return null
}
// filter download page by language. Do not work for movies :/
if (downloadPage.contains("/serie/"))
downloadPage = downloadPage.substringBeforeLast("/") + "/$langNumAddic7ed"
val doc = app.get(url = downloadPage).document
// get subtitles links from download page
return doc.select(".tabel95 .tabel95 tr:has(.language):contains($langName)").mapNotNull { node ->
val displayName =
doc.selectFirst("span.titulo")?.text()?.substringBefore(" Subtitle") + "\n" +
node.parent()!!.select(".NewsTitle").text().substringAfter("Version ").substringBefore(", Duration")
val link =
node.selectFirst("a[href~=updated\\/|original\\/]")?.attr("href")?.fixUrl()
val isHearingImpaired =
node.parent()!!.select("tr:last-child [title=\"Hearing Impaired\"]").isNotEmpty()
newSubtitleEntity(displayName, link, isHearingImpaired)
}
}
override suspend fun load(
auth: AuthData?,
subtitle: SubtitleEntity
): String? {
return subtitle.data
}
// Missing (?_?)
// Pair("2", ""),
// Pair("3", ""),
// Pair("33", ""),
// Pair("34", ""),
// Do not modify unless Addic7ed changes them!
// as they are the exact values from their website
private val langTagIETF2Addic7ed = mapOf(
"ar" to Pair("38", "Arabic"),
"az" to Pair("48", "Azerbaijani"),
"bg" to Pair("35", "Bulgarian"),
"bn" to Pair("47", "Bengali"),
"bs" to Pair("44", "Bosnian"),
"ca" to Pair("12", "Català"),
"cs" to Pair("14", "Czech"),
"cy" to Pair("65", "Welsh"),
"da" to Pair("30", "Danish"),
"de" to Pair("11", "German"),
"el" to Pair("27", "Greek"),
"en" to Pair("1", "English"),
"es-419" to Pair("6", "Spanish (Latin America)"),
"es-ar" to Pair("69", "Spanish (Argentina)"),
"es-es" to Pair("5", "Spanish (Spain)"),
"es" to Pair("4", "Spanish"),
"et" to Pair("54", "Estonian"),
"eu" to Pair("13", "Euskera"),
"fa" to Pair("43", "Persian"),
"fi" to Pair("28", "Finnish"),
"fr-ca" to Pair("53", "French (Canadian)"),
"fr" to Pair("8", "French"),
"gl" to Pair("15", "Galego"),
"he" to Pair("23", "Hebrew"),
"hi" to Pair("55", "Hindi"),
"hr" to Pair("31", "Croatian"),
"hu" to Pair("20", "Hungarian"),
"hy" to Pair("50", "Armenian"),
"id" to Pair("37", "Indonesian"),
"is" to Pair("56", "Icelandic"),
"it" to Pair("7", "Italian"),
"ja" to Pair("32", "Japanese"),
"kn" to Pair("66", "Kannada"),
"ko" to Pair("42", "Korean"),
"lt" to Pair("58", "Lithuanian"),
"lv" to Pair("57", "Latvian"),
"mk" to Pair("49", "Macedonian"),
"ml" to Pair("67", "Malayalam"),
"mr" to Pair("62", "Marathi"),
"ms" to Pair("40", "Malay"),
"nl" to Pair("17", "Dutch"),
"no" to Pair("29", "Norwegian"),
"pl" to Pair("21", "Polish"),
"pt-br" to Pair("10", "Portuguese (Brazilian)"),
"pt" to Pair("9", "Portuguese"),
"ro" to Pair("26", "Romanian"),
"ru" to Pair("19", "Russian"),
"si" to Pair("60", "Sinhala"),
"sk" to Pair("25", "Slovak"),
"sl" to Pair("22", "Slovenian"),
"sq" to Pair("52", "Albanian"),
"sr-latn" to Pair("36", "Serbian (Latin)"),
"sr" to Pair("39", "Serbian (Cyrillic)"),
"sv" to Pair("18", "Swedish"),
"ta" to Pair("59", "Tamil"),
"te" to Pair("63", "Telugu"),
"th" to Pair("46", "Thai"),
"tl" to Pair("68", "Tagalog"),
"tlh" to Pair("61", "Klingon"),
"tr" to Pair("16", "Turkish"),
"uk" to Pair("51", "Ukrainian"),
"vi" to Pair("45", "Vietnamese"),
"yue" to Pair("64", "Cantonese"),
"zh-hans" to Pair("41", "Chinese (Simplified)"),
"zh-hant" to Pair("24", "Chinese (Traditional)"),
)
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/syncproviders/providers/AniListApi.kt
================================================
package com.lagradost.cloudstream3.syncproviders.providers
import androidx.annotation.StringRes
import com.fasterxml.jackson.annotation.JsonProperty
import com.lagradost.cloudstream3.Actor
import com.lagradost.cloudstream3.ActorData
import com.lagradost.cloudstream3.ActorRole
import com.lagradost.cloudstream3.CloudStreamApp.Companion.getKey
import com.lagradost.cloudstream3.CloudStreamApp.Companion.setKey
import com.lagradost.cloudstream3.ErrorLoadingException
import com.lagradost.cloudstream3.NextAiring
import com.lagradost.cloudstream3.R
import com.lagradost.cloudstream3.Score
import com.lagradost.cloudstream3.TvType
import com.lagradost.cloudstream3.app
import com.lagradost.cloudstream3.mvvm.logError
import com.lagradost.cloudstream3.syncproviders.AuthData
import com.lagradost.cloudstream3.syncproviders.AuthLoginPage
import com.lagradost.cloudstream3.syncproviders.AuthToken
import com.lagradost.cloudstream3.syncproviders.AuthUser
import com.lagradost.cloudstream3.syncproviders.SyncAPI
import com.lagradost.cloudstream3.syncproviders.SyncIdName
import com.lagradost.cloudstream3.ui.SyncWatchType
import com.lagradost.cloudstream3.ui.library.ListSorting
import com.lagradost.cloudstream3.utils.AppUtils.parseJson
import com.lagradost.cloudstream3.utils.AppUtils.toJson
import com.lagradost.cloudstream3.utils.AppUtils.tryParseJson
import com.lagradost.cloudstream3.utils.DataStore.toKotlinObject
import com.lagradost.cloudstream3.utils.DataStoreHelper.toYear
import com.lagradost.cloudstream3.utils.txt
import java.net.URLEncoder
import java.util.Locale
class AniListApi : SyncAPI() {
override var name = "AniList"
override val idPrefix = "anilist"
val key = "6871"
override val redirectUrlIdentifier = "anilistlogin"
override var requireLibraryRefresh = true
override val hasOAuth2 = true
override var mainUrl = "https://anilist.co"
override val icon = R.drawable.ic_anilist_icon
override val createAccountUrl = "$mainUrl/signup"
override val syncIdName = SyncIdName.Anilist
override fun loginRequest(): AuthLoginPage? =
AuthLoginPage("https://anilist.co/api/v2/oauth/authorize?client_id=$key&response_type=token")
override suspend fun login(redirectUrl: String, payload: String?): AuthToken? {
val sanitizer = splitRedirectUrl(redirectUrl)
val token = AuthToken(
accessToken = sanitizer["access_token"] ?: throw ErrorLoadingException("No access token"),
//refreshToken = sanitizer["refresh_token"],
accessTokenLifetime = unixTime + sanitizer["expires_in"]!!.toLong(),
)
return token
}
// https://docs.anilist.co/guide/auth/
override suspend fun refreshToken(token: AuthToken): AuthToken? {
// AniList access tokens are long-lived. They will remain valid for 1 year from the time they are issued.
// Refresh tokens are not currently supported. Once a token expires, you will need to re-authenticate your users.
return super.refreshToken(token)
}
override suspend fun user(token: AuthToken?): AuthUser? {
val user = getUser(token ?: return null)
?: throw ErrorLoadingException("Unable to fetch user data")
return AuthUser(
id = user.id,
name = user.name,
profilePicture = user.picture,
)
}
override fun urlToId(url: String): String? =
url.removePrefix("$mainUrl/anime/").removeSuffix("/")
private fun getUrlFromId(id: Int): String {
return "$mainUrl/anime/$id"
}
override suspend fun search(auth : AuthData?, query: String): List? {
val data = searchShows(name) ?: return null
return data.data?.page?.media?.map {
SyncAPI.SyncSearchResult(
it.title.romaji ?: return null,
this.name,
it.id.toString(),
getUrlFromId(it.id),
it.bannerImage
)
}
}
override suspend fun load(auth : AuthData?, id: String): SyncAPI.SyncResult? {
val internalId = (Regex("anilist\\.co/anime/(\\d*)").find(id)?.groupValues?.getOrNull(1)
?: id).toIntOrNull() ?: throw ErrorLoadingException("Invalid internalId")
val season = getSeason(internalId).data.media
return SyncAPI.SyncResult(
season.id.toString(),
nextAiring = season.nextAiringEpisode?.let {
NextAiring(
it.episode ?: return@let null,
(it.timeUntilAiring ?: return@let null) + unixTime
)
},
title = season.title?.userPreferred,
synonyms = season.synonyms,
isAdult = season.isAdult,
totalEpisodes = season.episodes,
synopsis = season.description,
actors = season.characters?.edges?.mapNotNull { edge ->
val node = edge.node ?: return@mapNotNull null
ActorData(
actor = Actor(
name = node.name?.userPreferred ?: node.name?.full ?: node.name?.native
?: return@mapNotNull null,
image = node.image?.large ?: node.image?.medium
),
role = when (edge.role) {
"MAIN" -> ActorRole.Main
"SUPPORTING" -> ActorRole.Supporting
"BACKGROUND" -> ActorRole.Background
else -> null
},
voiceActor = edge.voiceActors?.firstNotNullOfOrNull { staff ->
Actor(
name = staff.name?.userPreferred ?: staff.name?.full
?: staff.name?.native
?: return@mapNotNull null,
image = staff.image?.large ?: staff.image?.medium
)
}
)
},
publicScore = Score.from100(season.averageScore),
recommendations = season.recommendations?.edges?.mapNotNull { rec ->
val recMedia = rec.node.mediaRecommendation
SyncAPI.SyncSearchResult(
name = recMedia?.title?.userPreferred ?: return@mapNotNull null,
this.name,
recMedia.id?.toString() ?: return@mapNotNull null,
getUrlFromId(recMedia.id),
recMedia.coverImage?.extraLarge ?: recMedia.coverImage?.large
?: recMedia.coverImage?.medium
)
},
trailers = when (season.trailer?.site?.lowercase()?.trim()) {
"youtube" -> listOf("https://www.youtube.com/watch?v=${season.trailer.id}")
else -> null
}
//TODO REST
)
}
override suspend fun status(auth : AuthData?, id: String): SyncAPI.AbstractSyncStatus? {
val internalId = id.toIntOrNull() ?: return null
val data = getDataAboutId(auth ?: return null, internalId) ?: return null
return SyncAPI.SyncStatus(
score = Score.from100(data.score),
watchedEpisodes = data.progress,
status = SyncWatchType.fromInternalId(data.type?.value ?: return null),
isFavorite = data.isFavourite,
maxEpisodes = data.episodes,
)
}
override suspend fun updateStatus(
auth: AuthData?,
id: String,
newStatus: AbstractSyncStatus
): Boolean {
return postDataAboutId(
auth ?: return false,
id.toIntOrNull() ?: return false,
fromIntToAnimeStatus(newStatus.status.internalId),
newStatus.score,
newStatus.watchedEpisodes
)
}
companion object {
const val MAX_STALE = 60 * 10
private val aniListStatusString =
arrayOf("CURRENT", "COMPLETED", "PAUSED", "DROPPED", "PLANNING", "REPEATING")
const val ANILIST_CACHED_LIST: String = "anilist_cached_list"
private fun fixName(name: String): String {
return name.lowercase(Locale.ROOT).replace(" ", "")
.replace("[^a-zA-Z0-9]".toRegex(), "")
}
private suspend fun searchShows(name: String): GetSearchRoot? {
try {
val query = """
query (${"$"}id: Int, ${"$"}page: Int, ${"$"}search: String, ${"$"}type: MediaType) {
Page (page: ${"$"}page, perPage: 10) {
media (id: ${"$"}id, search: ${"$"}search, type: ${"$"}type) {
id
idMal
seasonYear
startDate { year month day }
title {
romaji
}
averageScore
meanScore
nextAiringEpisode {
timeUntilAiring
episode
}
trailer { id site thumbnail }
bannerImage
recommendations {
nodes {
id
mediaRecommendation {
id
title {
english
romaji
}
idMal
coverImage { medium large extraLarge }
averageScore
}
}
}
relations {
edges {
id
relationType(version: 2)
node {
format
id
idMal
coverImage { medium large extraLarge }
averageScore
title {
english
romaji
}
}
}
}
}
}
}
"""
val data =
mapOf(
"query" to query,
"variables" to
mapOf(
"search" to name,
"page" to 1,
"type" to "ANIME"
).toJson()
)
val res = app.post(
"https://graphql.anilist.co/",
//headers = mapOf(),
data = data,//(if (vars == null) mapOf("query" to q) else mapOf("query" to q, "variables" to vars))
timeout = 5000 // REASONABLE TIMEOUT
).text.replace("\\", "")
return res.toKotlinObject()
} catch (e: Exception) {
logError(e)
}
return null
}
// Should use https://gist.github.com/purplepinapples/5dc60f15f2837bf1cea71b089cfeaa0a
suspend fun getShowId(malId: String?, name: String, year: Int?): GetSearchMedia? {
// Strips these from the name
val blackList = listOf(
"TV Dubbed",
"(Dub)",
"Subbed",
"(TV)",
"(Uncensored)",
"(Censored)",
"(\\d+)" // year
)
val blackListRegex =
Regex(
""" (${
blackList.joinToString(separator = "|").replace("(", "\\(")
.replace(")", "\\)")
})"""
)
//println("NAME $name NEW NAME ${name.replace(blackListRegex, "")}")
val shows = searchShows(name.replace(blackListRegex, ""))
shows?.data?.page?.media?.find {
(malId ?: "NONE") == it.idMal.toString()
}?.let { return it }
val filtered =
shows?.data?.page?.media?.filter {
(((it.startDate.year ?: year.toString()) == year.toString()
|| year == null))
}
filtered?.forEach {
it.title.romaji?.let { romaji ->
if (fixName(romaji) == fixName(name)) return it
}
}
return filtered?.firstOrNull()
}
// Changing names of these will show up in UI
enum class AniListStatusType(var value: Int, @StringRes val stringRes: Int) {
Watching(0, R.string.type_watching),
Completed(1, R.string.type_completed),
Paused(2, R.string.type_on_hold),
Dropped(3, R.string.type_dropped),
Planning(4, R.string.type_plan_to_watch),
ReWatching(5, R.string.type_re_watching),
None(-1, R.string.none)
}
fun fromIntToAnimeStatus(inp: Int): AniListStatusType {//= AniListStatusType.values().first { it.value == inp }
return when (inp) {
-1 -> AniListStatusType.None
0 -> AniListStatusType.Watching
1 -> AniListStatusType.Completed
2 -> AniListStatusType.Paused
3 -> AniListStatusType.Dropped
4 -> AniListStatusType.Planning
5 -> AniListStatusType.ReWatching
else -> AniListStatusType.None
}
}
fun convertAniListStringToStatus(string: String): AniListStatusType {
return fromIntToAnimeStatus(aniListStatusString.indexOf(string))
}
private suspend fun getSeason(id: Int): SeasonResponse {
val q = """
query (${'$'}id: Int = $id) {
Media (id: ${'$'}id, type: ANIME) {
id
idMal
coverImage {
extraLarge
large
medium
color
}
title {
romaji
english
native
userPreferred
}
duration
episodes
genres
synonyms
averageScore
isAdult
description(asHtml: false)
characters(sort: ROLE page: 1 perPage: 20) {
edges {
role
voiceActors {
name {
userPreferred
full
native
}
age
image {
large
medium
}
}
node {
name {
userPreferred
full
native
}
age
image {
large
medium
}
}
}
}
trailer {
id
site
thumbnail
}
relations {
edges {
id
relationType(version: 2)
node {
id
coverImage {
extraLarge
large
medium
color
}
}
}
}
recommendations {
edges {
node {
mediaRecommendation {
id
coverImage {
extraLarge
large
medium
color
}
title {
romaji
english
native
userPreferred
}
}
}
}
}
nextAiringEpisode {
timeUntilAiring
episode
}
format
}
}
"""
val data = app.post(
"https://graphql.anilist.co",
data = mapOf("query" to q),
cacheTime = 0,
).text
return tryParseJson(data) ?: throw ErrorLoadingException("Error parsing $data")
}
}
private suspend fun getDataAboutId(auth : AuthData, id: Int): AniListTitleHolder? {
val q =
"""query (${'$'}id: Int = $id) { # Define which variables will be used in the query (id)
Media (id: ${'$'}id, type: ANIME) { # Insert our variables into the query arguments (id) (type: ANIME is hard-coded in the query)
id
episodes
isFavourite
mediaListEntry {
progress
status
score (format: POINT_100)
}
title {
english
romaji
}
}
}"""
val data = postApi(auth.token, q, true)
val d = parseJson(data ?: return null)
val main = d.data?.media
if (main?.mediaListEntry != null) {
return AniListTitleHolder(
title = main.title,
id = id,
isFavourite = main.isFavourite,
progress = main.mediaListEntry.progress,
episodes = main.episodes,
score = main.mediaListEntry.score,
type = fromIntToAnimeStatus(aniListStatusString.indexOf(main.mediaListEntry.status)),
)
} else {
return AniListTitleHolder(
title = main?.title,
id = id,
isFavourite = main?.isFavourite,
progress = 0,
episodes = main?.episodes,
score = 0,
type = AniListStatusType.None,
)
}
}
private suspend fun postApi(token : AuthToken, q: String, cache: Boolean = false): String? {
return app.post(
"https://graphql.anilist.co/",
headers = mapOf(
"Authorization" to "Bearer ${token.accessToken ?: return null}",
if (cache) "Cache-Control" to "max-stale=$MAX_STALE" else "Cache-Control" to "no-cache"
),
cacheTime = 0,
data = mapOf(
"query" to URLEncoder.encode(
q,
"UTF-8"
)
), //(if (vars == null) mapOf("query" to q) else mapOf("query" to q, "variables" to vars))
timeout = 5 // REASONABLE TIMEOUT
).text.replace("\\/", "/")
}
data class MediaRecommendation(
@JsonProperty("id") val id: Int,
@JsonProperty("title") val title: Title?,
@JsonProperty("idMal") val idMal: Int?,
@JsonProperty("coverImage") val coverImage: CoverImage?,
@JsonProperty("averageScore") val averageScore: Int?
)
data class FullAnilistList(
@JsonProperty("data") val data: Data?
)
data class CompletedAt(
@JsonProperty("year") val year: Int,
@JsonProperty("month") val month: Int,
@JsonProperty("day") val day: Int
)
data class StartedAt(
@JsonProperty("year") val year: String?,
@JsonProperty("month") val month: String?,
@JsonProperty("day") val day: String?
)
data class Title(
@JsonProperty("english") val english: String?,
@JsonProperty("romaji") val romaji: String?
)
data class CoverImage(
@JsonProperty("medium") val medium: String?,
@JsonProperty("large") val large: String?,
@JsonProperty("extraLarge") val extraLarge: String?
)
data class Media(
@JsonProperty("id") val id: Int,
@JsonProperty("idMal") val idMal: Int?,
@JsonProperty("season") val season: String?,
@JsonProperty("seasonYear") val seasonYear: Int,
@JsonProperty("format") val format: String?,
//@JsonProperty("source") val source: String,
@JsonProperty("episodes") val episodes: Int,
@JsonProperty("title") val title: Title,
@JsonProperty("description") val description: String?,
@JsonProperty("coverImage") val coverImage: CoverImage,
@JsonProperty("synonyms") val synonyms: List,
@JsonProperty("nextAiringEpisode") val nextAiringEpisode: SeasonNextAiringEpisode?,
)
data class Entries(
@JsonProperty("status") val status: String?,
@JsonProperty("completedAt") val completedAt: CompletedAt,
@JsonProperty("startedAt") val startedAt: StartedAt,
@JsonProperty("updatedAt") val updatedAt: Int,
@JsonProperty("progress") val progress: Int,
@JsonProperty("score") val score: Int,
@JsonProperty("private") val private: Boolean,
@JsonProperty("media") val media: Media
) {
fun toLibraryItem(): SyncAPI.LibraryItem {
return SyncAPI.LibraryItem(
// English title first
this.media.title.english ?: this.media.title.romaji
?: this.media.synonyms.firstOrNull()
?: "",
"https://anilist.co/anime/${this.media.id}/",
this.media.id.toString(),
this.progress,
this.media.episodes,
Score.from100(this.score),
this.updatedAt.toLong(),
"AniList",
TvType.Anime,
this.media.coverImage.extraLarge ?: this.media.coverImage.large
?: this.media.coverImage.medium,
null,
null,
this.media.seasonYear.toYear(),
null,
plot = this.media.description,
)
}
}
data class Lists(
@JsonProperty("status") val status: String?,
@JsonProperty("entries") val entries: List
)
data class MediaListCollection(
@JsonProperty("lists") val lists: List
)
data class Data(
@JsonProperty("MediaListCollection") val mediaListCollection: MediaListCollection
)
private suspend fun getAniListAnimeListSmart(auth: AuthData): Array? {
return if (requireLibraryRefresh) {
val list = getFullAniListList(auth)?.data?.mediaListCollection?.lists?.toTypedArray()
if (list != null) {
setKey(ANILIST_CACHED_LIST, auth.user.id.toString(), list)
}
list
} else {
getKey>(
ANILIST_CACHED_LIST,
auth.user.id.toString()
) as? Array
}
}
override suspend fun library(auth : AuthData?): SyncAPI.LibraryMetadata? {
val list = getAniListAnimeListSmart(auth ?: return null)?.groupBy {
convertAniListStringToStatus(it.status ?: "").stringRes
}?.mapValues { group ->
group.value.map { it.entries.map { entry -> entry.toLibraryItem() } }.flatten()
} ?: emptyMap()
// To fill empty lists when AniList does not return them
val baseMap =
AniListStatusType.entries.filter { it.value >= 0 }.associate {
it.stringRes to emptyList()
}
return SyncAPI.LibraryMetadata(
(baseMap + list).map { SyncAPI.LibraryList(txt(it.key), it.value) },
setOf(
ListSorting.AlphabeticalA,
ListSorting.AlphabeticalZ,
ListSorting.UpdatedNew,
ListSorting.UpdatedOld,
ListSorting.ReleaseDateNew,
ListSorting.ReleaseDateOld,
ListSorting.RatingHigh,
ListSorting.RatingLow,
)
)
}
private suspend fun getFullAniListList(auth : AuthData): FullAnilistList? {
val userID = auth.user.id
val mediaType = "ANIME"
val query = """
query (${'$'}userID: Int = $userID, ${'$'}MEDIA: MediaType = $mediaType) {
MediaListCollection (userId: ${'$'}userID, type: ${'$'}MEDIA) {
lists {
status
entries
{
status
completedAt { year month day }
startedAt { year month day }
updatedAt
progress
score (format: POINT_100)
private
media
{
id
idMal
season
seasonYear
format
episodes
chapters
title
{
english
romaji
}
coverImage { extraLarge large medium }
synonyms
nextAiringEpisode {
timeUntilAiring
episode
}
}
}
}
}
}
"""
val text = postApi(auth.token, query)
return text?.toKotlinObject()
}
suspend fun toggleLike(auth : AuthData, id: Int): Boolean {
val q = """mutation (${'$'}animeId: Int = $id) {
ToggleFavourite (animeId: ${'$'}animeId) {
anime {
nodes {
id
title {
romaji
}
}
}
}
}"""
val data = postApi(auth.token, q)
return data != ""
}
/** Used to query a saved MediaItem on the list to get the id for removal */
data class MediaListItemRoot(@JsonProperty("data") val data: MediaListItem? = null)
data class MediaListItem(@JsonProperty("MediaList") val mediaList: MediaListId? = null)
data class MediaListId(@JsonProperty("id") val id: Long? = null)
private suspend fun postDataAboutId(
auth : AuthData,
id: Int,
type: AniListStatusType,
score: Score?,
progress: Int?
): Boolean {
val userID = auth.user.id
val q =
// Delete item if status type is None
if (type == AniListStatusType.None) {
// Get list ID for deletion
val idQuery = """
query MediaList(${'$'}userId: Int = $userID, ${'$'}mediaId: Int = $id) {
MediaList(userId: ${'$'}userId, mediaId: ${'$'}mediaId) {
id
}
}
"""
val response = postApi(auth.token, idQuery)
val listId =
tryParseJson(response)?.data?.mediaList?.id ?: return false
"""
mutation(${'$'}id: Int = $listId) {
DeleteMediaListEntry(id: ${'$'}id) {
deleted
}
}
"""
} else {
"""mutation (${'$'}id: Int = $id, ${'$'}status: MediaListStatus = ${
aniListStatusString[maxOf(
0,
type.value
)]
}, ${if (score != null) "${'$'}scoreRaw: Int = ${score.toInt(100)}" else ""} , ${if (progress != null) "${'$'}progress: Int = $progress" else ""}) {
SaveMediaListEntry (mediaId: ${'$'}id, status: ${'$'}status, scoreRaw: ${'$'}scoreRaw, progress: ${'$'}progress) {
id
status
progress
score
}
}"""
}
val data = postApi(auth.token, q)
return data != ""
}
private suspend fun getUser(token : AuthToken): AniListUser? {
val q = """
{
Viewer {
id
name
avatar {
large
}
favourites {
anime {
nodes {
id
}
}
}
}
}"""
val data = postApi(token, q)
if (data.isNullOrBlank()) return null
val userData = parseJson(data)
val u = userData.data?.viewer ?: return null
val user = AniListUser(
u.id,
u.name,
u.avatar?.large,
)
return user
}
suspend fun getAllSeasons(id: Int): List {
val seasons = mutableListOf()
suspend fun getSeasonRecursive(id: Int) {
val season = getSeason(id)
seasons.add(season)
if (season.data.media.format?.startsWith("TV") == true) {
season.data.media.relations?.edges?.forEach {
if (it.node?.format != null) {
if (it.relationType == "SEQUEL" && it.node.format.startsWith("TV")) {
getSeasonRecursive(it.node.id)
return@forEach
}
}
}
}
}
getSeasonRecursive(id)
return seasons.toList()
}
data class SeasonResponse(
@JsonProperty("data") val data: SeasonData,
)
data class SeasonData(
@JsonProperty("Media") val media: SeasonMedia,
)
data class SeasonMedia(
@JsonProperty("id") val id: Int?,
@JsonProperty("title") val title: MediaTitle?,
@JsonProperty("idMal") val idMal: Int?,
@JsonProperty("format") val format: String?,
@JsonProperty("nextAiringEpisode") val nextAiringEpisode: SeasonNextAiringEpisode?,
@JsonProperty("relations") val relations: SeasonEdges?,
@JsonProperty("coverImage") val coverImage: MediaCoverImage?,
@JsonProperty("duration") val duration: Int?,
@JsonProperty("episodes") val episodes: Int?,
@JsonProperty("genres") val genres: List?,
@JsonProperty("synonyms") val synonyms: List?,
@JsonProperty("averageScore") val averageScore: Int?,
@JsonProperty("isAdult") val isAdult: Boolean?,
@JsonProperty("trailer") val trailer: MediaTrailer?,
@JsonProperty("description") val description: String?,
@JsonProperty("characters") val characters: CharacterConnection?,
@JsonProperty("recommendations") val recommendations: RecommendationConnection?,
)
data class RecommendationConnection(
@JsonProperty("edges") val edges: List = emptyList(),
@JsonProperty("nodes") val nodes: List = emptyList(),
//@JsonProperty("pageInfo") val pageInfo: PageInfo,
)
data class RecommendationEdge(
//@JsonProperty("rating") val rating: Int,
@JsonProperty("node") val node: Recommendation,
)
data class Recommendation(
val id: Long,
@JsonProperty("mediaRecommendation") val mediaRecommendation: SeasonMedia?,
)
data class CharacterName(
@JsonProperty("name") val first: String?,
@JsonProperty("middle") val middle: String?,
@JsonProperty("last") val last: String?,
@JsonProperty("full") val full: String?,
@JsonProperty("native") val native: String?,
@JsonProperty("alternative") val alternative: List?,
@JsonProperty("alternativeSpoiler") val alternativeSpoiler: List?,
@JsonProperty("userPreferred") val userPreferred: String?,
)
data class CharacterImage(
@JsonProperty("large") val large: String?,
@JsonProperty("medium") val medium: String?,
)
data class Character(
@JsonProperty("name") val name: CharacterName?,
@JsonProperty("age") val age: String?,
@JsonProperty("image") val image: CharacterImage?,
)
data class CharacterEdge(
@JsonProperty("id") val id: Int?,
/**
MAIN
A primary character role in the media
SUPPORTING
A supporting character role in the media
BACKGROUND
A background character in the media
*/
@JsonProperty("role") val role: String?,
@JsonProperty("name") val name: String?,
@JsonProperty("voiceActors") val voiceActors: List?,
@JsonProperty("favouriteOrder") val favouriteOrder: Int?,
@JsonProperty("media") val media: List?,
@JsonProperty("node") val node: Character?,
)
data class StaffImage(
@JsonProperty("large") val large: String?,
@JsonProperty("medium") val medium: String?,
)
data class StaffName(
@JsonProperty("name") val first: String?,
@JsonProperty("middle") val middle: String?,
@JsonProperty("last") val last: String?,
@JsonProperty("full") val full: String?,
@JsonProperty("native") val native: String?,
@JsonProperty("alternative") val alternative: List?,
@JsonProperty("userPreferred") val userPreferred: String?,
)
data class Staff(
@JsonProperty("image") val image: StaffImage?,
@JsonProperty("name") val name: StaffName?,
@JsonProperty("age") val age: Int?,
)
data class CharacterConnection(
@JsonProperty("edges") val edges: List?,
@JsonProperty("nodes") val nodes: List?,
//@JsonProperty("pageInfo") pageInfo: PageInfo
)
data class MediaTrailer(
@JsonProperty("id") val id: String?,
@JsonProperty("site") val site: String?,
@JsonProperty("thumbnail") val thumbnail: String?,
)
data class MediaCoverImage(
@JsonProperty("extraLarge") val extraLarge: String?,
@JsonProperty("large") val large: String?,
@JsonProperty("medium") val medium: String?,
@JsonProperty("color") val color: String?,
)
data class SeasonNextAiringEpisode(
@JsonProperty("episode") val episode: Int?,
@JsonProperty("timeUntilAiring") val timeUntilAiring: Int?,
)
data class SeasonEdges(
@JsonProperty("edges") val edges: List?,
)
data class SeasonEdge(
@JsonProperty("id") val id: Int?,
@JsonProperty("relationType") val relationType: String?,
@JsonProperty("node") val node: SeasonNode?,
)
data class AniListFavoritesMediaConnection(
@JsonProperty("nodes") val nodes: List,
)
data class AniListFavourites(
@JsonProperty("anime") val anime: AniListFavoritesMediaConnection,
)
data class MediaTitle(
@JsonProperty("romaji") val romaji: String?,
@JsonProperty("english") val english: String?,
@JsonProperty("native") val native: String?,
@JsonProperty("userPreferred") val userPreferred: String?,
)
data class SeasonNode(
@JsonProperty("id") val id: Int,
@JsonProperty("format") val format: String?,
@JsonProperty("title") val title: Title?,
@JsonProperty("idMal") val idMal: Int?,
@JsonProperty("coverImage") val coverImage: CoverImage?,
@JsonProperty("averageScore") val averageScore: Int?
// @JsonProperty("nextAiringEpisode") val nextAiringEpisode: SeasonNextAiringEpisode?,
)
data class AniListAvatar(
@JsonProperty("large") val large: String?,
)
data class AniListViewer(
@JsonProperty("id") val id: Int,
@JsonProperty("name") val name: String,
@JsonProperty("avatar") val avatar: AniListAvatar?,
@JsonProperty("favourites") val favourites: AniListFavourites?,
)
data class AniListData(
@JsonProperty("Viewer") val viewer: AniListViewer?,
)
data class AniListRoot(
@JsonProperty("data") val data: AniListData?,
)
data class AniListUser(
@JsonProperty("id") val id: Int,
@JsonProperty("name") val name: String,
@JsonProperty("picture") val picture: String?,
)
data class LikeNode(
@JsonProperty("id") val id: Int?,
//@JsonProperty("idMal") public int idMal;
)
data class LikePageInfo(
@JsonProperty("total") val total: Int?,
@JsonProperty("currentPage") val currentPage: Int?,
@JsonProperty("lastPage") val lastPage: Int?,
@JsonProperty("perPage") val perPage: Int?,
@JsonProperty("hasNextPage") val hasNextPage: Boolean?,
)
data class LikeAnime(
@JsonProperty("nodes") val nodes: List?,
@JsonProperty("pageInfo") val pageInfo: LikePageInfo?,
)
data class LikeFavourites(
@JsonProperty("anime") val anime: LikeAnime?,
)
data class LikeViewer(
@JsonProperty("favourites") val favourites: LikeFavourites?,
)
data class LikeData(
@JsonProperty("Viewer") val viewer: LikeViewer?,
)
data class LikeRoot(
@JsonProperty("data") val data: LikeData?,
)
data class AniListTitleHolder(
@JsonProperty("title") val title: Title?,
@JsonProperty("isFavourite") val isFavourite: Boolean?,
@JsonProperty("id") val id: Int?,
@JsonProperty("progress") val progress: Int?,
@JsonProperty("episodes") val episodes: Int?,
@JsonProperty("score") val score: Int?,
@JsonProperty("type") val type: AniListStatusType?,
)
data class GetDataMediaListEntry(
@JsonProperty("progress") val progress: Int?,
@JsonProperty("status") val status: String?,
@JsonProperty("score") val score: Int?,
)
data class Nodes(
@JsonProperty("id") val id: Int?,
@JsonProperty("mediaRecommendation") val mediaRecommendation: MediaRecommendation?
)
data class GetDataMedia(
@JsonProperty("isFavourite") val isFavourite: Boolean?,
@JsonProperty("episodes") val episodes: Int?,
@JsonProperty("title") val title: Title?,
@JsonProperty("mediaListEntry") val mediaListEntry: GetDataMediaListEntry?
)
data class Recommendations(
@JsonProperty("nodes") val nodes: List?
)
data class GetDataData(
@JsonProperty("Media") val media: GetDataMedia?,
)
data class GetDataRoot(
@JsonProperty("data") val data: GetDataData?,
)
data class GetSearchTitle(
@JsonProperty("romaji") val romaji: String?,
)
data class TrailerObject(
@JsonProperty("id") val id: String?,
@JsonProperty("thumbnail") val thumbnail: String?,
@JsonProperty("site") val site: String?,
)
data class GetSearchMedia(
@JsonProperty("id") val id: Int,
@JsonProperty("idMal") val idMal: Int?,
@JsonProperty("seasonYear") val seasonYear: Int,
@JsonProperty("title") val title: GetSearchTitle,
@JsonProperty("startDate") val startDate: StartedAt,
@JsonProperty("averageScore") val averageScore: Int?,
@JsonProperty("meanScore") val meanScore: Int?,
@JsonProperty("bannerImage") val bannerImage: String?,
@JsonProperty("trailer") val trailer: TrailerObject?,
@JsonProperty("nextAiringEpisode") val nextAiringEpisode: SeasonNextAiringEpisode?,
@JsonProperty("recommendations") val recommendations: Recommendations?,
@JsonProperty("relations") val relations: SeasonEdges?
)
data class GetSearchPage(
@JsonProperty("Page") val page: GetSearchData?,
)
data class GetSearchData(
@JsonProperty("media") val media: List?,
)
data class GetSearchRoot(
@JsonProperty("data") val data: GetSearchPage?,
)
}
================================================
FILE: app/src/main/java/com/lagradost/cloudstream3/syncproviders/providers/KitsuApi.kt
================================================
package com.lagradost.cloudstream3.syncproviders.providers
import androidx.annotation.StringRes
import com.fasterxml.jackson.annotation.JsonProperty
import com.lagradost.cloudstream3.CloudStreamApp.Companion.getKey
import com.lagradost.cloudstream3.CloudStreamApp.Companion.setKey
import com.lagradost.cloudstream3.app
import com.lagradost.cloudstream3.R
import com.lagradost.cloudstream3.Score
import com.lagradost.cloudstream3.ShowStatus
import com.lagradost.cloudstream3.TvType
import com.lagradost.cloudstream3.mvvm.logError
import com.lagradost.cloudstream3.syncproviders.AuthData
import com.lagradost.cloudstream3.syncproviders.AuthLoginRequirement
import com.lagradost.cloudstream3.syncproviders.AuthLoginResponse
import com.lagradost.cloudstream3.syncproviders.AuthToken
import com.lagradost.cloudstream3.syncproviders.AuthUser
import com.lagradost.cloudstream3.syncproviders.SyncAPI
import com.lagradost.cloudstream3.syncproviders.SyncIdName
import com.lagradost.cloudstream3.ui.SyncWatchType
import com.lagradost.cloudstream3.ui.library.ListSorting
import com.lagradost.cloudstream3.utils.AppUtils.toJson
import com.lagradost.cloudstream3.utils.txt
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.withIndex
import okhttp3.RequestBody.Companion.toRequestBody
import java.text.SimpleDateFormat
import java.time.Instant
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.util.Date
import java.util.Locale
import kotlin.collections.set
const val KITSU_MAX_SEARCH_LIMIT = 20
class KitsuApi: SyncAPI() {
override var name = "Kitsu"
override val idPrefix = "kitsu"
private val apiUrl = "https://kitsu.io/api/edge"
private val oauthUrl = "https://kitsu.io/api/oauth"
override val hasInApp = true
override val mainUrl = "https://kitsu.app"
override val icon = R.drawable.kitsu_icon
override val syncIdName = SyncIdName.Kitsu
override val createAccountUrl = mainUrl
override val supportedWatchTypes = setOf(
SyncWatchType.WATCHING,
SyncWatchType.COMPLETED,
SyncWatchType.PLANTOWATCH,
SyncWatchType.DROPPED,
SyncWatchType.ONHOLD,
SyncWatchType.NONE
)
override val inAppLoginRequirement = AuthLoginRequirement(
password = true,
email = true
)
override suspend fun login(form: AuthLoginResponse): AuthToken? {
val username = form.email ?: return null
val password = form.password ?: return null
val grantType = "password"
val token = app.post(
"$oauthUrl/token",
data = mapOf(
"grant_type" to grantType,
"username" to username,
"password" to password
)
).parsed()
return AuthToken(
accessTokenLifetime = unixTime + token.expiresIn.toLong(),
refreshToken = token.refreshToken,
accessToken = token.accessToken,
)
}
override suspend fun refreshToken(token: AuthToken): AuthToken {
val res = app.post(
"$oauthUrl/token",
data = mapOf(
"grant_type" to "refresh_token",
"refresh_token" to token.refreshToken!!
)
).parsed()
return AuthToken(
accessToken = res.accessToken,
refreshToken = res.refreshToken,
accessTokenLifetime = unixTime + res.expiresIn.toLong()
)
}
override suspend fun user(token: AuthToken?): AuthUser? {
val user = app.get(
"$apiUrl/users?filter[self]=true",
headers = mapOf(
"Authorization" to "Bearer ${token?.accessToken ?: return null}"
), cacheTime = 0
).parsed()
if (user.data.isEmpty()) {
return null
}
return AuthUser(
id = user.data[0].id.toInt(),
name = user.data[0].attributes.name,
profilePicture = user.data[0].attributes.avatar?.original
)
}
override suspend fun search(auth: AuthData?, query: String): List? {
val auth = auth?.token?.accessToken ?: return null
val animeSelectedFields = arrayOf("titles","canonicalTitle","posterImage","episodeCount")
val url = "$apiUrl/anime?filter[text]=$query&page[limit]=$KITSU_MAX_SEARCH_LIMIT&fields[anime]=${animeSelectedFields.joinToString(",")}"
val res = app.get(
url, headers = mapOf(
"Authorization" to "Bearer $auth",
), cacheTime = 0
).parsed