package moe.yuuta.workmode.suspend.data import android.content.Context import android.content.SharedPreferences import com.crashlytics.android.Crashlytics import com.crashlytics.android.answers.Answers import com.crashlytics.android.answers.CustomEvent import com.elvishew.xlog.XLog import moe.yuuta.workmode.Setup import moe.yuuta.workmode.utils.Utils import java.util.stream.Collectors /** * An independent storage of suspended status */ class SuspendedStorage(mContext: Context) { private val logger = XLog.tag("Storage").build() companion object { private lateinit var instance: SuspendedStorage fun get(context: Context): SuspendedStorage { if (!::instance.isInitialized) { instance = SuspendedStorage(context) } return instance } } private val storage: SharedPreferences = mContext.getSharedPreferences("suspended", Context.MODE_PRIVATE) fun getStorage(): SharedPreferences = storage fun getList(): List = (getStorage().getStringSet("list", setOf()) ?: listOf()).toList() fun setList(set: Set) { logger.d("s() $set") getStorage().edit().putStringSet("list", set).apply() } fun setStatus(status: Status) { getStorage().edit().putInt("status", when (status) { Status.OFF -> 0 Status.ON -> 1 }).apply() } fun getStatus(): Status = when (getStorage().getInt("status", 0)) { 0 -> Status.OFF 1 -> Status.ON else -> Status.OFF } fun setListMode(listMode: ListMode) { getStorage().edit().putInt("list_mode", when (listMode) { ListMode.BLACKLIST -> 0 ListMode.WHITELIST -> 1 }).apply() } fun getListMode(): ListMode = when (getStorage().getInt("list_mode", 0)) { 0 -> ListMode.BLACKLIST 1 -> ListMode.WHITELIST else -> ListMode.BLACKLIST } fun cleanList(context: Context) { val installed = context.packageManager.getInstalledApplications(0) .stream() .filter(Utils.buildGeneralApplicationInfoFilter(context)) .map { return@map it.packageName } .collect(Collectors.toList()) setList(getList().stream() .filter { return@filter installed.contains(it) } .collect(Collectors.toSet())) } // #Anti-Crack fun reportCrack(id: String, reason: String) { if (getList().isEmpty()) { // Only report when user had set at least one app. logger.d("Skipping for registering...") return } val reportTimes = getStorage().getInt("c_$id", 0) getStorage().edit() .putInt("c_$id", reportTimes + 1) .apply() if (reportTimes <= 0) { Runnable { Runnable { if (Setup.FABRIC_ENABLE) Runnable { Answers.getInstance().logCustom(CustomEvent("St.rf.pa.") .putCustomAttribute("rn", reason) .putCustomAttribute("ic", id)) Crashlytics.log("Sf. $reason $id") }.run() }.run() }.run() } } // #Anti-Crack fun removeCrack(id: String) { getStorage().edit() .remove("c_$id") .apply() if (Setup.FABRIC_ENABLE) Runnable { Answers.getInstance().logCustom(CustomEvent("St.rf.rm.") .putCustomAttribute("ic", id)) Crashlytics.log("Sf.rm. $id") }.run() } }