chore: cleanup pt2

This commit is contained in:
rebelonion 2024-04-19 06:13:14 -05:00
parent 24147e746a
commit 70a50ece43
52 changed files with 501 additions and 294 deletions

View file

@ -5,12 +5,12 @@ import com.google.firebase.FirebaseApp
import com.google.firebase.crashlytics.FirebaseCrashlytics import com.google.firebase.crashlytics.FirebaseCrashlytics
import com.google.firebase.crashlytics.ktx.crashlytics import com.google.firebase.crashlytics.ktx.crashlytics
import com.google.firebase.ktx.Firebase import com.google.firebase.ktx.Firebase
import com.google.firebase.ktx.app
class FirebaseCrashlytics : CrashlyticsInterface { class FirebaseCrashlytics : CrashlyticsInterface {
override fun initialize(context: Context) { override fun initialize(context: Context) {
FirebaseApp.initializeApp(context) FirebaseApp.initializeApp(context)
} }
override fun logException(e: Throwable) { override fun logException(e: Throwable) {
FirebaseCrashlytics.getInstance().recordException(e) FirebaseCrashlytics.getInstance().recordException(e)
} }

View file

@ -8,7 +8,6 @@ import android.content.Context
import android.content.Intent import android.content.Intent
import android.content.IntentFilter import android.content.IntentFilter
import android.net.Uri import android.net.Uri
import android.os.Build
import android.os.Environment import android.os.Environment
import android.widget.TextView import android.widget.TextView
import androidx.core.content.ContextCompat import androidx.core.content.ContextCompat
@ -88,7 +87,11 @@ object AppUpdater {
try { try {
val apks = val apks =
client.get("https://api.github.com/repos/$repo/releases/tags/v$version") client.get("https://api.github.com/repos/$repo/releases/tags/v$version")
.parsed<GithubResponse>().assets?.filter { it.browserDownloadURL.endsWith(".apk") } .parsed<GithubResponse>().assets?.filter {
it.browserDownloadURL.endsWith(
".apk"
)
}
val apkToDownload = apks?.first() val apkToDownload = apks?.first()
apkToDownload?.browserDownloadURL.apply { apkToDownload?.browserDownloadURL.apply {
if (this != null) activity.downloadUpdate(version, this) if (this != null) activity.downloadUpdate(version, this)

View file

@ -1,7 +1,9 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" <manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"> xmlns:tools="http://schemas.android.com/tools">
<uses-sdk tools:overrideLibrary="go.server.gojni" /> <uses-sdk tools:overrideLibrary="go.server.gojni" />
<uses-feature <uses-feature
android:name="android.software.leanback" android:name="android.software.leanback"
android:required="false" /> android:required="false" />
@ -42,8 +44,10 @@
<uses-feature <uses-feature
android:name="android.hardware.bluetooth" android:name="android.hardware.bluetooth"
android:required="false" /> android:required="false" />
<uses-permission android:name="android.permission.BLUETOOTH"
android:maxSdkVersion="30"/> <uses-permission
android:name="android.permission.BLUETOOTH"
android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" /> <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<!-- ExoPlayer: Bluetooth Headsets --> <!-- ExoPlayer: Bluetooth Headsets -->
@ -167,7 +171,7 @@
android:name=".widgets.statistics.ProfileStatsConfigure" android:name=".widgets.statistics.ProfileStatsConfigure"
android:exported="true"> android:exported="true">
<intent-filter> <intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_CONFIGURE"/> <action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" />
</intent-filter> </intent-filter>
</activity> </activity>
@ -430,10 +434,11 @@
android:name="androidx.media3.exoplayer.scheduler.PlatformScheduler$PlatformSchedulerService" android:name="androidx.media3.exoplayer.scheduler.PlatformScheduler$PlatformSchedulerService"
android:exported="true" android:exported="true"
android:permission="android.permission.BIND_JOB_SERVICE" /> android:permission="android.permission.BIND_JOB_SERVICE" />
<service android:name=".addons.torrent.ServerService" <service
android:name=".addons.torrent.ServerService"
android:exported="false" android:exported="false"
android:stopWithTask="true" android:foregroundServiceType="dataSync"
android:foregroundServiceType="dataSync" /> android:stopWithTask="true" />
<meta-data <meta-data
android:name="com.google.android.gms.cast.framework.OPTIONS_PROVIDER_CLASS_NAME" android:name="com.google.android.gms.cast.framework.OPTIONS_PROVIDER_CLASS_NAME"

View file

@ -16,7 +16,6 @@ import android.content.DialogInterface
import android.content.Intent import android.content.Intent
import android.content.pm.PackageManager import android.content.pm.PackageManager
import android.content.res.Configuration import android.content.res.Configuration
import android.content.res.Resources
import android.content.res.Resources.getSystem import android.content.res.Resources.getSystem
import android.graphics.Bitmap import android.graphics.Bitmap
import android.graphics.Color import android.graphics.Color
@ -68,12 +67,9 @@ import android.widget.FrameLayout
import android.widget.ImageView import android.widget.ImageView
import android.widget.TextView import android.widget.TextView
import android.widget.Toast import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate import androidx.appcompat.app.AppCompatDelegate
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import androidx.core.content.ContextCompat.getSystemService import androidx.core.content.ContextCompat.getSystemService
import androidx.core.content.FileProvider import androidx.core.content.FileProvider
import androidx.core.math.MathUtils.clamp import androidx.core.math.MathUtils.clamp
@ -189,9 +185,10 @@ fun currActivity(): Activity? {
var loadMedia: Int? = null var loadMedia: Int? = null
var loadIsMAL = false var loadIsMAL = false
val Int.toPx get() = TypedValue.applyDimension( val Int.toPx
get() = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, this.toFloat(), getSystem().displayMetrics TypedValue.COMPLEX_UNIT_DIP, this.toFloat(), getSystem().displayMetrics
).toInt() ).toInt()
fun initActivity(a: Activity) { fun initActivity(a: Activity) {
val window = a.window val window = a.window
@ -220,7 +217,8 @@ fun initActivity(a: Activity) {
window.decorView window.decorView
).hide(WindowInsetsCompat.Type.statusBars()) ).hide(WindowInsetsCompat.Type.statusBars())
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && statusBarHeight == 0 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && statusBarHeight == 0
&& a.resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) { && a.resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT
) {
window.decorView.rootWindowInsets?.displayCutout?.apply { window.decorView.rootWindowInsets?.displayCutout?.apply {
if (boundingRects.size > 0) { if (boundingRects.size > 0) {
statusBarHeight = min(boundingRects[0].width(), boundingRects[0].height()) statusBarHeight = min(boundingRects[0].width(), boundingRects[0].height())
@ -296,7 +294,12 @@ fun ViewGroup.setBaseline(navBar: AnimatedBottomBar, overlayView: View) {
navBar.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED) navBar.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)
overlayView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED) overlayView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)
clipToPadding = false clipToPadding = false
setPadding(paddingLeft, paddingTop, paddingRight, navBarHeight + navBar.measuredHeight + overlayView.measuredHeight) setPadding(
paddingLeft,
paddingTop,
paddingRight,
navBarHeight + navBar.measuredHeight + overlayView.measuredHeight
)
} }
fun Activity.reloadActivity() { fun Activity.reloadActivity() {
@ -310,7 +313,8 @@ fun Activity.restartApp() {
val mainIntent = Intent.makeRestartActivityTask( val mainIntent = Intent.makeRestartActivityTask(
packageManager.getLaunchIntentForPackage(this.packageName)!!.component packageManager.getLaunchIntentForPackage(this.packageName)!!.component
) )
val component = ComponentName(this@restartApp.packageName, this@restartApp::class.qualifiedName!!) val component =
ComponentName(this@restartApp.packageName, this@restartApp::class.qualifiedName!!)
try { try {
startActivity(Intent().setComponent(component)) startActivity(Intent().setComponent(component))
} catch (e: Exception) { } catch (e: Exception) {
@ -953,7 +957,8 @@ fun copyToClipboard(string: String, toast: Boolean = true) {
fun countDown(media: Media, view: ViewGroup) { fun countDown(media: Media, view: ViewGroup) {
if (media.anime?.nextAiringEpisode != null && media.anime.nextAiringEpisodeTime != null if (media.anime?.nextAiringEpisode != null && media.anime.nextAiringEpisodeTime != null
&& (media.anime.nextAiringEpisodeTime!! - System.currentTimeMillis() / 1000) <= 86400 * 28.toLong()) { && (media.anime.nextAiringEpisodeTime!! - System.currentTimeMillis() / 1000) <= 86400 * 28.toLong()
) {
val v = ItemCountDownBinding.inflate(LayoutInflater.from(view.context), view, false) val v = ItemCountDownBinding.inflate(LayoutInflater.from(view.context), view, false)
view.addView(v.root, 0) view.addView(v.root, 0)
v.mediaCountdownText.text = v.mediaCountdownText.text =
@ -1025,7 +1030,7 @@ fun displayTimer(media: Media, view: ViewGroup) {
when { when {
media.anime != null -> countDown(media, view) media.anime != null -> countDown(media, view)
media.format == "MANGA" || media.format == "ONE_SHOT" -> sinceWhen(media, view) media.format == "MANGA" || media.format == "ONE_SHOT" -> sinceWhen(media, view)
else -> { } // No timer yet else -> {} // No timer yet
} }
} }

View file

@ -35,12 +35,12 @@ import androidx.lifecycle.lifecycleScope
import androidx.media3.common.util.UnstableApi import androidx.media3.common.util.UnstableApi
import androidx.viewpager2.adapter.FragmentStateAdapter import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.work.OneTimeWorkRequest import androidx.work.OneTimeWorkRequest
import ani.dantotsu.addons.torrent.ServerService
import ani.dantotsu.addons.torrent.TorrentAddonManager
import ani.dantotsu.connections.anilist.Anilist import ani.dantotsu.connections.anilist.Anilist
import ani.dantotsu.connections.anilist.AnilistHomeViewModel import ani.dantotsu.connections.anilist.AnilistHomeViewModel
import ani.dantotsu.databinding.ActivityMainBinding import ani.dantotsu.databinding.ActivityMainBinding
import ani.dantotsu.databinding.SplashScreenBinding import ani.dantotsu.databinding.SplashScreenBinding
import ani.dantotsu.addons.torrent.ServerService
import ani.dantotsu.addons.torrent.TorrentAddonManager
import ani.dantotsu.home.AnimeFragment import ani.dantotsu.home.AnimeFragment
import ani.dantotsu.home.HomeFragment import ani.dantotsu.home.HomeFragment
import ani.dantotsu.home.LoginFragment import ani.dantotsu.home.LoginFragment

View file

@ -3,7 +3,6 @@ package ani.dantotsu.connections.anilist
import android.content.ActivityNotFoundException import android.content.ActivityNotFoundException
import android.content.Context import android.content.Context
import android.net.Uri import android.net.Uri
import android.util.Log
import androidx.browser.customtabs.CustomTabsIntent import androidx.browser.customtabs.CustomTabsIntent
import ani.dantotsu.R import ani.dantotsu.R
import ani.dantotsu.client import ani.dantotsu.client
@ -14,7 +13,6 @@ import ani.dantotsu.settings.saving.PrefManager
import ani.dantotsu.settings.saving.PrefName import ani.dantotsu.settings.saving.PrefName
import ani.dantotsu.snackString import ani.dantotsu.snackString
import ani.dantotsu.toast import ani.dantotsu.toast
import ani.dantotsu.tryWithSuspend
import ani.dantotsu.util.Logger import ani.dantotsu.util.Logger
import java.util.Calendar import java.util.Calendar
@ -201,7 +199,9 @@ object Anilist {
toast("Rate limited. Try after $retry seconds") toast("Rate limited. Try after $retry seconds")
throw Exception("Rate limited after $retry seconds") throw Exception("Rate limited after $retry seconds")
} }
if (!json.text.startsWith("{")) {throw Exception(currContext()?.getString(R.string.anilist_down))} if (!json.text.startsWith("{")) {
throw Exception(currContext()?.getString(R.string.anilist_down))
}
if (show) Logger.log("Anilist Response: ${json.text}") if (show) Logger.log("Anilist Response: ${json.text}")
json.parsed() json.parsed()
} else null } else null

View file

@ -1061,21 +1061,32 @@ query (${"$"}page: Int = 1, ${"$"}id: Int, ${"$"}type: MediaType, ${"$"}isAdult:
} }
return null return null
} }
private val onListAnime = (if(PrefManager.getVal(PrefName.IncludeAnimeList)) "" else "onList:false").replace("\"", "")
private val isAdult = (if (PrefManager.getVal(PrefName.AdultOnly)) "isAdult:true" else "").replace("\"", "") private val onListAnime =
private fun recentAnimeUpdates(page: Int): String{ (if (PrefManager.getVal(PrefName.IncludeAnimeList)) "" else "onList:false").replace(
"\"",
""
)
private val isAdult =
(if (PrefManager.getVal(PrefName.AdultOnly)) "isAdult:true" else "").replace("\"", "")
private fun recentAnimeUpdates(page: Int): String {
return """Page(page:$page,perPage:50){pageInfo{hasNextPage total}airingSchedules(airingAt_greater:0 airingAt_lesser:${System.currentTimeMillis() / 1000 - 10000} sort:TIME_DESC){episode airingAt media{id idMal status chapters episodes nextAiringEpisode{episode} isAdult type meanScore isFavourite format bannerImage countryOfOrigin coverImage{large} title{english romaji userPreferred} mediaListEntry{progress private score(format:POINT_100) status}}}}""" return """Page(page:$page,perPage:50){pageInfo{hasNextPage total}airingSchedules(airingAt_greater:0 airingAt_lesser:${System.currentTimeMillis() / 1000 - 10000} sort:TIME_DESC){episode airingAt media{id idMal status chapters episodes nextAiringEpisode{episode} isAdult type meanScore isFavourite format bannerImage countryOfOrigin coverImage{large} title{english romaji userPreferred} mediaListEntry{progress private score(format:POINT_100) status}}}}"""
} }
private fun trendingMovies(page: Int): String{
private fun trendingMovies(page: Int): String {
return """Page(page:$page,perPage:50){pageInfo{hasNextPage total}media(sort:POPULARITY_DESC, type: ANIME, format: MOVIE, $onListAnime, $isAdult){id idMal status chapters episodes nextAiringEpisode{episode}isAdult type meanScore isFavourite format bannerImage countryOfOrigin coverImage{large}title{english romaji userPreferred}mediaListEntry{progress private score(format:POINT_100)status}}}""" return """Page(page:$page,perPage:50){pageInfo{hasNextPage total}media(sort:POPULARITY_DESC, type: ANIME, format: MOVIE, $onListAnime, $isAdult){id idMal status chapters episodes nextAiringEpisode{episode}isAdult type meanScore isFavourite format bannerImage countryOfOrigin coverImage{large}title{english romaji userPreferred}mediaListEntry{progress private score(format:POINT_100)status}}}"""
} }
private fun topRatedAnime(page: Int): String{
private fun topRatedAnime(page: Int): String {
return """Page(page:$page,perPage:50){pageInfo{hasNextPage total}media(sort: SCORE_DESC, type: ANIME, $onListAnime, $isAdult){id idMal status chapters episodes nextAiringEpisode{episode}isAdult type meanScore isFavourite format bannerImage countryOfOrigin coverImage{large}title{english romaji userPreferred}mediaListEntry{progress private score(format:POINT_100)status}}}""" return """Page(page:$page,perPage:50){pageInfo{hasNextPage total}media(sort: SCORE_DESC, type: ANIME, $onListAnime, $isAdult){id idMal status chapters episodes nextAiringEpisode{episode}isAdult type meanScore isFavourite format bannerImage countryOfOrigin coverImage{large}title{english romaji userPreferred}mediaListEntry{progress private score(format:POINT_100)status}}}"""
} }
private fun mostFavAnime(page: Int): String{
private fun mostFavAnime(page: Int): String {
return """Page(page:$page,perPage:50){pageInfo{hasNextPage total}media(sort:FAVOURITES_DESC,type: ANIME, $onListAnime, $isAdult){id idMal status chapters episodes nextAiringEpisode{episode}isAdult type meanScore isFavourite format bannerImage countryOfOrigin coverImage{large}title{english romaji userPreferred}mediaListEntry{progress private score(format:POINT_100)status}}}""" return """Page(page:$page,perPage:50){pageInfo{hasNextPage total}media(sort:FAVOURITES_DESC,type: ANIME, $onListAnime, $isAdult){id idMal status chapters episodes nextAiringEpisode{episode}isAdult type meanScore isFavourite format bannerImage countryOfOrigin coverImage{large}title{english romaji userPreferred}mediaListEntry{progress private score(format:POINT_100)status}}}"""
} }
suspend fun loadAnimeList(): Map<String, ArrayList<Media>>{
suspend fun loadAnimeList(): Map<String, ArrayList<Media>> {
val list = mutableMapOf<String, ArrayList<Media>>() val list = mutableMapOf<String, ArrayList<Media>>()
fun query(): String { fun query(): String {
return """{ return """{
@ -1136,25 +1147,36 @@ query (${"$"}page: Int = 1, ${"$"}id: Int, ${"$"}type: MediaType, ${"$"}isAdult:
} }
return list return list
} }
private val onListManga = (if(PrefManager.getVal(PrefName.IncludeMangaList)) "" else "onList:false").replace("\"", "")
private fun trendingManga(page: Int): String{ private val onListManga =
(if (PrefManager.getVal(PrefName.IncludeMangaList)) "" else "onList:false").replace(
"\"",
""
)
private fun trendingManga(page: Int): String {
return """Page(page:$page,perPage:50){pageInfo{hasNextPage total}media(sort:POPULARITY_DESC, type: MANGA,countryOfOrigin:JP, $onListManga, $isAdult){id idMal status chapters episodes nextAiringEpisode{episode}isAdult type meanScore isFavourite format bannerImage countryOfOrigin coverImage{large}title{english romaji userPreferred}mediaListEntry{progress private score(format:POINT_100)status}}}""" return """Page(page:$page,perPage:50){pageInfo{hasNextPage total}media(sort:POPULARITY_DESC, type: MANGA,countryOfOrigin:JP, $onListManga, $isAdult){id idMal status chapters episodes nextAiringEpisode{episode}isAdult type meanScore isFavourite format bannerImage countryOfOrigin coverImage{large}title{english romaji userPreferred}mediaListEntry{progress private score(format:POINT_100)status}}}"""
} }
private fun trendingManhwa(page: Int): String{
private fun trendingManhwa(page: Int): String {
return """Page(page:$page,perPage:50){pageInfo{hasNextPage total}media(sort:POPULARITY_DESC, type: MANGA, countryOfOrigin:KR, $onListManga, $isAdult){id idMal status chapters episodes nextAiringEpisode{episode}isAdult type meanScore isFavourite format bannerImage countryOfOrigin coverImage{large}title{english romaji userPreferred}mediaListEntry{progress private score(format:POINT_100)status}}}""" return """Page(page:$page,perPage:50){pageInfo{hasNextPage total}media(sort:POPULARITY_DESC, type: MANGA, countryOfOrigin:KR, $onListManga, $isAdult){id idMal status chapters episodes nextAiringEpisode{episode}isAdult type meanScore isFavourite format bannerImage countryOfOrigin coverImage{large}title{english romaji userPreferred}mediaListEntry{progress private score(format:POINT_100)status}}}"""
} }
private fun trendingNovel(page: Int): String{
private fun trendingNovel(page: Int): String {
return """Page(page:$page,perPage:50){pageInfo{hasNextPage total}media(sort:POPULARITY_DESC, type: MANGA, format: NOVEL, countryOfOrigin:JP, $onListManga, $isAdult){id idMal status chapters episodes nextAiringEpisode{episode}isAdult type meanScore isFavourite format bannerImage countryOfOrigin coverImage{large}title{english romaji userPreferred}mediaListEntry{progress private score(format:POINT_100)status}}}""" return """Page(page:$page,perPage:50){pageInfo{hasNextPage total}media(sort:POPULARITY_DESC, type: MANGA, format: NOVEL, countryOfOrigin:JP, $onListManga, $isAdult){id idMal status chapters episodes nextAiringEpisode{episode}isAdult type meanScore isFavourite format bannerImage countryOfOrigin coverImage{large}title{english romaji userPreferred}mediaListEntry{progress private score(format:POINT_100)status}}}"""
} }
private fun topRatedManga(page: Int): String{
private fun topRatedManga(page: Int): String {
return """Page(page:$page,perPage:50){pageInfo{hasNextPage total}media(sort: SCORE_DESC, type: MANGA, $onListManga, $isAdult){id idMal status chapters episodes nextAiringEpisode{episode}isAdult type meanScore isFavourite format bannerImage countryOfOrigin coverImage{large}title{english romaji userPreferred}mediaListEntry{progress private score(format:POINT_100)status}}}""" return """Page(page:$page,perPage:50){pageInfo{hasNextPage total}media(sort: SCORE_DESC, type: MANGA, $onListManga, $isAdult){id idMal status chapters episodes nextAiringEpisode{episode}isAdult type meanScore isFavourite format bannerImage countryOfOrigin coverImage{large}title{english romaji userPreferred}mediaListEntry{progress private score(format:POINT_100)status}}}"""
} }
private fun mostFavManga(page: Int): String{
private fun mostFavManga(page: Int): String {
return """Page(page:$page,perPage:50){pageInfo{hasNextPage total}media(sort:FAVOURITES_DESC,type: MANGA, $onListManga, $isAdult){id idMal status chapters episodes nextAiringEpisode{episode}isAdult type meanScore isFavourite format bannerImage countryOfOrigin coverImage{large}title{english romaji userPreferred}mediaListEntry{progress private score(format:POINT_100)status}}}""" return """Page(page:$page,perPage:50){pageInfo{hasNextPage total}media(sort:FAVOURITES_DESC,type: MANGA, $onListManga, $isAdult){id idMal status chapters episodes nextAiringEpisode{episode}isAdult type meanScore isFavourite format bannerImage countryOfOrigin coverImage{large}title{english romaji userPreferred}mediaListEntry{progress private score(format:POINT_100)status}}}"""
} }
suspend fun loadMangaList(): Map<String, ArrayList<Media>>{
suspend fun loadMangaList(): Map<String, ArrayList<Media>> {
val list = mutableMapOf<String, ArrayList<Media>>() val list = mutableMapOf<String, ArrayList<Media>>()
fun query(): String{ fun query(): String {
return """{ return """{
trendingManga:${trendingManga(1)} trendingManga:${trendingManga(1)}
trendingManga2:${trendingManga(2)} trendingManga2:${trendingManga(2)}
@ -1169,7 +1191,7 @@ query (${"$"}page: Int = 1, ${"$"}id: Int, ${"$"}type: MediaType, ${"$"}isAdult:
}""".trimIndent() }""".trimIndent()
} }
executeQuery<Query.MangaList>(query() , force = true)?.data?.apply { executeQuery<Query.MangaList>(query(), force = true)?.data?.apply {
list["trendingManga"] = trendingManga?.media?.map { Media(it) } as ArrayList<Media> list["trendingManga"] = trendingManga?.media?.map { Media(it) } as ArrayList<Media>
list["trendingManhwa"] = trendingManhwa?.media?.map { Media(it) } as ArrayList<Media> list["trendingManhwa"] = trendingManhwa?.media?.map { Media(it) } as ArrayList<Media>
list["trendingNovel"] = trendingNovel?.media?.map { Media(it) } as ArrayList<Media> list["trendingNovel"] = trendingNovel?.media?.map { Media(it) } as ArrayList<Media>
@ -1185,6 +1207,7 @@ query (${"$"}page: Int = 1, ${"$"}id: Int, ${"$"}type: MediaType, ${"$"}isAdult:
return list return list
} }
suspend fun recentlyUpdated( suspend fun recentlyUpdated(
greater: Long = 0, greater: Long = 0,
lesser: Long = System.currentTimeMillis() / 1000 - 10000 lesser: Long = System.currentTimeMillis() / 1000 - 10000
@ -1235,6 +1258,7 @@ Page(page:$page,perPage:50) {
}""".replace("\n", " ").replace(""" """, "") }""".replace("\n", " ").replace(""" """, "")
return executeQuery<Query.Page>(query, force = true)?.data?.page return executeQuery<Query.Page>(query, force = true)?.data?.page
} }
var i = 1 var i = 1
val list = mutableListOf<Media>() val list = mutableListOf<Media>()
var res: Page? = null var res: Page? = null
@ -1468,7 +1492,8 @@ Page(page:$page,perPage:50) {
val characters = arrayListOf<Character>() val characters = arrayListOf<Character>()
while (hasNextPage) { while (hasNextPage) {
page++ page++
val query = executeQuery<Query.Author>(query(page), force = true val query = executeQuery<Query.Author>(
query(page), force = true
)?.data?.author )?.data?.author
hasNextPage = query?.staffMedia?.let { hasNextPage = query?.staffMedia?.let {
it.edges?.forEach { i -> it.edges?.forEach { i ->
@ -1487,7 +1512,16 @@ Page(page:$page,perPage:50) {
} ?: false } ?: false
query?.characters?.let { query?.characters?.let {
it.nodes?.forEach { i -> it.nodes?.forEach { i ->
characters.add(Character(i.id, i.name?.userPreferred, i.image?.large, i.image?.medium, "", false)) characters.add(
Character(
i.id,
i.name?.userPreferred,
i.image?.large,
i.image?.medium,
"",
false
)
)
} }
} }
} }
@ -1501,6 +1535,7 @@ Page(page:$page,perPage:50) {
author.yearMedia = yearMedia author.yearMedia = yearMedia
return author return author
} }
suspend fun toggleFollow(id: Int): Query.ToggleFollow? { suspend fun toggleFollow(id: Int): Query.ToggleFollow? {
return executeQuery<Query.ToggleFollow>( return executeQuery<Query.ToggleFollow>(
"""mutation{ToggleFollow(userId:$id){id, isFollowing, isFollower}}""" """mutation{ToggleFollow(userId:$id){id, isFollowing, isFollower}}"""
@ -1568,7 +1603,11 @@ Page(page:$page,perPage:50) {
} }
suspend fun getNotifications(id: Int, page: Int = 1, resetNotification: Boolean = true): NotificationResponse? { suspend fun getNotifications(
id: Int,
page: Int = 1,
resetNotification: Boolean = true
): NotificationResponse? {
val reset = if (resetNotification) "true" else "false" val reset = if (resetNotification) "true" else "false"
val res = executeQuery<NotificationResponse>( val res = executeQuery<NotificationResponse>(
"""{User(id:$id){unreadNotificationCount}Page(page:$page,perPage:$ITEMS_PER_PAGE){pageInfo{currentPage,hasNextPage}notifications(resetNotificationCount:$reset){__typename...on AiringNotification{id,type,animeId,episode,contexts,createdAt,media{id,title{romaji,english,native,userPreferred}bannerImage,coverImage{medium,large}},}...on FollowingNotification{id,userId,type,context,createdAt,user{id,name,bannerImage,avatar{medium,large,}}}...on ActivityMessageNotification{id,userId,type,activityId,context,createdAt,message{id}user{id,name,bannerImage,avatar{medium,large,}}}...on ActivityMentionNotification{id,userId,type,activityId,context,createdAt,activity{__typename}user{id,name,bannerImage,avatar{medium,large,}}}...on ActivityReplyNotification{id,userId,type,activityId,context,createdAt,activity{__typename}user{id,name,bannerImage,avatar{medium,large,}}}...on ActivityReplySubscribedNotification{id,userId,type,activityId,context,createdAt,activity{__typename}user{id,name,bannerImage,avatar{medium,large,}}}...on ActivityLikeNotification{id,userId,type,activityId,context,createdAt,activity{__typename}user{id,name,bannerImage,avatar{medium,large,}}}...on ActivityReplyLikeNotification{id,userId,type,activityId,context,createdAt,activity{__typename}user{id,name,bannerImage,avatar{medium,large,}}}...on ThreadCommentMentionNotification{id,userId,type,commentId,context,createdAt,thread{id}comment{id}user{id,name,bannerImage,avatar{medium,large,}}}...on ThreadCommentReplyNotification{id,userId,type,commentId,context,createdAt,thread{id}comment{id}user{id,name,bannerImage,avatar{medium,large,}}}...on ThreadCommentSubscribedNotification{id,userId,type,commentId,context,createdAt,thread{id}comment{id}user{id,name,bannerImage,avatar{medium,large,}}}...on ThreadCommentLikeNotification{id,userId,type,commentId,context,createdAt,thread{id}comment{id}user{id,name,bannerImage,avatar{medium,large,}}}...on ThreadLikeNotification{id,userId,type,threadId,context,createdAt,thread{id}comment{id}user{id,name,bannerImage,avatar{medium,large,}}}...on RelatedMediaAdditionNotification{id,type,context,createdAt,media{id,title{romaji,english,native,userPreferred}bannerImage,coverImage{medium,large}}}...on MediaDataChangeNotification{id,type,mediaId,context,reason,createdAt,media{id,title{romaji,english,native,userPreferred}bannerImage,coverImage{medium,large}}}...on MediaMergeNotification{id,type,mediaId,deletedMediaTitles,context,reason,createdAt,media{id,title{romaji,english,native,userPreferred}bannerImage,coverImage{medium,large}}}...on MediaDeletionNotification{id,type,deletedMediaTitle,context,reason,createdAt,}}}}""", """{User(id:$id){unreadNotificationCount}Page(page:$page,perPage:$ITEMS_PER_PAGE){pageInfo{currentPage,hasNextPage}notifications(resetNotificationCount:$reset){__typename...on AiringNotification{id,type,animeId,episode,contexts,createdAt,media{id,title{romaji,english,native,userPreferred}bannerImage,coverImage{medium,large}},}...on FollowingNotification{id,userId,type,context,createdAt,user{id,name,bannerImage,avatar{medium,large,}}}...on ActivityMessageNotification{id,userId,type,activityId,context,createdAt,message{id}user{id,name,bannerImage,avatar{medium,large,}}}...on ActivityMentionNotification{id,userId,type,activityId,context,createdAt,activity{__typename}user{id,name,bannerImage,avatar{medium,large,}}}...on ActivityReplyNotification{id,userId,type,activityId,context,createdAt,activity{__typename}user{id,name,bannerImage,avatar{medium,large,}}}...on ActivityReplySubscribedNotification{id,userId,type,activityId,context,createdAt,activity{__typename}user{id,name,bannerImage,avatar{medium,large,}}}...on ActivityLikeNotification{id,userId,type,activityId,context,createdAt,activity{__typename}user{id,name,bannerImage,avatar{medium,large,}}}...on ActivityReplyLikeNotification{id,userId,type,activityId,context,createdAt,activity{__typename}user{id,name,bannerImage,avatar{medium,large,}}}...on ThreadCommentMentionNotification{id,userId,type,commentId,context,createdAt,thread{id}comment{id}user{id,name,bannerImage,avatar{medium,large,}}}...on ThreadCommentReplyNotification{id,userId,type,commentId,context,createdAt,thread{id}comment{id}user{id,name,bannerImage,avatar{medium,large,}}}...on ThreadCommentSubscribedNotification{id,userId,type,commentId,context,createdAt,thread{id}comment{id}user{id,name,bannerImage,avatar{medium,large,}}}...on ThreadCommentLikeNotification{id,userId,type,commentId,context,createdAt,thread{id}comment{id}user{id,name,bannerImage,avatar{medium,large,}}}...on ThreadLikeNotification{id,userId,type,threadId,context,createdAt,thread{id}comment{id}user{id,name,bannerImage,avatar{medium,large,}}}...on RelatedMediaAdditionNotification{id,type,context,createdAt,media{id,title{romaji,english,native,userPreferred}bannerImage,coverImage{medium,large}}}...on MediaDataChangeNotification{id,type,mediaId,context,reason,createdAt,media{id,title{romaji,english,native,userPreferred}bannerImage,coverImage{medium,large}}}...on MediaMergeNotification{id,type,mediaId,deletedMediaTitles,context,reason,createdAt,media{id,title{romaji,english,native,userPreferred}bannerImage,coverImage{medium,large}}}...on MediaDeletionNotification{id,type,deletedMediaTitle,context,reason,createdAt,}}}}""",
@ -1583,7 +1622,12 @@ Page(page:$page,perPage:50) {
return res return res
} }
suspend fun getFeed(userId: Int?, global: Boolean = false, page: Int = 1, activityId: Int? = null): FeedResponse? { suspend fun getFeed(
userId: Int?,
global: Boolean = false,
page: Int = 1,
activityId: Int? = null
): FeedResponse? {
val filter = if (activityId != null) "id:$activityId," val filter = if (activityId != null) "id:$activityId,"
else if (userId != null) "userId:$userId," else if (userId != null) "userId:$userId,"
else if (global) "isFollowing:false,hasRepliesOrTypeText:true," else if (global) "isFollowing:false,hasRepliesOrTypeText:true,"
@ -1612,14 +1656,26 @@ Page(page:$page,perPage:50) {
.filter { it.timeUntilAiring != null } .filter { it.timeUntilAiring != null }
} }
suspend fun isUserFav(favType: AnilistMutations.FavType, id: Int): Boolean { //anilist isFavourite is broken, so we need to check it manually suspend fun isUserFav(
val res = getUserProfile(Anilist.userid?: return false) favType: AnilistMutations.FavType,
id: Int
): Boolean { //anilist isFavourite is broken, so we need to check it manually
val res = getUserProfile(Anilist.userid ?: return false)
return when (favType) { return when (favType) {
AnilistMutations.FavType.ANIME -> res?.data?.user?.favourites?.anime?.nodes?.any { it.id == id } ?: false AnilistMutations.FavType.ANIME -> res?.data?.user?.favourites?.anime?.nodes?.any { it.id == id }
AnilistMutations.FavType.MANGA -> res?.data?.user?.favourites?.manga?.nodes?.any { it.id == id } ?: false ?: false
AnilistMutations.FavType.CHARACTER -> res?.data?.user?.favourites?.characters?.nodes?.any { it.id == id } ?: false
AnilistMutations.FavType.STAFF -> res?.data?.user?.favourites?.staff?.nodes?.any { it.id == id } ?: false AnilistMutations.FavType.MANGA -> res?.data?.user?.favourites?.manga?.nodes?.any { it.id == id }
AnilistMutations.FavType.STUDIO -> res?.data?.user?.favourites?.studios?.nodes?.any { it.id == id } ?: false ?: false
AnilistMutations.FavType.CHARACTER -> res?.data?.user?.favourites?.characters?.nodes?.any { it.id == id }
?: false
AnilistMutations.FavType.STAFF -> res?.data?.user?.favourites?.staff?.nodes?.any { it.id == id }
?: false
AnilistMutations.FavType.STUDIO -> res?.data?.user?.favourites?.studios?.nodes?.any { it.id == id }
?: false
} }
} }

View file

@ -5,9 +5,6 @@ import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.LiveData import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModel
import androidx.webkit.internal.ApiFeature.M
import androidx.webkit.internal.ApiFeature.P
import androidx.webkit.internal.StartupApiFeature
import ani.dantotsu.BuildConfig import ani.dantotsu.BuildConfig
import ani.dantotsu.R import ani.dantotsu.R
import ani.dantotsu.connections.discord.Discord import ani.dantotsu.connections.discord.Discord
@ -190,21 +187,25 @@ class AnilistAnimeViewModel : ViewModel() {
var loaded: Boolean = false var loaded: Boolean = false
private val updated: MutableLiveData<MutableList<Media>> = private val updated: MutableLiveData<MutableList<Media>> =
MutableLiveData<MutableList<Media>>(null) MutableLiveData<MutableList<Media>>(null)
fun getUpdated(): LiveData<MutableList<Media>> = updated fun getUpdated(): LiveData<MutableList<Media>> = updated
private val popularMovies: MutableLiveData<MutableList<Media>> = private val popularMovies: MutableLiveData<MutableList<Media>> =
MutableLiveData<MutableList<Media>>(null) MutableLiveData<MutableList<Media>>(null)
fun getMovies(): LiveData<MutableList<Media>> = popularMovies fun getMovies(): LiveData<MutableList<Media>> = popularMovies
private val topRatedAnime: MutableLiveData<MutableList<Media>> = private val topRatedAnime: MutableLiveData<MutableList<Media>> =
MutableLiveData<MutableList<Media>>(null) MutableLiveData<MutableList<Media>>(null)
fun getTopRated(): LiveData<MutableList<Media>> = topRatedAnime fun getTopRated(): LiveData<MutableList<Media>> = topRatedAnime
private val mostFavAnime: MutableLiveData<MutableList<Media>> = private val mostFavAnime: MutableLiveData<MutableList<Media>> =
MutableLiveData<MutableList<Media>>(null) MutableLiveData<MutableList<Media>>(null)
fun getMostFav(): LiveData<MutableList<Media>> = mostFavAnime fun getMostFav(): LiveData<MutableList<Media>> = mostFavAnime
suspend fun loadAll() { suspend fun loadAll() {
val list= Anilist.query.loadAnimeList() val list = Anilist.query.loadAnimeList()
updated.postValue(list["recentUpdates"]) updated.postValue(list["recentUpdates"])
popularMovies.postValue(list["trendingMovies"]) popularMovies.postValue(list["trendingMovies"])
topRatedAnime.postValue(list["topRated"]) topRatedAnime.postValue(list["topRated"])
@ -283,22 +284,27 @@ class AnilistMangaViewModel : ViewModel() {
private val popularManga: MutableLiveData<MutableList<Media>> = private val popularManga: MutableLiveData<MutableList<Media>> =
MutableLiveData<MutableList<Media>>(null) MutableLiveData<MutableList<Media>>(null)
fun getPopularManga(): LiveData<MutableList<Media>> = popularManga fun getPopularManga(): LiveData<MutableList<Media>> = popularManga
private val popularManhwa: MutableLiveData<MutableList<Media>> = private val popularManhwa: MutableLiveData<MutableList<Media>> =
MutableLiveData<MutableList<Media>>(null) MutableLiveData<MutableList<Media>>(null)
fun getPopularManhwa(): LiveData<MutableList<Media>> = popularManhwa fun getPopularManhwa(): LiveData<MutableList<Media>> = popularManhwa
private val popularNovel: MutableLiveData<MutableList<Media>> = private val popularNovel: MutableLiveData<MutableList<Media>> =
MutableLiveData<MutableList<Media>>(null) MutableLiveData<MutableList<Media>>(null)
fun getPopularNovel(): LiveData<MutableList<Media>> = popularNovel fun getPopularNovel(): LiveData<MutableList<Media>> = popularNovel
private val topRatedManga: MutableLiveData<MutableList<Media>> = private val topRatedManga: MutableLiveData<MutableList<Media>> =
MutableLiveData<MutableList<Media>>(null) MutableLiveData<MutableList<Media>>(null)
fun getTopRated(): LiveData<MutableList<Media>> = topRatedManga fun getTopRated(): LiveData<MutableList<Media>> = topRatedManga
private val mostFavManga: MutableLiveData<MutableList<Media>> = private val mostFavManga: MutableLiveData<MutableList<Media>> =
MutableLiveData<MutableList<Media>>(null) MutableLiveData<MutableList<Media>>(null)
fun getMostFav(): LiveData<MutableList<Media>> = mostFavManga fun getMostFav(): LiveData<MutableList<Media>> = mostFavManga
suspend fun loadAll() { suspend fun loadAll() {
val list = Anilist.query.loadMangaList() val list = Anilist.query.loadMangaList()

View file

@ -4,7 +4,6 @@ import android.net.Uri
import android.os.Bundle import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatActivity
import ani.dantotsu.logError import ani.dantotsu.logError
import ani.dantotsu.util.Logger
import ani.dantotsu.settings.saving.PrefManager import ani.dantotsu.settings.saving.PrefManager
import ani.dantotsu.settings.saving.PrefName import ani.dantotsu.settings.saving.PrefName
import ani.dantotsu.startMainActivity import ani.dantotsu.startMainActivity

View file

@ -11,7 +11,7 @@ data class SearchResults(
var onList: Boolean? = null, var onList: Boolean? = null,
var perPage: Int? = null, var perPage: Int? = null,
var search: String? = null, var search: String? = null,
var countryOfOrigin :String? = null, var countryOfOrigin: String? = null,
var sort: String? = null, var sort: String? = null,
var genres: MutableList<String>? = null, var genres: MutableList<String>? = null,
var excludedGenres: MutableList<String>? = null, var excludedGenres: MutableList<String>? = null,

View file

@ -149,8 +149,10 @@ class Query {
@Serializable @Serializable
data class Data( data class Data(
@SerialName("favoriteAnime") val favoriteAnime: ani.dantotsu.connections.anilist.api.User?, @SerialName("favoriteAnime") val favoriteAnime: ani.dantotsu.connections.anilist.api.User?,
@SerialName("favoriteManga") val favoriteManga: ani.dantotsu.connections.anilist.api.User?) @SerialName("favoriteManga") val favoriteManga: ani.dantotsu.connections.anilist.api.User?
)
} }
@Serializable @Serializable
data class AnimeList( data class AnimeList(
@SerialName("data") @SerialName("data")
@ -168,6 +170,7 @@ class Query {
@SerialName("mostFav2") val mostFav2: ani.dantotsu.connections.anilist.api.Page?, @SerialName("mostFav2") val mostFav2: ani.dantotsu.connections.anilist.api.Page?,
) )
} }
@Serializable @Serializable
data class MangaList( data class MangaList(
@SerialName("data") @SerialName("data")
@ -187,6 +190,7 @@ class Query {
@SerialName("mostFav2") val mostFav2: ani.dantotsu.connections.anilist.api.Page?, @SerialName("mostFav2") val mostFav2: ani.dantotsu.connections.anilist.api.Page?,
) )
} }
@Serializable @Serializable
data class ToggleFollow( data class ToggleFollow(
@SerialName("data") @SerialName("data")
@ -317,13 +321,13 @@ class Query {
val statistics: NNUserStatisticTypes, val statistics: NNUserStatisticTypes,
@SerialName("siteUrl") @SerialName("siteUrl")
val siteUrl: String, val siteUrl: String,
): java.io.Serializable ) : java.io.Serializable
@Serializable @Serializable
data class NNUserStatisticTypes( data class NNUserStatisticTypes(
@SerialName("anime") var anime: NNUserStatistics, @SerialName("anime") var anime: NNUserStatistics,
@SerialName("manga") var manga: NNUserStatistics @SerialName("manga") var manga: NNUserStatistics
): java.io.Serializable ) : java.io.Serializable
@Serializable @Serializable
data class NNUserStatistics( data class NNUserStatistics(
@ -334,7 +338,7 @@ class Query {
@SerialName("episodesWatched") var episodesWatched: Int, @SerialName("episodesWatched") var episodesWatched: Int,
@SerialName("chaptersRead") var chaptersRead: Int, @SerialName("chaptersRead") var chaptersRead: Int,
@SerialName("volumesRead") var volumesRead: Int, @SerialName("volumesRead") var volumesRead: Int,
): java.io.Serializable ) : java.io.Serializable
@Serializable @Serializable
data class UserFavourites( data class UserFavourites(
@ -348,13 +352,13 @@ class Query {
val staff: UserStaffFavouritesCollection, val staff: UserStaffFavouritesCollection,
@SerialName("studios") @SerialName("studios")
val studios: UserStudioFavouritesCollection, val studios: UserStudioFavouritesCollection,
): java.io.Serializable ) : java.io.Serializable
@Serializable @Serializable
data class UserMediaFavouritesCollection( data class UserMediaFavouritesCollection(
@SerialName("nodes") @SerialName("nodes")
val nodes: List<UserMediaImageFavorite>, val nodes: List<UserMediaImageFavorite>,
): java.io.Serializable ) : java.io.Serializable
@Serializable @Serializable
data class UserMediaImageFavorite( data class UserMediaImageFavorite(
@ -362,13 +366,13 @@ class Query {
val id: Int, val id: Int,
@SerialName("coverImage") @SerialName("coverImage")
val coverImage: MediaCoverImage val coverImage: MediaCoverImage
): java.io.Serializable ) : java.io.Serializable
@Serializable @Serializable
data class UserCharacterFavouritesCollection( data class UserCharacterFavouritesCollection(
@SerialName("nodes") @SerialName("nodes")
val nodes: List<UserCharacterImageFavorite>, val nodes: List<UserCharacterImageFavorite>,
): java.io.Serializable ) : java.io.Serializable
@Serializable @Serializable
data class UserCharacterImageFavorite( data class UserCharacterImageFavorite(
@ -380,19 +384,19 @@ class Query {
val image: CharacterImage, val image: CharacterImage,
@SerialName("isFavourite") @SerialName("isFavourite")
val isFavourite: Boolean val isFavourite: Boolean
): java.io.Serializable ) : java.io.Serializable
@Serializable @Serializable
data class UserStaffFavouritesCollection( data class UserStaffFavouritesCollection(
@SerialName("nodes") @SerialName("nodes")
val nodes: List<UserCharacterImageFavorite>, //downstream it's the same as character val nodes: List<UserCharacterImageFavorite>, //downstream it's the same as character
): java.io.Serializable ) : java.io.Serializable
@Serializable @Serializable
data class UserStudioFavouritesCollection( data class UserStudioFavouritesCollection(
@SerialName("nodes") @SerialName("nodes")
val nodes: List<UserStudioFavorite>, val nodes: List<UserStudioFavorite>,
): java.io.Serializable ) : java.io.Serializable
@Serializable @Serializable
data class UserStudioFavorite( data class UserStudioFavorite(
@ -400,7 +404,7 @@ class Query {
val id: Int, val id: Int,
@SerialName("name") @SerialName("name")
val name: String, val name: String,
): java.io.Serializable ) : java.io.Serializable
//---------------------------------------- //----------------------------------------
// Statistics // Statistics
@ -409,12 +413,12 @@ class Query {
data class StatisticsResponse( data class StatisticsResponse(
@SerialName("data") @SerialName("data")
val data: Data val data: Data
): java.io.Serializable { ) : java.io.Serializable {
@Serializable @Serializable
data class Data( data class Data(
@SerialName("User") @SerialName("User")
val user: StatisticsUser? val user: StatisticsUser?
): java.io.Serializable ) : java.io.Serializable
} }
@Serializable @Serializable

View file

@ -21,6 +21,7 @@ enum class NotificationType(val value: String) {
MEDIA_DATA_CHANGE("MEDIA_DATA_CHANGE"), MEDIA_DATA_CHANGE("MEDIA_DATA_CHANGE"),
MEDIA_MERGE("MEDIA_MERGE"), MEDIA_MERGE("MEDIA_MERGE"),
MEDIA_DELETION("MEDIA_DELETION"), MEDIA_DELETION("MEDIA_DELETION"),
//custom //custom
COMMENT_REPLY("COMMENT_REPLY"), COMMENT_REPLY("COMMENT_REPLY"),
} }

View file

@ -93,6 +93,7 @@ data class StaffConnection(
// The pagination information // The pagination information
// @SerialName("pageInfo") var pageInfo: PageInfo?, // @SerialName("pageInfo") var pageInfo: PageInfo?,
) )
@Serializable @Serializable
data class StaffImage( data class StaffImage(
// The character's image of media at its largest size // The character's image of media at its largest size
@ -101,6 +102,7 @@ data class StaffImage(
// The character's image of media at medium size // The character's image of media at medium size
@SerialName("medium") var medium: String?, @SerialName("medium") var medium: String?,
) : java.io.Serializable ) : java.io.Serializable
@Serializable @Serializable
data class StaffEdge( data class StaffEdge(
var role: String?, var role: String?,

View file

@ -111,7 +111,7 @@ data class UserAvatar(
// The avatar of user at medium size // The avatar of user at medium size
@SerialName("medium") var medium: String?, @SerialName("medium") var medium: String?,
): java.io.Serializable ) : java.io.Serializable
@Serializable @Serializable
data class UserStatisticTypes( data class UserStatisticTypes(

View file

@ -24,7 +24,7 @@ class MangaUpdates {
private val apiUrl = "https://api.mangaupdates.com/v1/releases/search" private val apiUrl = "https://api.mangaupdates.com/v1/releases/search"
suspend fun search(title: String, startDate: FuzzyDate?) : MangaUpdatesResponse.Results? { suspend fun search(title: String, startDate: FuzzyDate?): MangaUpdatesResponse.Results? {
return tryWithSuspend { return tryWithSuspend {
val query = JSONObject().apply { val query = JSONObject().apply {
try { try {
@ -96,6 +96,7 @@ class MangaUpdates {
@SerialName("release_date") @SerialName("release_date")
val releaseDate: String val releaseDate: String
) )
@Serializable @Serializable
data class MetaData( data class MetaData(
val series: Series val series: Series

View file

@ -32,7 +32,12 @@ object CommentsAPI {
var isMod: Boolean = false var isMod: Boolean = false
var totalVotes: Int = 0 var totalVotes: Int = 0
suspend fun getCommentsForId(id: Int, page: Int = 1, tag: Int?, sort: String?): CommentResponse? { suspend fun getCommentsForId(
id: Int,
page: Int = 1,
tag: Int?,
sort: String?
): CommentResponse? {
var url = "$ADDRESS/comments/$id/$page" var url = "$ADDRESS/comments/$id/$page"
val request = requestBuilder() val request = requestBuilder()
tag?.let { tag?.let {
@ -399,7 +404,7 @@ object CommentsAPI {
null null
} }
val message = parsed?.message ?: reason ?: error val message = parsed?.message ?: reason ?: error
val fullMessage = if(code == 500) message else "$code: $message" val fullMessage = if (code == 500) message else "$code: $message"
toast(fullMessage) toast(fullMessage)
} }

View file

@ -7,6 +7,7 @@ class CrashlyticsStub : CrashlyticsInterface {
override fun initialize(context: Context) { override fun initialize(context: Context) {
//no-op //no-op
} }
override fun logException(e: Throwable) { override fun logException(e: Throwable) {
Logger.log(e) Logger.log(e)
} }

View file

@ -63,7 +63,7 @@ class DiscordService : Service() {
PowerManager.PARTIAL_WAKE_LOCK, PowerManager.PARTIAL_WAKE_LOCK,
"discordRPC:backgroundPresence" "discordRPC:backgroundPresence"
) )
wakeLock.acquire(30*60*1000L /*30 minutes*/) wakeLock.acquire(30 * 60 * 1000L /*30 minutes*/)
log("WakeLock Acquired") log("WakeLock Acquired")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val serviceChannel = NotificationChannel( val serviceChannel = NotificationChannel(
@ -402,7 +402,8 @@ class DiscordService : Service() {
Thread.sleep(heartbeat.toLong()) Thread.sleep(heartbeat.toLong())
heartbeatSend(webSocket, sequence) heartbeatSend(webSocket, sequence)
log("WebSocket: Heartbeat Sent") log("WebSocket: Heartbeat Sent")
} catch (ignored: InterruptedException) { } } catch (ignored: InterruptedException) {
}
} }
} }

View file

@ -1,9 +1,7 @@
package ani.dantotsu.connections.github package ani.dantotsu.connections.github
import ani.dantotsu.Mapper import ani.dantotsu.Mapper
import ani.dantotsu.R
import ani.dantotsu.client import ani.dantotsu.client
import ani.dantotsu.getAppString
import ani.dantotsu.settings.Developer import ani.dantotsu.settings.Developer
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking import kotlinx.coroutines.runBlocking
@ -17,7 +15,8 @@ class Forks {
fun getForks(): Array<Developer> { fun getForks(): Array<Developer> {
var forks = arrayOf<Developer>() var forks = arrayOf<Developer>()
runBlocking(Dispatchers.IO) { runBlocking(Dispatchers.IO) {
val res = client.get("https://api.github.com/repos/rebelonion/Dantotsu/forks?sort=stargazers") val res =
client.get("https://api.github.com/repos/rebelonion/Dantotsu/forks?sort=stargazers")
.parsed<JsonArray>().map { .parsed<JsonArray>().map {
Mapper.json.decodeFromJsonElement<GithubResponse>(it) Mapper.json.decodeFromJsonElement<GithubResponse>(it)
} }

View file

@ -53,7 +53,11 @@ class DownloadsManager(private val context: Context) {
saveDownloads() saveDownloads()
} }
fun removeDownload(downloadedType: DownloadedType, toast: Boolean = true, onFinished: () -> Unit) { fun removeDownload(
downloadedType: DownloadedType,
toast: Boolean = true,
onFinished: () -> Unit
) {
downloadsList.remove(downloadedType) downloadsList.remove(downloadedType)
CoroutineScope(Dispatchers.IO).launch { CoroutineScope(Dispatchers.IO).launch {
removeDirectory(downloadedType, toast) removeDirectory(downloadedType, toast)

View file

@ -244,7 +244,8 @@ class AnimeDownloaderService : Service() {
headersStringBuilder.append("\"").append("User-Agent: ") headersStringBuilder.append("\"").append("User-Agent: ")
.append(defaultHeaders["User-Agent"]).append("\"\'\r\n\'") .append(defaultHeaders["User-Agent"]).append("\"\'\r\n\'")
} }
val probeRequest = "-headers $headersStringBuilder -i ${task.video.file.url} -show_entries format=duration -v quiet -of csv=\"p=0\"" val probeRequest =
"-headers $headersStringBuilder -i ${task.video.file.url} -show_entries format=duration -v quiet -of csv=\"p=0\""
ffExtension.executeFFProbe( ffExtension.executeFFProbe(
probeRequest probeRequest
) { ) {

View file

@ -267,7 +267,9 @@ class NovelDownloaderService : Service() {
task.coverUrl?.let { task.coverUrl?.let {
file.parentFile?.let { it1 -> downloadImage(it, it1, "cover.jpg") } file.parentFile?.let { it1 -> downloadImage(it, it1, "cover.jpg") }
} }
val outputStream = this@NovelDownloaderService.contentResolver.openOutputStream(file.uri) ?: throw Exception("Could not open OutputStream") val outputStream =
this@NovelDownloaderService.contentResolver.openOutputStream(file.uri)
?: throw Exception("Could not open OutputStream")
val sink = outputStream.sink().buffer() val sink = outputStream.sink().buffer()
val responseBody = response.body val responseBody = response.body

View file

@ -5,9 +5,9 @@ import android.app.PendingIntent
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
import android.os.Build import android.os.Build
import ani.dantotsu.notifications.TaskScheduler.TaskType
import ani.dantotsu.notifications.anilist.AnilistNotificationReceiver import ani.dantotsu.notifications.anilist.AnilistNotificationReceiver
import ani.dantotsu.notifications.comment.CommentNotificationReceiver import ani.dantotsu.notifications.comment.CommentNotificationReceiver
import ani.dantotsu.notifications.TaskScheduler.TaskType
import ani.dantotsu.notifications.subscription.SubscriptionNotificationReceiver import ani.dantotsu.notifications.subscription.SubscriptionNotificationReceiver
import ani.dantotsu.settings.saving.PrefManager import ani.dantotsu.settings.saving.PrefManager
import ani.dantotsu.settings.saving.PrefName import ani.dantotsu.settings.saving.PrefName

View file

@ -5,9 +5,9 @@ import android.content.BroadcastReceiver
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
import android.os.Build import android.os.Build
import ani.dantotsu.notifications.TaskScheduler.TaskType
import ani.dantotsu.notifications.anilist.AnilistNotificationWorker import ani.dantotsu.notifications.anilist.AnilistNotificationWorker
import ani.dantotsu.notifications.comment.CommentNotificationWorker import ani.dantotsu.notifications.comment.CommentNotificationWorker
import ani.dantotsu.notifications.TaskScheduler.TaskType
import ani.dantotsu.settings.saving.PrefManager import ani.dantotsu.settings.saving.PrefManager
import ani.dantotsu.settings.saving.PrefName import ani.dantotsu.settings.saving.PrefName
import ani.dantotsu.util.Logger import ani.dantotsu.util.Logger

View file

@ -21,11 +21,16 @@ interface TaskScheduler {
for (taskType in TaskType.entries) { for (taskType in TaskType.entries) {
val interval = when (taskType) { val interval = when (taskType) {
TaskType.COMMENT_NOTIFICATION -> CommentNotificationWorker.checkIntervals[PrefManager.getVal( TaskType.COMMENT_NOTIFICATION -> CommentNotificationWorker.checkIntervals[PrefManager.getVal(
PrefName.CommentNotificationInterval)] PrefName.CommentNotificationInterval
)]
TaskType.ANILIST_NOTIFICATION -> AnilistNotificationWorker.checkIntervals[PrefManager.getVal( TaskType.ANILIST_NOTIFICATION -> AnilistNotificationWorker.checkIntervals[PrefManager.getVal(
PrefName.AnilistNotificationInterval)] PrefName.AnilistNotificationInterval
)]
TaskType.SUBSCRIPTION_NOTIFICATION -> SubscriptionNotificationWorker.checkIntervals[PrefManager.getVal( TaskType.SUBSCRIPTION_NOTIFICATION -> SubscriptionNotificationWorker.checkIntervals[PrefManager.getVal(
PrefName.SubscriptionNotificationInterval)] PrefName.SubscriptionNotificationInterval
)]
} }
scheduleRepeatingTask(taskType, interval) scheduleRepeatingTask(taskType, interval)
} }
@ -62,6 +67,7 @@ interface TaskScheduler {
} }
} }
} }
enum class TaskType { enum class TaskType {
COMMENT_NOTIFICATION, COMMENT_NOTIFICATION,
ANILIST_NOTIFICATION, ANILIST_NOTIFICATION,

View file

@ -66,6 +66,7 @@ class MediaNameFetch {
val type = object : TypeToken<MediaResponse>() {}.type val type = object : TypeToken<MediaResponse>() {}.type
return gson.fromJson(response, type) return gson.fromJson(response, type)
} }
data class ReturnedData(val title: String, val coverImage: String, val color: String) data class ReturnedData(val title: String, val coverImage: String, val color: String)
data class MediaResponse(val data: Map<String, MediaItem>) data class MediaResponse(val data: Map<String, MediaItem>)

View file

@ -32,7 +32,7 @@ class SubscriptionHelper {
return data return data
} }
private fun saveSelected( mediaId: Int, data: Selected) { private fun saveSelected(mediaId: Int, data: Selected) {
PrefManager.setCustomVal("${mediaId}-select", data) PrefManager.setCustomVal("${mediaId}-select", data)
} }

View file

@ -6,20 +6,15 @@ import android.os.Bundle
import android.view.LayoutInflater import android.view.LayoutInflater
import android.view.View import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import androidx.core.app.NotificationCompat
import androidx.fragment.app.Fragment import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.LinearLayoutManager
import ani.dantotsu.R
import ani.dantotsu.connections.crashlytics.CrashlyticsInterface
import ani.dantotsu.databinding.FragmentExtensionsBinding import ani.dantotsu.databinding.FragmentExtensionsBinding
import ani.dantotsu.settings.paging.AnimeExtensionAdapter import ani.dantotsu.settings.paging.AnimeExtensionAdapter
import ani.dantotsu.settings.paging.AnimeExtensionsViewModel import ani.dantotsu.settings.paging.AnimeExtensionsViewModel
import ani.dantotsu.settings.paging.AnimeExtensionsViewModelFactory import ani.dantotsu.settings.paging.AnimeExtensionsViewModelFactory
import ani.dantotsu.settings.paging.OnAnimeInstallClickListener import ani.dantotsu.settings.paging.OnAnimeInstallClickListener
import ani.dantotsu.snackString
import eu.kanade.tachiyomi.data.notification.Notifications
import eu.kanade.tachiyomi.extension.anime.AnimeExtensionManager import eu.kanade.tachiyomi.extension.anime.AnimeExtensionManager
import eu.kanade.tachiyomi.extension.anime.model.AnimeExtension import eu.kanade.tachiyomi.extension.anime.model.AnimeExtension
import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.collectLatest

View file

@ -10,7 +10,7 @@ import ani.dantotsu.databinding.BottomSheetDiscordRpcBinding
import ani.dantotsu.settings.saving.PrefManager import ani.dantotsu.settings.saving.PrefManager
import ani.dantotsu.settings.saving.PrefName import ani.dantotsu.settings.saving.PrefName
class DiscordDialogFragment: BottomSheetDialogFragment() { class DiscordDialogFragment : BottomSheetDialogFragment() {
private var _binding: BottomSheetDiscordRpcBinding? = null private var _binding: BottomSheetDiscordRpcBinding? = null
private val binding get() = _binding!! private val binding get() = _binding!!
@ -22,11 +22,12 @@ class DiscordDialogFragment: BottomSheetDialogFragment() {
_binding = BottomSheetDiscordRpcBinding.inflate(inflater, container, false) _binding = BottomSheetDiscordRpcBinding.inflate(inflater, container, false)
return binding.root return binding.root
} }
override fun onViewCreated(view: View, savedInstanceState: Bundle?) { override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState) super.onViewCreated(view, savedInstanceState)
when (PrefManager.getCustomVal("discord_mode", "dantotsu")) { when (PrefManager.getCustomVal("discord_mode", "dantotsu")) {
"nothing" -> binding.radioNothing.isChecked= true "nothing" -> binding.radioNothing.isChecked = true
"dantotsu" -> binding.radioDantotsu.isChecked = true "dantotsu" -> binding.radioDantotsu.isChecked = true
"anilist" -> binding.radioAnilist.isChecked = true "anilist" -> binding.radioAnilist.isChecked = true
else -> binding.radioAnilist.isChecked = true else -> binding.radioAnilist.isChecked = true
@ -35,7 +36,8 @@ class DiscordDialogFragment: BottomSheetDialogFragment() {
binding.showIcon.setOnCheckedChangeListener { _, isChecked -> binding.showIcon.setOnCheckedChangeListener { _, isChecked ->
PrefManager.setVal(PrefName.ShowAniListIcon, isChecked) PrefManager.setVal(PrefName.ShowAniListIcon, isChecked)
} }
binding.anilistLinkPreview.text = getString(R.string.anilist_link, PrefManager.getVal<String>(PrefName.AnilistUserName)) binding.anilistLinkPreview.text =
getString(R.string.anilist_link, PrefManager.getVal<String>(PrefName.AnilistUserName))
binding.radioGroup.setOnCheckedChangeListener { _, checkedId -> binding.radioGroup.setOnCheckedChangeListener { _, checkedId ->
val mode = when (checkedId) { val mode = when (checkedId) {

View file

@ -213,9 +213,17 @@ class ExtensionsActivity : AppCompatActivity() {
private fun getSavedRepositories(repoInventory: ViewGroup, type: MediaType) { private fun getSavedRepositories(repoInventory: ViewGroup, type: MediaType) {
repoInventory.removeAllViews() repoInventory.removeAllViews()
val prefName: PrefName? = when (type) { val prefName: PrefName? = when (type) {
MediaType.ANIME -> { PrefName.AnimeExtensionRepos } MediaType.ANIME -> {
MediaType.MANGA -> { PrefName.MangaExtensionRepos } PrefName.AnimeExtensionRepos
else -> { null } }
MediaType.MANGA -> {
PrefName.MangaExtensionRepos
}
else -> {
null
}
} }
prefName?.let { repoList -> prefName?.let { repoList ->
PrefManager.getVal<Set<String>>(repoList).forEach { item -> PrefManager.getVal<Set<String>>(repoList).forEach { item ->
@ -233,9 +241,15 @@ class ExtensionsActivity : AppCompatActivity() {
repoInventory.removeView(view.root) repoInventory.removeView(view.root)
CoroutineScope(Dispatchers.IO).launch { CoroutineScope(Dispatchers.IO).launch {
when (type) { when (type) {
MediaType.ANIME -> { animeExtensionManager.findAvailableExtensions() } MediaType.ANIME -> {
MediaType.MANGA -> { mangaExtensionManager.findAvailableExtensions() } animeExtensionManager.findAvailableExtensions()
else -> { } }
MediaType.MANGA -> {
mangaExtensionManager.findAvailableExtensions()
}
else -> {}
} }
} }
dialog.dismiss() dialog.dismiss()
@ -274,9 +288,17 @@ class ExtensionsActivity : AppCompatActivity() {
private fun generateRepositoryButton(type: MediaType) { private fun generateRepositoryButton(type: MediaType) {
val hintResource: Int? = when (type) { val hintResource: Int? = when (type) {
MediaType.ANIME -> { R.string.anime_add_repository } MediaType.ANIME -> {
MediaType.MANGA -> { R.string.manga_add_repository } R.string.anime_add_repository
else -> { null } }
MediaType.MANGA -> {
R.string.manga_add_repository
}
else -> {
null
}
} }
hintResource?.let { res -> hintResource?.let { res ->
binding.openSettingsButton.setOnClickListener { binding.openSettingsButton.setOnClickListener {

View file

@ -11,7 +11,10 @@ import eu.kanade.tachiyomi.extension.InstallStep
import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get import uy.kohesive.injekt.api.get
class InstallerSteps(private val notificationManager: NotificationManager, private val context: Context) { class InstallerSteps(
private val notificationManager: NotificationManager,
private val context: Context
) {
fun onInstallStep(installStep: InstallStep, extra: () -> Unit) { fun onInstallStep(installStep: InstallStep, extra: () -> Unit) {
val builder = NotificationCompat.Builder( val builder = NotificationCompat.Builder(

View file

@ -6,20 +6,15 @@ import android.os.Bundle
import android.view.LayoutInflater import android.view.LayoutInflater
import android.view.View import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import androidx.core.app.NotificationCompat
import androidx.fragment.app.Fragment import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.LinearLayoutManager
import ani.dantotsu.R
import ani.dantotsu.connections.crashlytics.CrashlyticsInterface
import ani.dantotsu.databinding.FragmentExtensionsBinding import ani.dantotsu.databinding.FragmentExtensionsBinding
import ani.dantotsu.settings.paging.MangaExtensionAdapter import ani.dantotsu.settings.paging.MangaExtensionAdapter
import ani.dantotsu.settings.paging.MangaExtensionsViewModel import ani.dantotsu.settings.paging.MangaExtensionsViewModel
import ani.dantotsu.settings.paging.MangaExtensionsViewModelFactory import ani.dantotsu.settings.paging.MangaExtensionsViewModelFactory
import ani.dantotsu.settings.paging.OnMangaInstallClickListener import ani.dantotsu.settings.paging.OnMangaInstallClickListener
import ani.dantotsu.snackString
import eu.kanade.tachiyomi.data.notification.Notifications
import eu.kanade.tachiyomi.extension.manga.MangaExtensionManager import eu.kanade.tachiyomi.extension.manga.MangaExtensionManager
import eu.kanade.tachiyomi.extension.manga.model.MangaExtension import eu.kanade.tachiyomi.extension.manga.model.MangaExtension
import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.collectLatest

View file

@ -24,7 +24,6 @@ import ani.dantotsu.others.getSerialized
import ani.dantotsu.parsers.Subtitle import ani.dantotsu.parsers.Subtitle
import ani.dantotsu.settings.saving.PrefManager import ani.dantotsu.settings.saving.PrefManager
import ani.dantotsu.settings.saving.PrefName import ani.dantotsu.settings.saving.PrefName
import ani.dantotsu.settings.saving.internal.Pref
import ani.dantotsu.snackString import ani.dantotsu.snackString
import ani.dantotsu.statusBarHeight import ani.dantotsu.statusBarHeight
import ani.dantotsu.themes.ThemeManager import ani.dantotsu.themes.ThemeManager
@ -40,7 +39,8 @@ class PlayerSettingsActivity : AppCompatActivity() {
var media: Media? = null var media: Media? = null
var subtitle: Subtitle? = null var subtitle: Subtitle? = null
private val Int.toSP get() = TypedValue.applyDimension( private val Int.toSP
get() = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_SP, this.toFloat(), Resources.getSystem().displayMetrics TypedValue.COMPLEX_UNIT_SP, this.toFloat(), Resources.getSystem().displayMetrics
) )
@ -151,8 +151,10 @@ class PlayerSettingsActivity : AppCompatActivity() {
binding.playerSettingsTimeStampsAutoHide.isEnabled = isChecked binding.playerSettingsTimeStampsAutoHide.isEnabled = isChecked
} }
binding.playerSettingsTimeStampsAutoHide.isChecked = PrefManager.getVal(PrefName.AutoHideTimeStamps) binding.playerSettingsTimeStampsAutoHide.isChecked =
binding.playerSettingsTimeStampsAutoHide.isEnabled = binding.playerSettingsShowTimeStamp.isChecked PrefManager.getVal(PrefName.AutoHideTimeStamps)
binding.playerSettingsTimeStampsAutoHide.isEnabled =
binding.playerSettingsShowTimeStamp.isChecked
binding.playerSettingsTimeStampsAutoHide.setOnCheckedChangeListener { _, isChecked -> binding.playerSettingsTimeStampsAutoHide.setOnCheckedChangeListener { _, isChecked ->
PrefManager.setVal(PrefName.AutoHideTimeStamps, isChecked) PrefManager.setVal(PrefName.AutoHideTimeStamps, isChecked)
} }
@ -484,10 +486,11 @@ class PlayerSettingsActivity : AppCompatActivity() {
updateSubPreview() updateSubPreview()
} }
} }
binding.subtitleTest.addOnChangeListener(object: Xpandable.OnChangeListener { binding.subtitleTest.addOnChangeListener(object : Xpandable.OnChangeListener {
override fun onExpand() { override fun onExpand() {
updateSubPreview() updateSubPreview()
} }
override fun onRetract() {} override fun onRetract() {}
}) })
updateSubPreview() updateSubPreview()
@ -496,7 +499,8 @@ class PlayerSettingsActivity : AppCompatActivity() {
private fun updateSubPreview() { private fun updateSubPreview() {
binding.subtitleTestWindow.run { binding.subtitleTestWindow.run {
alpha = PrefManager.getVal(PrefName.SubAlpha) alpha = PrefManager.getVal(PrefName.SubAlpha)
setBackgroundColor(when (PrefManager.getVal<Int>(PrefName.SubWindow)) { setBackgroundColor(
when (PrefManager.getVal<Int>(PrefName.SubWindow)) {
0 -> Color.TRANSPARENT 0 -> Color.TRANSPARENT
1 -> Color.BLACK 1 -> Color.BLACK
2 -> Color.DKGRAY 2 -> Color.DKGRAY
@ -510,7 +514,8 @@ class PlayerSettingsActivity : AppCompatActivity() {
10 -> Color.BLUE 10 -> Color.BLUE
11 -> Color.MAGENTA 11 -> Color.MAGENTA
else -> Color.TRANSPARENT else -> Color.TRANSPARENT
}) }
)
} }
binding.subtitleTestText.run { binding.subtitleTestText.run {
textSize = PrefManager.getVal<Int>(PrefName.FontSize).toSP textSize = PrefManager.getVal<Int>(PrefName.FontSize).toSP
@ -524,7 +529,8 @@ class PlayerSettingsActivity : AppCompatActivity() {
6 -> ResourcesCompat.getFont(this.context, R.font.blocky) 6 -> ResourcesCompat.getFont(this.context, R.font.blocky)
else -> ResourcesCompat.getFont(this.context, R.font.poppins_semi_bold) else -> ResourcesCompat.getFont(this.context, R.font.poppins_semi_bold)
} }
setTextColor(when (PrefManager.getVal<Int>(PrefName.PrimaryColor)) { setTextColor(
when (PrefManager.getVal<Int>(PrefName.PrimaryColor)) {
0 -> Color.BLACK 0 -> Color.BLACK
1 -> Color.DKGRAY 1 -> Color.DKGRAY
2 -> Color.GRAY 2 -> Color.GRAY
@ -538,8 +544,10 @@ class PlayerSettingsActivity : AppCompatActivity() {
10 -> Color.MAGENTA 10 -> Color.MAGENTA
11 -> Color.TRANSPARENT 11 -> Color.TRANSPARENT
else -> Color.WHITE else -> Color.WHITE
}) }
setBackgroundColor(when (PrefManager.getVal<Int>(PrefName.SubBackground)) { )
setBackgroundColor(
when (PrefManager.getVal<Int>(PrefName.SubBackground)) {
0 -> Color.TRANSPARENT 0 -> Color.TRANSPARENT
1 -> Color.BLACK 1 -> Color.BLACK
2 -> Color.DKGRAY 2 -> Color.DKGRAY
@ -553,7 +561,8 @@ class PlayerSettingsActivity : AppCompatActivity() {
10 -> Color.BLUE 10 -> Color.BLUE
11 -> Color.MAGENTA 11 -> Color.MAGENTA
else -> Color.TRANSPARENT else -> Color.TRANSPARENT
}) }
)
} }
} }
} }

View file

@ -5,15 +5,15 @@ import ani.dantotsu.databinding.ItemSettingsSwitchBinding
data class Settings( data class Settings(
val type: Int, val type: Int,
val name : String, val name: String,
val desc: String, val desc: String,
val icon : Int, val icon: Int,
val onClick: ((ItemSettingsBinding) -> Unit)? = null, val onClick: ((ItemSettingsBinding) -> Unit)? = null,
val onLongClick: (() -> Unit)? = null, val onLongClick: (() -> Unit)? = null,
val switch: ((isChecked:Boolean , view: ItemSettingsSwitchBinding ) -> Unit)? = null, val switch: ((isChecked: Boolean, view: ItemSettingsSwitchBinding) -> Unit)? = null,
val attach:((ItemSettingsBinding) -> Unit)? = null, val attach: ((ItemSettingsBinding) -> Unit)? = null,
val attachToSwitch : ((ItemSettingsSwitchBinding) -> Unit)? = null, val attachToSwitch: ((ItemSettingsSwitchBinding) -> Unit)? = null,
val isVisible: Boolean = true, val isVisible: Boolean = true,
val isActivity: Boolean = false, val isActivity: Boolean = false,
var isChecked : Boolean = false, var isChecked: Boolean = false,
) )

View file

@ -95,7 +95,7 @@ class SettingsAboutActivity : AppCompatActivity() {
Settings( Settings(
type = 1, type = 1,
name = getString(R.string.devs), name = getString(R.string.devs),
desc= getString(R.string.devs_desc), desc = getString(R.string.devs_desc),
icon = R.drawable.ic_round_accessible_forward_24, icon = R.drawable.ic_round_accessible_forward_24,
onClick = { onClick = {
DevelopersDialogFragment().show(supportFragmentManager, "dialog") DevelopersDialogFragment().show(supportFragmentManager, "dialog")
@ -131,7 +131,8 @@ class SettingsAboutActivity : AppCompatActivity() {
), ),
) )
) )
binding.settingsRecyclerView.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false) binding.settingsRecyclerView.layoutManager =
LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
} }
} }
} }

View file

@ -13,7 +13,6 @@ import ani.dantotsu.R
import ani.dantotsu.connections.anilist.Anilist import ani.dantotsu.connections.anilist.Anilist
import ani.dantotsu.connections.discord.Discord import ani.dantotsu.connections.discord.Discord
import ani.dantotsu.connections.mal.MAL import ani.dantotsu.connections.mal.MAL
import ani.dantotsu.databinding.ActivitySettingsAboutBinding
import ani.dantotsu.databinding.ActivitySettingsAccountsBinding import ani.dantotsu.databinding.ActivitySettingsAccountsBinding
import ani.dantotsu.initActivity import ani.dantotsu.initActivity
import ani.dantotsu.loadImage import ani.dantotsu.loadImage
@ -33,6 +32,7 @@ class SettingsAccountActivity : AppCompatActivity() {
private val restartMainActivity = object : OnBackPressedCallback(false) { private val restartMainActivity = object : OnBackPressedCallback(false) {
override fun handleOnBackPressed() = startMainActivity(this@SettingsAccountActivity) override fun handleOnBackPressed() = startMainActivity(this@SettingsAccountActivity)
} }
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
ThemeManager(this).applyTheme() ThemeManager(this).applyTheme()

View file

@ -12,7 +12,6 @@ import android.os.Bundle
import android.view.ViewGroup import android.view.ViewGroup
import android.widget.TextView import android.widget.TextView
import androidx.activity.addCallback import androidx.activity.addCallback
import androidx.activity.OnBackPressedCallback
import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.updateLayoutParams import androidx.core.view.updateLayoutParams
import androidx.lifecycle.lifecycleScope import androidx.lifecycle.lifecycleScope
@ -69,11 +68,11 @@ class SettingsActivity : AppCompatActivity() {
bottomMargin = navBarHeight bottomMargin = navBarHeight
} }
onBackPressedDispatcher.addCallback(context){ onBackPressedDispatcher.addCallback(context) {
if (PrefManager.getCustomVal("reload", false)) { if (PrefManager.getCustomVal("reload", false)) {
startMainActivity(context) startMainActivity(context)
PrefManager.setCustomVal("reload", false) PrefManager.setCustomVal("reload", false)
}else{ } else {
finish() finish()
} }
} }
@ -278,6 +277,7 @@ class SettingsActivity : AppCompatActivity() {
?: "Unknown Architecture" ?: "Unknown Architecture"
} }
} }
override fun onResume() { override fun onResume() {
ThemeManager(this).applyTheme() ThemeManager(this).applyTheme()
super.onResume() super.onResume()

View file

@ -2,19 +2,14 @@ package ani.dantotsu.settings
import android.content.Context import android.content.Context
import android.os.Bundle import android.os.Bundle
import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import android.view.animation.LinearInterpolator import android.view.animation.LinearInterpolator
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.view.updateLayoutParams import androidx.core.view.updateLayoutParams
import androidx.lifecycle.lifecycleScope import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.LinearLayoutManager
import ani.dantotsu.R import ani.dantotsu.R
import ani.dantotsu.addons.AddonDownloader import ani.dantotsu.addons.AddonDownloader
import ani.dantotsu.addons.AddonListener
import ani.dantotsu.addons.download.DownloadAddonManager import ani.dantotsu.addons.download.DownloadAddonManager
import ani.dantotsu.addons.torrent.ServerService import ani.dantotsu.addons.torrent.ServerService
import ani.dantotsu.addons.torrent.TorrentAddonManager import ani.dantotsu.addons.torrent.TorrentAddonManager
@ -27,15 +22,12 @@ import ani.dantotsu.settings.saving.PrefName
import ani.dantotsu.snackString import ani.dantotsu.snackString
import ani.dantotsu.statusBarHeight import ani.dantotsu.statusBarHeight
import ani.dantotsu.themes.ThemeManager import ani.dantotsu.themes.ThemeManager
import ani.dantotsu.toast
import ani.dantotsu.util.Logger import ani.dantotsu.util.Logger
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job import kotlinx.coroutines.Job
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive import kotlinx.coroutines.isActive
import kotlinx.coroutines.job
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import tachiyomi.core.util.lang.launchIO import tachiyomi.core.util.lang.launchIO

View file

@ -22,7 +22,7 @@ import ani.dantotsu.themes.ThemeManager
import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get import uy.kohesive.injekt.api.get
class SettingsAnimeActivity: AppCompatActivity(){ class SettingsAnimeActivity : AppCompatActivity() {
private lateinit var binding: ActivitySettingsAnimeBinding private lateinit var binding: ActivitySettingsAnimeBinding
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
@ -59,7 +59,12 @@ class SettingsAnimeActivity: AppCompatActivity(){
onClick = { onClick = {
val dialog = AlertDialog.Builder(context, R.style.MyPopup) val dialog = AlertDialog.Builder(context, R.style.MyPopup)
.setTitle(R.string.purge_anime_downloads) .setTitle(R.string.purge_anime_downloads)
.setMessage(getString(R.string.purge_confirm, getString(R.string.anime))) .setMessage(
getString(
R.string.purge_confirm,
getString(R.string.anime)
)
)
.setPositiveButton(R.string.yes) { dialog, _ -> .setPositiveButton(R.string.yes) { dialog, _ ->
val downloadsManager = Injekt.get<DownloadsManager>() val downloadsManager = Injekt.get<DownloadsManager>()
downloadsManager.purgeDownloads(MediaType.ANIME) downloadsManager.purgeDownloads(MediaType.ANIME)

View file

@ -41,9 +41,10 @@ import kotlinx.coroutines.launch
import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get import uy.kohesive.injekt.api.get
class SettingsCommonActivity: AppCompatActivity(){ class SettingsCommonActivity : AppCompatActivity() {
private lateinit var binding: ActivitySettingsCommonBinding private lateinit var binding: ActivitySettingsCommonBinding
private lateinit var launcher: LauncherWrapper private lateinit var launcher: LauncherWrapper
@OptIn(DelicateCoroutinesApi::class) @OptIn(DelicateCoroutinesApi::class)
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
@ -138,7 +139,12 @@ class SettingsCommonActivity: AppCompatActivity(){
desc = getString(R.string.ui_settings), desc = getString(R.string.ui_settings),
icon = R.drawable.ic_round_auto_awesome_24, icon = R.drawable.ic_round_auto_awesome_24,
onClick = { onClick = {
startActivity(Intent(context, UserInterfaceSettingsActivity::class.java)) startActivity(
Intent(
context,
UserInterfaceSettingsActivity::class.java
)
)
}, },
isActivity = true isActivity = true
), ),
@ -150,7 +156,8 @@ class SettingsCommonActivity: AppCompatActivity(){
onClick = { onClick = {
val managers = arrayOf("Default", "1DM", "ADM") val managers = arrayOf("Default", "1DM", "ADM")
val downloadManagerDialog = val downloadManagerDialog =
AlertDialog.Builder(context, R.style.MyPopup).setTitle(R.string.download_manager) AlertDialog.Builder(context, R.style.MyPopup)
.setTitle(R.string.download_manager)
var downloadManager: Int = PrefManager.getVal(PrefName.DownloadManager) var downloadManager: Int = PrefManager.getVal(PrefName.DownloadManager)
val dialog = downloadManagerDialog.setSingleChoiceItems( val dialog = downloadManagerDialog.setSingleChoiceItems(
managers, downloadManager managers, downloadManager
@ -231,7 +238,8 @@ class SettingsCommonActivity: AppCompatActivity(){
launcher.registerForCallback { success -> launcher.registerForCallback { success ->
if (success) { if (success) {
toast(getString(R.string.please_wait)) toast(getString(R.string.please_wait))
val newUri = PrefManager.getVal<String>(PrefName.DownloadsDir) val newUri =
PrefManager.getVal<String>(PrefName.DownloadsDir)
GlobalScope.launch(Dispatchers.IO) { GlobalScope.launch(Dispatchers.IO) {
Injekt.get<DownloadsManager>().moveDownloadsDir( Injekt.get<DownloadsManager>().moveDownloadsDir(
context, Uri.parse(oldUri), Uri.parse(newUri) context, Uri.parse(oldUri), Uri.parse(newUri)
@ -262,7 +270,7 @@ class SettingsCommonActivity: AppCompatActivity(){
desc = getString(R.string.always_continue_content), desc = getString(R.string.always_continue_content),
icon = R.drawable.ic_round_delete_24, icon = R.drawable.ic_round_delete_24,
isChecked = PrefManager.getVal(PrefName.ContinueMedia), isChecked = PrefManager.getVal(PrefName.ContinueMedia),
switch = {isChecked, _ -> switch = { isChecked, _ ->
PrefManager.setVal(PrefName.ContinueMedia, isChecked) PrefManager.setVal(PrefName.ContinueMedia, isChecked)
} }
), ),
@ -272,7 +280,7 @@ class SettingsCommonActivity: AppCompatActivity(){
desc = getString(R.string.search_source_list), desc = getString(R.string.search_source_list),
icon = R.drawable.ic_round_search_sources_24, icon = R.drawable.ic_round_search_sources_24,
isChecked = PrefManager.getVal(PrefName.SearchSources), isChecked = PrefManager.getVal(PrefName.SearchSources),
switch = {isChecked, _ -> switch = { isChecked, _ ->
PrefManager.setVal(PrefName.SearchSources, isChecked) PrefManager.setVal(PrefName.SearchSources, isChecked)
} }
), ),
@ -282,7 +290,7 @@ class SettingsCommonActivity: AppCompatActivity(){
desc = getString(R.string.recentlyListOnly), desc = getString(R.string.recentlyListOnly),
icon = R.drawable.ic_round_new_releases_24, icon = R.drawable.ic_round_new_releases_24,
isChecked = PrefManager.getVal(PrefName.RecentlyListOnly), isChecked = PrefManager.getVal(PrefName.RecentlyListOnly),
switch = {isChecked, _ -> switch = { isChecked, _ ->
PrefManager.setVal(PrefName.RecentlyListOnly, isChecked) PrefManager.setVal(PrefName.RecentlyListOnly, isChecked)
} }
), ),
@ -292,7 +300,7 @@ class SettingsCommonActivity: AppCompatActivity(){
desc = getString(R.string.adult_only_content), desc = getString(R.string.adult_only_content),
icon = R.drawable.ic_round_nsfw_24, icon = R.drawable.ic_round_nsfw_24,
isChecked = PrefManager.getVal(PrefName.AdultOnly), isChecked = PrefManager.getVal(PrefName.AdultOnly),
switch = {isChecked, _ -> switch = { isChecked, _ ->
PrefManager.setVal(PrefName.AdultOnly, isChecked) PrefManager.setVal(PrefName.AdultOnly, isChecked)
restartApp() restartApp()
}, },
@ -334,6 +342,7 @@ class SettingsCommonActivity: AppCompatActivity(){
} }
} }
private fun passwordAlertDialog(isExporting: Boolean, callback: (CharArray?) -> Unit) { private fun passwordAlertDialog(isExporting: Boolean, callback: (CharArray?) -> Unit) {
val password = CharArray(16).apply { fill('0') } val password = CharArray(16).apply { fill('0') }

View file

@ -98,7 +98,7 @@ class SettingsDialogFragment : BottomSheetDialogFragment() {
} }
binding.settingsNotificationCount.isVisible = Anilist.unreadNotificationCount > 0 binding.settingsNotificationCount.isVisible = Anilist.unreadNotificationCount > 0
binding.settingsNotificationCount.text = Anilist.unreadNotificationCount.toString() binding.settingsNotificationCount.text = Anilist.unreadNotificationCount.toString()
binding.settingsUserAvatar.setOnClickListener{ binding.settingsUserAvatar.setOnClickListener {
ContextCompat.startActivity( ContextCompat.startActivity(
requireContext(), Intent(requireContext(), ProfileActivity::class.java) requireContext(), Intent(requireContext(), ProfileActivity::class.java)
.putExtra("userId", Anilist.userid), null .putExtra("userId", Anilist.userid), null

View file

@ -24,7 +24,6 @@ import ani.dantotsu.settings.saving.PrefManager
import ani.dantotsu.settings.saving.PrefName import ani.dantotsu.settings.saving.PrefName
import ani.dantotsu.statusBarHeight import ani.dantotsu.statusBarHeight
import ani.dantotsu.themes.ThemeManager import ani.dantotsu.themes.ThemeManager
import com.google.android.material.textfield.TextInputEditText
import eu.kanade.domain.base.BasePreferences import eu.kanade.domain.base.BasePreferences
import eu.kanade.tachiyomi.extension.anime.AnimeExtensionManager import eu.kanade.tachiyomi.extension.anime.AnimeExtensionManager
import eu.kanade.tachiyomi.extension.manga.MangaExtensionManager import eu.kanade.tachiyomi.extension.manga.MangaExtensionManager
@ -35,7 +34,7 @@ import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get import uy.kohesive.injekt.api.get
import uy.kohesive.injekt.injectLazy import uy.kohesive.injekt.injectLazy
class SettingsExtensionsActivity: AppCompatActivity() { class SettingsExtensionsActivity : AppCompatActivity() {
private lateinit var binding: ActivitySettingsExtensionsBinding private lateinit var binding: ActivitySettingsExtensionsBinding
private val extensionInstaller = Injekt.get<BasePreferences>().extensionInstaller() private val extensionInstaller = Injekt.get<BasePreferences>().extensionInstaller()
private val animeExtensionManager: AnimeExtensionManager by injectLazy() private val animeExtensionManager: AnimeExtensionManager by injectLazy()
@ -52,7 +51,7 @@ class SettingsExtensionsActivity: AppCompatActivity() {
topMargin = statusBarHeight topMargin = statusBarHeight
bottomMargin = navBarHeight bottomMargin = navBarHeight
} }
extensionSettingsBack.setOnClickListener{ extensionSettingsBack.setOnClickListener {
onBackPressedDispatcher.onBackPressed() onBackPressedDispatcher.onBackPressed()
} }
fun setExtensionOutput(repoInventory: ViewGroup, type: MediaType) { fun setExtensionOutput(repoInventory: ViewGroup, type: MediaType) {
@ -139,7 +138,12 @@ class SettingsExtensionsActivity: AppCompatActivity() {
} }
} }
fun processEditorAction(dialog: AlertDialog, editText: EditText, mediaType: MediaType, view: ViewGroup) { fun processEditorAction(
dialog: AlertDialog,
editText: EditText,
mediaType: MediaType,
view: ViewGroup
) {
editText.setOnEditorActionListener { textView, action, keyEvent -> editText.setOnEditorActionListener { textView, action, keyEvent ->
if (action == EditorInfo.IME_ACTION_SEARCH || action == EditorInfo.IME_ACTION_DONE || (keyEvent?.action == KeyEvent.ACTION_UP && keyEvent.keyCode == KeyEvent.KEYCODE_ENTER)) { if (action == EditorInfo.IME_ACTION_SEARCH || action == EditorInfo.IME_ACTION_DONE || (keyEvent?.action == KeyEvent.ACTION_UP && keyEvent.keyCode == KeyEvent.KEYCODE_ENTER)) {
return@setOnEditorActionListener if (textView.text.isNullOrBlank()) { return@setOnEditorActionListener if (textView.text.isNullOrBlank()) {
@ -178,7 +182,12 @@ class SettingsExtensionsActivity: AppCompatActivity() {
dialog.dismiss() dialog.dismiss()
}.create() }.create()
processEditorAction(alertDialog, editText, MediaType.ANIME, it.attachView) processEditorAction(
alertDialog,
editText,
MediaType.ANIME,
it.attachView
)
alertDialog.show() alertDialog.show()
alertDialog.window?.setDimAmount(0.8f) alertDialog.window?.setDimAmount(0.8f)
}, },
@ -209,7 +218,12 @@ class SettingsExtensionsActivity: AppCompatActivity() {
dialog.dismiss() dialog.dismiss()
}.create() }.create()
processEditorAction(alertDialog, editText, MediaType.MANGA, it.attachView) processEditorAction(
alertDialog,
editText,
MediaType.MANGA,
it.attachView
)
alertDialog.show() alertDialog.show()
alertDialog.window?.setDimAmount(0.8f) alertDialog.window?.setDimAmount(0.8f)
}, },
@ -229,7 +243,10 @@ class SettingsExtensionsActivity: AppCompatActivity() {
val alertDialog = AlertDialog.Builder(context, R.style.MyPopup) val alertDialog = AlertDialog.Builder(context, R.style.MyPopup)
.setTitle(R.string.user_agent).setView(dialogView.root) .setTitle(R.string.user_agent).setView(dialogView.root)
.setPositiveButton(getString(R.string.ok)) { dialog, _ -> .setPositiveButton(getString(R.string.ok)) { dialog, _ ->
PrefManager.setVal(PrefName.DefaultUserAgent, editText.text.toString()) PrefManager.setVal(
PrefName.DefaultUserAgent,
editText.text.toString()
)
dialog.dismiss() dialog.dismiss()
}.setNeutralButton(getString(R.string.reset)) { dialog, _ -> }.setNeutralButton(getString(R.string.reset)) { dialog, _ ->
PrefManager.removeVal(PrefName.DefaultUserAgent) PrefManager.removeVal(PrefName.DefaultUserAgent)

View file

@ -22,7 +22,7 @@ import ani.dantotsu.themes.ThemeManager
import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get import uy.kohesive.injekt.api.get
class SettingsMangaActivity: AppCompatActivity(){ class SettingsMangaActivity : AppCompatActivity() {
private lateinit var binding: ActivitySettingsMangaBinding private lateinit var binding: ActivitySettingsMangaBinding
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
@ -82,7 +82,12 @@ class SettingsMangaActivity: AppCompatActivity(){
onClick = { onClick = {
val dialog = AlertDialog.Builder(context, R.style.MyPopup) val dialog = AlertDialog.Builder(context, R.style.MyPopup)
.setTitle(R.string.purge_manga_downloads) .setTitle(R.string.purge_manga_downloads)
.setMessage(getString(R.string.purge_confirm, getString(R.string.manga))) .setMessage(
getString(
R.string.purge_confirm,
getString(R.string.manga)
)
)
.setPositiveButton(R.string.yes) { dialog, _ -> .setPositiveButton(R.string.yes) { dialog, _ ->
val downloadsManager = Injekt.get<DownloadsManager>() val downloadsManager = Injekt.get<DownloadsManager>()
downloadsManager.purgeDownloads(MediaType.MANGA) downloadsManager.purgeDownloads(MediaType.MANGA)
@ -103,7 +108,12 @@ class SettingsMangaActivity: AppCompatActivity(){
onClick = { onClick = {
val dialog = AlertDialog.Builder(context, R.style.MyPopup) val dialog = AlertDialog.Builder(context, R.style.MyPopup)
.setTitle(R.string.purge_novel_downloads) .setTitle(R.string.purge_novel_downloads)
.setMessage(getString(R.string.purge_confirm, getString(R.string.novels))) .setMessage(
getString(
R.string.purge_confirm,
getString(R.string.novels)
)
)
.setPositiveButton(R.string.yes) { dialog, _ -> .setPositiveButton(R.string.yes) { dialog, _ ->
val downloadsManager = Injekt.get<DownloadsManager>() val downloadsManager = Injekt.get<DownloadsManager>()
downloadsManager.purgeDownloads(MediaType.NOVEL) downloadsManager.purgeDownloads(MediaType.NOVEL)
@ -121,7 +131,7 @@ class SettingsMangaActivity: AppCompatActivity(){
desc = getString(R.string.include_list), desc = getString(R.string.include_list),
icon = R.drawable.view_list_24, icon = R.drawable.view_list_24,
isChecked = PrefManager.getVal(PrefName.IncludeMangaList), isChecked = PrefManager.getVal(PrefName.IncludeMangaList),
switch = {isChecked, _ -> switch = { isChecked, _ ->
PrefManager.setVal(PrefName.IncludeMangaList, isChecked) PrefManager.setVal(PrefName.IncludeMangaList, isChecked)
restartApp() restartApp()
} }

View file

@ -25,7 +25,7 @@ import ani.dantotsu.settings.saving.PrefName
import ani.dantotsu.statusBarHeight import ani.dantotsu.statusBarHeight
import ani.dantotsu.themes.ThemeManager import ani.dantotsu.themes.ThemeManager
class SettingsNotificationActivity: AppCompatActivity(){ class SettingsNotificationActivity : AppCompatActivity() {
private lateinit var binding: ActivitySettingsNotificationsBinding private lateinit var binding: ActivitySettingsNotificationsBinding
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
@ -68,17 +68,27 @@ class SettingsNotificationActivity: AppCompatActivity(){
arrayListOf( arrayListOf(
Settings( Settings(
type = 1, type = 1,
name = getString(R.string.subscriptions_checking_time_s, timeNames[curTime]), name = getString(
R.string.subscriptions_checking_time_s,
timeNames[curTime]
),
desc = getString(R.string.subscriptions_info), desc = getString(R.string.subscriptions_info),
icon = R.drawable.ic_round_notifications_none_24, icon = R.drawable.ic_round_notifications_none_24,
onClick = { onClick = {
val speedDialog = AlertDialog.Builder(context, R.style.MyPopup) val speedDialog = AlertDialog.Builder(context, R.style.MyPopup)
.setTitle(R.string.subscriptions_checking_time) .setTitle(R.string.subscriptions_checking_time)
val dialog = speedDialog.setSingleChoiceItems(timeNames, curTime) { dialog, i -> val dialog =
speedDialog.setSingleChoiceItems(timeNames, curTime) { dialog, i ->
curTime = i curTime = i
it.settingsTitle.text= it.settingsTitle.text =
getString(R.string.subscriptions_checking_time_s, timeNames[i]) getString(
PrefManager.setVal(PrefName.SubscriptionNotificationInterval, curTime) R.string.subscriptions_checking_time_s,
timeNames[i]
)
PrefManager.setVal(
PrefName.SubscriptionNotificationInterval,
curTime
)
dialog.dismiss() dialog.dismiss()
TaskScheduler.create( TaskScheduler.create(
context, PrefManager.getVal(PrefName.UseAlarmManager) context, PrefManager.getVal(PrefName.UseAlarmManager)
@ -100,11 +110,15 @@ class SettingsNotificationActivity: AppCompatActivity(){
onClick = { onClick = {
val types = NotificationType.entries.map { it.name } val types = NotificationType.entries.map { it.name }
val filteredTypes = val filteredTypes =
PrefManager.getVal<Set<String>>(PrefName.AnilistFilteredTypes).toMutableSet() PrefManager.getVal<Set<String>>(PrefName.AnilistFilteredTypes)
.toMutableSet()
val selected = types.map { filteredTypes.contains(it) }.toBooleanArray() val selected = types.map { filteredTypes.contains(it) }.toBooleanArray()
val dialog = AlertDialog.Builder(context, R.style.MyPopup) val dialog = AlertDialog.Builder(context, R.style.MyPopup)
.setTitle(R.string.anilist_notification_filters) .setTitle(R.string.anilist_notification_filters)
.setMultiChoiceItems(types.toTypedArray(), selected) { _, which, isChecked -> .setMultiChoiceItems(
types.toTypedArray(),
selected
) { _, which, isChecked ->
val type = types[which] val type = types[which]
if (isChecked) { if (isChecked) {
filteredTypes.add(type) filteredTypes.add(type)
@ -130,13 +144,20 @@ class SettingsNotificationActivity: AppCompatActivity(){
), ),
icon = R.drawable.ic_round_notifications_none_24, icon = R.drawable.ic_round_notifications_none_24,
onClick = { onClick = {
val selected = PrefManager.getVal<Int>(PrefName.AnilistNotificationInterval) val selected =
PrefManager.getVal<Int>(PrefName.AnilistNotificationInterval)
val dialog = AlertDialog.Builder(context, R.style.MyPopup) val dialog = AlertDialog.Builder(context, R.style.MyPopup)
.setTitle(R.string.subscriptions_checking_time) .setTitle(R.string.subscriptions_checking_time)
.setSingleChoiceItems(aItems.toTypedArray(), selected) { dialog, i -> .setSingleChoiceItems(
aItems.toTypedArray(),
selected
) { dialog, i ->
PrefManager.setVal(PrefName.AnilistNotificationInterval, i) PrefManager.setVal(PrefName.AnilistNotificationInterval, i)
it.settingsTitle.text = it.settingsTitle.text =
getString(R.string.anilist_notifications_checking_time, aItems[i]) getString(
R.string.anilist_notifications_checking_time,
aItems[i]
)
dialog.dismiss() dialog.dismiss()
TaskScheduler.create( TaskScheduler.create(
context, PrefManager.getVal(PrefName.UseAlarmManager) context, PrefManager.getVal(PrefName.UseAlarmManager)
@ -158,13 +179,20 @@ class SettingsNotificationActivity: AppCompatActivity(){
), ),
icon = R.drawable.ic_round_notifications_none_24, icon = R.drawable.ic_round_notifications_none_24,
onClick = { onClick = {
val selected = PrefManager.getVal<Int>(PrefName.CommentNotificationInterval) val selected =
PrefManager.getVal<Int>(PrefName.CommentNotificationInterval)
val dialog = AlertDialog.Builder(context, R.style.MyPopup) val dialog = AlertDialog.Builder(context, R.style.MyPopup)
.setTitle(R.string.subscriptions_checking_time) .setTitle(R.string.subscriptions_checking_time)
.setSingleChoiceItems(cItems.toTypedArray(), selected) { dialog, i -> .setSingleChoiceItems(
cItems.toTypedArray(),
selected
) { dialog, i ->
PrefManager.setVal(PrefName.CommentNotificationInterval, i) PrefManager.setVal(PrefName.CommentNotificationInterval, i)
it.settingsTitle.text = it.settingsTitle.text =
getString(R.string.comment_notification_checking_time, cItems[i]) getString(
R.string.comment_notification_checking_time,
cItems[i]
)
dialog.dismiss() dialog.dismiss()
TaskScheduler.create( TaskScheduler.create(
context, PrefManager.getVal(PrefName.UseAlarmManager) context, PrefManager.getVal(PrefName.UseAlarmManager)
@ -181,7 +209,10 @@ class SettingsNotificationActivity: AppCompatActivity(){
icon = R.drawable.ic_round_smart_button_24, icon = R.drawable.ic_round_smart_button_24,
isChecked = PrefManager.getVal(PrefName.SubscriptionCheckingNotifications), isChecked = PrefManager.getVal(PrefName.SubscriptionCheckingNotifications),
switch = { isChecked, _ -> switch = { isChecked, _ ->
PrefManager.setVal(PrefName.SubscriptionCheckingNotifications, isChecked) PrefManager.setVal(
PrefName.SubscriptionCheckingNotifications,
isChecked
)
}, },
onLongClick = { onLongClick = {
openSettings(context, null) openSettings(context, null)
@ -193,7 +224,7 @@ class SettingsNotificationActivity: AppCompatActivity(){
desc = getString(R.string.use_alarm_manager_reliable), desc = getString(R.string.use_alarm_manager_reliable),
icon = R.drawable.ic_anilist, icon = R.drawable.ic_anilist,
isChecked = PrefManager.getVal(PrefName.UseAlarmManager), isChecked = PrefManager.getVal(PrefName.UseAlarmManager),
switch = {isChecked, view -> switch = { isChecked, view ->
if (isChecked) { if (isChecked) {
val alertDialog = AlertDialog.Builder(context, R.style.MyPopup) val alertDialog = AlertDialog.Builder(context, R.style.MyPopup)
.setTitle(R.string.use_alarm_manager) .setTitle(R.string.use_alarm_manager)

View file

@ -164,14 +164,17 @@ class SettingsThemeActivity : AppCompatActivity(), SimpleDialog.OnDialogResultLi
icon = R.drawable.ic_palette, icon = R.drawable.ic_palette,
onClick = { onClick = {
val originalColor: Int = PrefManager.getVal(PrefName.CustomThemeInt) val originalColor: Int = PrefManager.getVal(PrefName.CustomThemeInt)
class CustomColorDialog : SimpleColorDialog() { class CustomColorDialog : SimpleColorDialog() {
override fun onPositiveButtonClick() { override fun onPositiveButtonClick() {
reload() reload()
super.onPositiveButtonClick() super.onPositiveButtonClick()
} }
} }
val tag = "colorPicker" val tag = "colorPicker"
CustomColorDialog().title(R.string.custom_theme).colorPreset(originalColor) CustomColorDialog().title(R.string.custom_theme)
.colorPreset(originalColor)
.colors(context, SimpleColorDialog.MATERIAL_COLOR_PALLET) .colors(context, SimpleColorDialog.MATERIAL_COLOR_PALLET)
.allowCustom(true).showOutline(0x46000000).gridNumColumn(5) .allowCustom(true).showOutline(0x46000000).gridNumColumn(5)
.choiceMode(SimpleColorDialog.SINGLE_CHOICE).neg() .choiceMode(SimpleColorDialog.SINGLE_CHOICE).neg()
@ -198,7 +201,8 @@ class SettingsThemeActivity : AppCompatActivity(), SimpleDialog.OnDialogResultLi
} }
return true return true
} }
fun reload(){
fun reload() {
PrefManager.setCustomVal("reload", true) PrefManager.setCustomVal("reload", true)
restartApp() restartApp()
} }

View file

@ -102,7 +102,7 @@ enum class PrefName(val data: Pref) { //TODO: Split this into multiple files
UseProxyForTimeStamps(Pref(Location.Player, Boolean::class, false)), UseProxyForTimeStamps(Pref(Location.Player, Boolean::class, false)),
ShowTimeStampButton(Pref(Location.Player, Boolean::class, true)), ShowTimeStampButton(Pref(Location.Player, Boolean::class, true)),
AutoSkipOPED(Pref(Location.Player, Boolean::class, false)), AutoSkipOPED(Pref(Location.Player, Boolean::class, false)),
AutoSkipRecap(Pref(Location.Player, Boolean::class, false )), AutoSkipRecap(Pref(Location.Player, Boolean::class, false)),
AutoPlay(Pref(Location.Player, Boolean::class, true)), AutoPlay(Pref(Location.Player, Boolean::class, true)),
AutoSkipFiller(Pref(Location.Player, Boolean::class, false)), AutoSkipFiller(Pref(Location.Player, Boolean::class, false)),
AskIndividualPlayer(Pref(Location.Player, Boolean::class, true)), AskIndividualPlayer(Pref(Location.Player, Boolean::class, true)),

View file

@ -82,6 +82,7 @@ class SharedPreferenceStringSetLiveData(
fun SharedPreferences.intLiveData(key: String, defValue: Int): SharedPreferenceLiveData<Int> { fun SharedPreferences.intLiveData(key: String, defValue: Int): SharedPreferenceLiveData<Int> {
return SharedPreferenceIntLiveData(this, key, defValue) return SharedPreferenceIntLiveData(this, key, defValue)
} }
@Suppress("unused") @Suppress("unused")
fun SharedPreferences.stringLiveData( fun SharedPreferences.stringLiveData(

View file

@ -1,6 +1,5 @@
package ani.dantotsu.widgets.statistics package ani.dantotsu.widgets.statistics
import android.app.Activity
import android.appwidget.AppWidgetManager import android.appwidget.AppWidgetManager
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
@ -12,9 +11,7 @@ import android.view.View
import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatActivity
import ani.dantotsu.R import ani.dantotsu.R
import ani.dantotsu.databinding.StatisticsWidgetConfigureBinding import ani.dantotsu.databinding.StatisticsWidgetConfigureBinding
import ani.dantotsu.themes.ThemeManager import ani.dantotsu.themes.ThemeManager
import ani.dantotsu.widgets.upcoming.UpcomingWidget
import com.google.android.material.button.MaterialButton import com.google.android.material.button.MaterialButton
import eltos.simpledialogfragment.SimpleDialog import eltos.simpledialogfragment.SimpleDialog
import eltos.simpledialogfragment.color.SimpleColorDialog import eltos.simpledialogfragment.color.SimpleColorDialog
@ -64,9 +61,12 @@ class ProfileStatsConfigure : AppCompatActivity(),
AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID AppWidgetManager.INVALID_APPWIDGET_ID
) )
val prefs = getSharedPreferences(ProfileStatsWidget.getPrefsName(appWidgetId), Context.MODE_PRIVATE) val prefs =
val topBackground = prefs.getInt(ProfileStatsWidget.PREF_BACKGROUND_COLOR, Color.parseColor("#80000000")) getSharedPreferences(ProfileStatsWidget.getPrefsName(appWidgetId), Context.MODE_PRIVATE)
(binding.topBackgroundButton as MaterialButton).iconTint = ColorStateList.valueOf(topBackground) val topBackground =
prefs.getInt(ProfileStatsWidget.PREF_BACKGROUND_COLOR, Color.parseColor("#80000000"))
(binding.topBackgroundButton as MaterialButton).iconTint =
ColorStateList.valueOf(topBackground)
binding.topBackgroundButton.setOnClickListener { binding.topBackgroundButton.setOnClickListener {
val tag = ProfileStatsWidget.PREF_BACKGROUND_COLOR val tag = ProfileStatsWidget.PREF_BACKGROUND_COLOR
SimpleColorDialog().title(R.string.custom_theme) SimpleColorDialog().title(R.string.custom_theme)
@ -83,8 +83,10 @@ class ProfileStatsConfigure : AppCompatActivity(),
.neg() .neg()
.show(this@ProfileStatsConfigure, tag) .show(this@ProfileStatsConfigure, tag)
} }
val bottomBackground = prefs.getInt(ProfileStatsWidget.PREF_BACKGROUND_FADE, Color.parseColor("#00000000")) val bottomBackground =
(binding.bottomBackgroundButton as MaterialButton).iconTint = ColorStateList.valueOf(bottomBackground) prefs.getInt(ProfileStatsWidget.PREF_BACKGROUND_FADE, Color.parseColor("#00000000"))
(binding.bottomBackgroundButton as MaterialButton).iconTint =
ColorStateList.valueOf(bottomBackground)
binding.bottomBackgroundButton.setOnClickListener { binding.bottomBackgroundButton.setOnClickListener {
val tag = ProfileStatsWidget.PREF_BACKGROUND_FADE val tag = ProfileStatsWidget.PREF_BACKGROUND_FADE
SimpleColorDialog().title(R.string.custom_theme) SimpleColorDialog().title(R.string.custom_theme)
@ -196,7 +198,10 @@ class ProfileStatsConfigure : AppCompatActivity(),
) )
val subTextColor = typedValueOutline.data val subTextColor = typedValueOutline.data
getSharedPreferences(ProfileStatsWidget.getPrefsName(appWidgetId), Context.MODE_PRIVATE).edit().apply { getSharedPreferences(
ProfileStatsWidget.getPrefsName(appWidgetId),
Context.MODE_PRIVATE
).edit().apply {
putInt(ProfileStatsWidget.PREF_BACKGROUND_COLOR, backgroundColor) putInt(ProfileStatsWidget.PREF_BACKGROUND_COLOR, backgroundColor)
putInt(ProfileStatsWidget.PREF_BACKGROUND_FADE, backgroundColor) putInt(ProfileStatsWidget.PREF_BACKGROUND_FADE, backgroundColor)
putInt(ProfileStatsWidget.PREF_TITLE_TEXT_COLOR, textColor) putInt(ProfileStatsWidget.PREF_TITLE_TEXT_COLOR, textColor)

View file

@ -41,13 +41,17 @@ class LocalAnimeSource(
override suspend fun getLatestUpdates(page: Int) = getSearchAnime(page, "", LATEST_FILTERS) override suspend fun getLatestUpdates(page: Int) = getSearchAnime(page, "", LATEST_FILTERS)
@Deprecated("Use the non-RxJava API instead", replaceWith = ReplaceWith("getPopularAnime")) @Deprecated("Use the non-RxJava API instead", replaceWith = ReplaceWith("getPopularAnime"))
override fun fetchPopularAnime(page: Int) = getSearchAnime override fun fetchPopularAnime(page: Int) = fetchSearchAnime(page, "", POPULAR_FILTERS)
@Deprecated("Use the non-RxJava API instead", replaceWith = ReplaceWith("getLatestUpdates")) @Deprecated("Use the non-RxJava API instead", replaceWith = ReplaceWith("getLatestUpdates"))
override fun fetchLatestUpdates(page: Int) = getSearchAnime override fun fetchLatestUpdates(page: Int) = fetchSearchAnime(page, "", LATEST_FILTERS)
@Deprecated("Use the non-RxJava API instead", replaceWith = ReplaceWith("getSearchAnime")) @Deprecated("Use the non-RxJava API instead", replaceWith = ReplaceWith("getSearchAnime"))
override fun fetchSearchAnime(page: Int, query: String, filters: AnimeFilterList): Observable<AnimesPage> { override fun fetchSearchAnime(
page: Int,
query: String,
filters: AnimeFilterList
): Observable<AnimesPage> {
return runBlocking { return runBlocking {
Observable.just(getSearchAnime(page, query, filters)) Observable.just(getSearchAnime(page, query, filters))
} }