Bimba.git

ref: 68ae37f62658ef2b5dfe364bfa283d03b4f35951

app/src/main/java/xyz/apiote/bimba/czwek/settings/feeds/FeedSettings.kt


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// SPDX-FileCopyrightText: Adam Evyčędo
//
// SPDX-License-Identifier: GPL-3.0-or-later

package xyz.apiote.bimba.czwek.settings.feeds

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.edit
import com.github.jershell.kbson.KBson
import kotlinx.serialization.Serializable
import xyz.apiote.bimba.czwek.api.Server
import java.net.URLEncoder

@Serializable
@OptIn(ExperimentalStdlibApi::class)
data class FeedsSettings(val settings: MutableMap<String, FeedSettings>) {
	fun activeFeeds() = settings.count { it.value.enabled && it.value.useOnline }
	fun getIDs() = settings.filter { it.value.enabled && it.value.useOnline }.keys.joinToString(",")

	fun save(context: Context, server: Server) {
		val doc = KBson().dump(serializer(), this).toHexString()
		val feedsPreferences =
			context.getSharedPreferences("feeds_settings", AppCompatActivity.MODE_PRIVATE)
		feedsPreferences.edit {
			val key = URLEncoder.encode(server.apiPath, "utf-8")
			putString(key, doc)
		}
	}

	companion object {
		fun load(context: Context, apiPath: String = Server.get(context).apiPath): FeedsSettings {
			val doc = context.getSharedPreferences(
				"feeds_settings",
				Context.MODE_PRIVATE
			).getString(URLEncoder.encode(apiPath, "utf-8"), null)
			return doc?.let { KBson().load(serializer(), doc.hexToByteArray()) } ?: FeedsSettings(
				mutableMapOf()
			)
		}
	}
}

@Serializable
data class FeedSettings(
	val enabled: Boolean,
	val useOnline: Boolean
)

fun migrateFeedsSettings(context: Context, server: Server = Server.get(context)) {
	val shp =
		context.getSharedPreferences(
			URLEncoder.encode(server.apiPath, "utf-8"),
			AppCompatActivity.MODE_PRIVATE
		)
	if (shp.all.isEmpty()) {
		return
	}

	val feedsSettings = FeedsSettings(mutableMapOf())
	shp.all.forEach { (feedID, enabled) ->
		if (enabled as Boolean) {
			feedsSettings.settings[feedID] = FeedSettings(enabled = true, useOnline = true)
		}
	}
	shp.edit {
		clear()
	}
	feedsSettings.save(context, server)
}