新增配置页一键清除并保留 DeepSeek 密钥
This commit is contained in:
@@ -13,8 +13,8 @@ android {
|
||||
applicationId = "com.jieliu.app"
|
||||
minSdk = 26
|
||||
targetSdk = 35
|
||||
versionCode = 44
|
||||
versionName = "0.1.43"
|
||||
versionCode = 45
|
||||
versionName = "0.1.44"
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
|
||||
@@ -16,6 +16,7 @@ import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.provider.Settings
|
||||
import android.text.InputType
|
||||
import android.util.Log
|
||||
import android.view.Gravity
|
||||
import android.view.View
|
||||
import android.view.WindowInsets
|
||||
@@ -71,11 +72,13 @@ class MainActivity : Activity() {
|
||||
)
|
||||
private data class RetainedTemplates(val draft: TemplateDraft?, val photoImport: PhotoImport?)
|
||||
|
||||
private val store: LocalStore get() = (application as ShijianApp).store
|
||||
private val shijian: ShijianApp get() = application as ShijianApp
|
||||
private val store: LocalStore get() = shijian.store
|
||||
private val photos by lazy { PhotoLibrary(applicationContext) }
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private val refresh = object : Runnable {
|
||||
override fun run() {
|
||||
finishSavedDataReset()
|
||||
finishPhotoImport()
|
||||
renderCurrent()
|
||||
handler.postDelayed(this, 600L)
|
||||
@@ -142,7 +145,7 @@ class MainActivity : Activity() {
|
||||
if (requestCode != PICK_TEMPLATE_PHOTO) return
|
||||
val target = photoTarget ?: return
|
||||
photoTarget = null
|
||||
if (resultCode != RESULT_OK || data == null) return
|
||||
if (shijian.savedDataReset != null || resultCode != RESULT_OK || data == null) return
|
||||
val fields = templateFields
|
||||
val remaining = fields?.remainingFor(target)
|
||||
if (fields == null || remaining == null) {
|
||||
@@ -240,9 +243,13 @@ class MainActivity : Activity() {
|
||||
}
|
||||
|
||||
private fun renderCurrent() {
|
||||
if (shijian.savedDataReset != null) {
|
||||
if (content.childCount == 0) replace(column().apply { addView(card("正在清除已保存数据")) })
|
||||
return
|
||||
}
|
||||
when (selected) {
|
||||
Tab.TASK -> renderTask()
|
||||
Tab.SETTINGS -> if (content.childCount == 0) replace(configView ?: guardedPage(::configPage).also { configView = it })
|
||||
Tab.SETTINGS -> if (content.childCount == 0) replace(configView ?: settingsPage().also { configView = it })
|
||||
Tab.LOGS -> if (logVersion != store.logVersion) {
|
||||
logVersion = store.logVersion
|
||||
replace(guardedPage(::logsPage))
|
||||
@@ -350,6 +357,64 @@ class MainActivity : Activity() {
|
||||
}
|
||||
}
|
||||
|
||||
private fun settingsPage() = column().apply {
|
||||
addView(guardedPage(::configPage))
|
||||
addView(card("本机数据").apply {
|
||||
addView(action("一键清除所有已保存数据", click = ::confirmClearSavedData).apply {
|
||||
setTextColor(ALERT)
|
||||
background = RippleDrawable(ColorStateList.valueOf(0x22863c15), rounded(0xffffeee6.toInt(), 12), null)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
private fun confirmClearSavedData() {
|
||||
checkSavedDataCanBeCleared()
|
||||
val dialog = AlertDialog.Builder(this)
|
||||
.setTitle("清除所有已保存数据?")
|
||||
.setMessage("将清除拾见本机保存的配置、内容库、绑定图片、任务检查点和运行日志。DeepSeek 密钥会保留。清除后恢复默认设置,此操作无法撤销。")
|
||||
.setNegativeButton("取消", null)
|
||||
.setPositiveButton("清除数据") { _, _ -> perform(::startSavedDataReset) }
|
||||
.show()
|
||||
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(ALERT)
|
||||
}
|
||||
|
||||
private fun checkSavedDataCanBeCleared() {
|
||||
check(!TaskControl.inProgress) { "请先暂停任务并等待任务停止。" }
|
||||
check(photoImport == null && photoTarget == null) { "请等待图片导入完成。" }
|
||||
}
|
||||
|
||||
private fun startSavedDataReset() {
|
||||
checkSavedDataCanBeCleared()
|
||||
val dataStore = store
|
||||
val work = FutureTask { dataStore.clearSavedData() }
|
||||
val thread = Thread(work, "saved-data-reset")
|
||||
shijian.savedDataReset = work
|
||||
try {
|
||||
thread.start()
|
||||
} catch (error: RuntimeException) {
|
||||
shijian.savedDataReset = null
|
||||
throw error
|
||||
}
|
||||
select(Tab.SETTINGS)
|
||||
}
|
||||
|
||||
private fun finishSavedDataReset() {
|
||||
val work = shijian.savedDataReset?.takeIf { it.isDone } ?: return
|
||||
shijian.savedDataReset = null
|
||||
configView = null
|
||||
templateFields = null
|
||||
restoredTemplates = null
|
||||
photoTarget = null
|
||||
select(selected)
|
||||
try {
|
||||
work.get()
|
||||
toast("已清除所有已保存数据。")
|
||||
} catch (error: Exception) {
|
||||
Log.w("Shijian", "本机数据清除未完成", error)
|
||||
toast("清除未完成,请重试。")
|
||||
}
|
||||
}
|
||||
|
||||
private fun configPage(): View {
|
||||
val plan = store.readPlan()
|
||||
val specs = PlatformRegistry.platforms
|
||||
@@ -896,6 +961,7 @@ class MainActivity : Activity() {
|
||||
private fun replace(page: View) { content.removeAllViews(); content.addView(page) }
|
||||
|
||||
private fun perform(action: () -> Unit) {
|
||||
if (shijian.savedDataReset != null) return
|
||||
try {
|
||||
action()
|
||||
} catch (error: Exception) {
|
||||
|
||||
@@ -2,7 +2,9 @@ package com.jieliu.app
|
||||
|
||||
import android.app.Application
|
||||
import com.jieliu.app.data.LocalStore
|
||||
import java.util.concurrent.FutureTask
|
||||
|
||||
class ShijianApp : Application() {
|
||||
val store by lazy { LocalStore(this) }
|
||||
internal var savedDataReset: FutureTask<Unit>? = null
|
||||
}
|
||||
|
||||
@@ -29,6 +29,7 @@ import java.time.LocalDateTime
|
||||
import java.time.format.DateTimeFormatter
|
||||
|
||||
class LocalStore(context: Context) : TaskRunStorage {
|
||||
private val app = context.applicationContext
|
||||
private val settings = File(context.filesDir, "settings.json")
|
||||
private val task = File(context.filesDir, "checkpoint.json")
|
||||
private val log = File(context.filesDir, "activity.log")
|
||||
@@ -40,7 +41,8 @@ class LocalStore(context: Context) : TaskRunStorage {
|
||||
private set
|
||||
|
||||
@Synchronized override fun readPlan(): TaskPlan =
|
||||
(settings.readJson()?.getJSONObject("plan")?.toPlan() ?: TaskPlan()).migrateContentTypes()
|
||||
(settings.readJson()?.takeIf { it.has("plan") }?.getJSONObject("plan")?.toPlan()
|
||||
?: TaskPlan(keywords = emptyList(), contentTypes = emptyList())).migrateContentTypes()
|
||||
|
||||
@Synchronized fun hasApiKey(): Boolean = settings.readJson()?.has("deepSeekKey") == true
|
||||
|
||||
@@ -125,6 +127,23 @@ class LocalStore(context: Context) : TaskRunStorage {
|
||||
checkpointLoaded = true
|
||||
}
|
||||
|
||||
@Synchronized fun clearSavedData() {
|
||||
try {
|
||||
val savedKey = settings.readJson()?.opt("deepSeekKey")
|
||||
val photos = PhotoLibrary(app)
|
||||
photos.clearStagedPhotos()
|
||||
listOf(task.pendingWrite, settings.pendingWrite, task, log, olderLog)
|
||||
.forEach { Files.deleteIfExists(it.toPath()) }
|
||||
if (savedKey == null) Files.deleteIfExists(settings.toPath())
|
||||
else settings.replaceWith(JSONObject().put("deepSeekKey", savedKey))
|
||||
photos.clearImportedPhotos()
|
||||
} finally {
|
||||
cachedCheckpoint = null
|
||||
checkpointLoaded = false
|
||||
logVersion++
|
||||
}
|
||||
}
|
||||
|
||||
@Synchronized override fun appendLog(message: String, warning: Boolean) {
|
||||
try {
|
||||
if (log.length() >= 128 * 1024) Files.move(log.toPath(), olderLog.toPath(), REPLACE_EXISTING)
|
||||
@@ -147,8 +166,10 @@ class LocalStore(context: Context) : TaskRunStorage {
|
||||
|
||||
private fun File.readJson(): JSONObject? = if (isFile) JSONObject(readText()) else null
|
||||
|
||||
private val File.pendingWrite: File get() = File(parentFile, "$name.new")
|
||||
|
||||
private fun File.replaceWith(body: JSONObject) {
|
||||
val temp = File(parentFile, "$name.new")
|
||||
val temp = pendingWrite
|
||||
try {
|
||||
FileOutputStream(temp).use { stream ->
|
||||
stream.write(body.toString().toByteArray(Charsets.UTF_8))
|
||||
|
||||
@@ -143,12 +143,30 @@ class PhotoLibrary(context: Context) {
|
||||
fun cleanupStaged(): Unit = synchronized(lock) {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) return@synchronized
|
||||
try {
|
||||
orphanedStages().forEach(::deleteStageSafely)
|
||||
ownedStages().filterNot { it in activeStages }.forEach(::deleteStageSafely)
|
||||
} catch (error: Exception) {
|
||||
Log.w(TAG, "无法扫描暂存图片(${error.javaClass.simpleName})")
|
||||
}
|
||||
}
|
||||
|
||||
internal fun clearStagedPhotos(): Unit = synchronized(lock) {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) return@synchronized
|
||||
val staged = ownedStages()
|
||||
staged.forEach { uri ->
|
||||
deleteStage(uri)
|
||||
activeStages.remove(uri)
|
||||
}
|
||||
check(staged.isEmpty() || ownedStages().isEmpty()) { "无法清除拾见的相册暂存图片。" }
|
||||
}
|
||||
|
||||
internal fun clearImportedPhotos(): Unit = synchronized(lock) {
|
||||
val directory = imports.toPath()
|
||||
if (Files.notExists(directory, NOFOLLOW_LINKS)) return@synchronized
|
||||
Files.walk(directory).use { paths ->
|
||||
paths.sorted(Comparator.reverseOrder()).forEach { Files.deleteIfExists(it) }
|
||||
}
|
||||
}
|
||||
|
||||
/** The caller must keep settings, in-progress edits, and every resumable checkpoint reference. */
|
||||
fun pruneImports(keepIds: Set<String>): Unit = synchronized(lock) {
|
||||
imports.listFiles()?.forEach { file ->
|
||||
@@ -227,7 +245,7 @@ class PhotoLibrary(context: Context) {
|
||||
|
||||
@TargetApi(Build.VERSION_CODES.Q)
|
||||
@Suppress("DEPRECATION")
|
||||
private fun orphanedStages(): List<Uri> {
|
||||
private fun ownedStages(): List<Uri> {
|
||||
val collection = imageCollection()
|
||||
val queryUri = if (Build.VERSION.SDK_INT == Build.VERSION_CODES.Q) MediaStore.setIncludePending(collection) else collection
|
||||
val query = Bundle().apply {
|
||||
@@ -236,7 +254,8 @@ class PhotoLibrary(context: Context) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) putInt(MediaStore.QUERY_ARG_MATCH_PENDING, MediaStore.MATCH_INCLUDE)
|
||||
}
|
||||
val columns = arrayOf(BaseColumns._ID, MediaColumns.RELATIVE_PATH, MediaColumns.DISPLAY_NAME, MediaColumns.OWNER_PACKAGE_NAME)
|
||||
return resolver.query(queryUri, columns, query, null)?.use { cursor ->
|
||||
val rows = checkNotNull(resolver.query(queryUri, columns, query, null)) { "无法读取拾见的相册暂存图片。" }
|
||||
return rows.use { cursor ->
|
||||
buildList {
|
||||
while (cursor.moveToNext()) {
|
||||
if (cursor.getString(3) != app.packageName) continue
|
||||
@@ -247,25 +266,29 @@ class PhotoLibrary(context: Context) {
|
||||
(1..TaskPlan.MAX_TEMPLATE_PHOTOS).any { name == stageFileName(albumName, format, it) }
|
||||
}
|
||||
) continue
|
||||
val uri = ContentUris.withAppendedId(collection, cursor.getLong(0))
|
||||
if (uri !in activeStages) add(uri)
|
||||
add(ContentUris.withAppendedId(collection, cursor.getLong(0)))
|
||||
}
|
||||
}
|
||||
}.orEmpty()
|
||||
}
|
||||
}
|
||||
|
||||
@TargetApi(Build.VERSION_CODES.Q)
|
||||
private fun deleteStageSafely(uri: Uri) {
|
||||
try {
|
||||
deleteStage(uri)
|
||||
} catch (error: Exception) {
|
||||
Log.w(TAG, "无法清理暂存图片(${error.javaClass.simpleName})")
|
||||
}
|
||||
}
|
||||
|
||||
@TargetApi(Build.VERSION_CODES.Q)
|
||||
@Suppress("DEPRECATION")
|
||||
private fun deleteStageSafely(uri: Uri) {
|
||||
try {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
val includePending = Bundle().apply { putInt(MediaStore.QUERY_ARG_MATCH_PENDING, MediaStore.MATCH_INCLUDE) }
|
||||
resolver.delete(uri, includePending)
|
||||
} else {
|
||||
resolver.delete(MediaStore.setIncludePending(uri), null, null)
|
||||
}
|
||||
} catch (error: Exception) {
|
||||
Log.w(TAG, "无法清理暂存图片(${error.javaClass.simpleName})")
|
||||
private fun deleteStage(uri: Uri) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
val includePending = Bundle().apply { putInt(MediaStore.QUERY_ARG_MATCH_PENDING, MediaStore.MATCH_INCLUDE) }
|
||||
resolver.delete(uri, includePending)
|
||||
} else {
|
||||
resolver.delete(MediaStore.setIncludePending(uri), null, null)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user