Skip to content

Commit

Permalink
[fix] Fix a bug that appContext has not been initialized (#23)
Browse files Browse the repository at this point in the history
  • Loading branch information
SkyD666 committed Apr 13, 2024
1 parent 27e75b8 commit b505bc0
Show file tree
Hide file tree
Showing 10 changed files with 61 additions and 38 deletions.
2 changes: 1 addition & 1 deletion app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ android {
minSdk = 24
targetSdk = 34
versionCode = 63
versionName = "2.2-beta03"
versionName = "2.2-beta04"

testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables {
Expand Down
24 changes: 18 additions & 6 deletions app/src/main/java/com/skyd/rays/config/StickerConfig.kt
Original file line number Diff line number Diff line change
@@ -1,12 +1,24 @@
package com.skyd.rays.config

import com.skyd.rays.appContext
import android.content.Context
import java.io.File

val STICKER_DIR: String = File(appContext.filesDir.path, "Sticker").path
// https://github.com/SkyD666/Rays-Android/issues/23
val Context.STICKER_DIR: String
get() = File(filesDir.path, "Sticker")
.apply { if (!exists()) mkdirs() }
.path

val TEMP_STICKER_DIR: File = File(appContext.cacheDir, "TempSticker")
val PROVIDER_THUMBNAIL_DIR: File = File(TEMP_STICKER_DIR, "Provider/Thumbnail")
val Context.TEMP_STICKER_DIR: File
get() = File(cacheDir, "TempSticker")
.apply { if (!exists()) mkdirs() }
val Context.PROVIDER_THUMBNAIL_DIR: File
get() = File(TEMP_STICKER_DIR, "Provider/Thumbnail")
.apply { if (!exists()) mkdirs() }

val IMPORT_FILES_DIR: File = File(appContext.cacheDir, "ImportFiles")
val EXPORT_FILES_DIR: File = File(appContext.cacheDir, "ExportFiles")
val Context.IMPORT_FILES_DIR: File
get() = File(cacheDir, "ImportFiles")
.apply { if (!exists()) mkdirs() }
val Context.EXPORT_FILES_DIR: File
get() = File(cacheDir, "ExportFiles")
.apply { if (!exists()) mkdirs() }
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ sealed interface HandleImportedStickerStrategy : Parcelable {
}

fun moveFile(stickerFile: File) {
val destStickerFile = File(STICKER_DIR, stickerFile.name)
val destStickerFile = File(appContext.STICKER_DIR, stickerFile.name)
stickerFile.copyTo(target = destStickerFile, overwrite = true)
stickerFile.deleteRecursively()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ interface StickerDao {
appContext, scope, CurrentStickerUuidPreference.default
)
}
File(STICKER_DIR, stickerUuid).deleteRecursively()
File(appContext.STICKER_DIR, stickerUuid).deleteRecursively()
}
// 设置了外键,ForeignKey.CASCADE,因此会自动deleteTags
return innerDeleteStickers(stickerUuids)
Expand All @@ -226,7 +226,7 @@ interface StickerDao {
fun deleteAllStickerWithTags() {
val scope = CoroutineScope(Dispatchers.IO)
CurrentStickerUuidPreference.put(appContext, scope, CurrentStickerUuidPreference.default)
File(STICKER_DIR).deleteRecursively()
File(appContext.STICKER_DIR).deleteRecursively()
// 设置了外键,ForeignKey.CASCADE,因此会自动deleteTags
innerDeleteAllStickers()
}
Expand Down
37 changes: 23 additions & 14 deletions app/src/main/java/com/skyd/rays/model/provider/StickerProvider.kt
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ class StickerProvider : DocumentsProvider() {
add(Root.COLUMN_TITLE, context!!.getString(R.string.app_name))

// This document id cannot change after it's shared.
add(Root.COLUMN_DOCUMENT_ID, STICKER_DIR)
add(Root.COLUMN_DOCUMENT_ID, context!!.STICKER_DIR)

// The child MIME types are used to filter the roots and only present to the
// user those roots that contain the desired type somewhere in their file hierarchy.
Expand All @@ -92,15 +92,24 @@ class StickerProvider : DocumentsProvider() {
override fun queryDocument(documentId: String, projection: Array<out String>?): Cursor {
// Create a cursor with the requested projection, or the default projection.
return MatrixCursor(projection ?: DEFAULT_DOCUMENT_COLUMNS).apply {
val uuids = listOf(File(documentId).name)
val modifiedMap = getModifiedMap(uuids)
includeFile(
this,
path = documentId,
lastModified = modifiedMap[uuids.first()],
displayMap = getDisplayMap(uuids),
mimeTypeMap = getMimeTypeMap(uuids),
)
if (documentId == context!!.STICKER_DIR) {
includeFile(
this,
path = documentId,
displayMap = mapOf(),
mimeTypeMap = mutableMapOf(),
)
} else {
val uuids = listOf(File(documentId).name)
val modifiedMap = getModifiedMap(uuids)
includeFile(
this,
path = documentId,
lastModified = modifiedMap[uuids.first()],
displayMap = getDisplayMap(uuids),
mimeTypeMap = getMimeTypeMap(uuids),
)
}
}
}

Expand All @@ -110,7 +119,7 @@ class StickerProvider : DocumentsProvider() {
sortOrder: String?
): Cursor {
return MatrixCursor(projection ?: DEFAULT_DOCUMENT_COLUMNS).apply {
val parent = File(parentDocumentId ?: STICKER_DIR)
val parent = File(parentDocumentId ?: context!!.STICKER_DIR)
val listFiles = parent.listFiles().orEmpty()
val stickerUuids = listFiles.map { it.name }
val modifiedMap = getModifiedMap(stickerUuids)
Expand Down Expand Up @@ -229,7 +238,7 @@ class StickerProvider : DocumentsProvider() {
): AssetFileDescriptor {
val stickerFile = File(documentId)
// TODO: delete thumbFile
val thumbFile = File(PROVIDER_THUMBNAIL_DIR, stickerFile.name)
val thumbFile = File(context!!.PROVIDER_THUMBNAIL_DIR, stickerFile.name)
if (!thumbFile.exists()) {
thumbFile.parentFile?.mkdirs()
thumbFile.createNewFile()
Expand Down Expand Up @@ -286,7 +295,7 @@ class StickerProvider : DocumentsProvider() {
val stickers = entryPoint.stickerDao().getRecentModifiedStickers()
.associateBy { it.sticker.uuid }
val listFiles = stickers.values
.map { File(STICKER_DIR, it.sticker.uuid) }
.map { File(context!!.STICKER_DIR, it.sticker.uuid) }
.filter { it.exists() }
.toTypedArray()
val stickerUuids = listFiles.map { it.name }
Expand Down Expand Up @@ -314,7 +323,7 @@ class StickerProvider : DocumentsProvider() {
val stickers = entryPoint.searchRepo().requestStickerWithTagsList(query.orEmpty())
.associateBy { it.sticker.uuid }
val listFiles = stickers.values
.map { File(STICKER_DIR, it.sticker.uuid) }
.map { File(context!!.STICKER_DIR, it.sticker.uuid) }
.filter { it.exists() }
.toTypedArray()
val stickerUuids = listFiles.map { it.name }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ class AddRepository @Inject constructor(
}
}

val tempFile = File(STICKER_DIR, "${Random.nextLong()}")
val tempFile = File(appContext.STICKER_DIR, "${Random.nextLong()}")
uri.copyTo(tempFile)
val stickerMd5 = tempFile.md5() ?: error("can not calc sticker's md5!")
val uuidGotByMd5 = stickerDao.containsByMd5(stickerMd5)
Expand All @@ -68,7 +68,7 @@ class AddRepository @Inject constructor(
} else {
stickerWithTags.sticker.stickerMd5 = stickerMd5
val uuid = stickerDao.addStickerWithTags(stickerWithTags)
if (!tempFile.renameTo(File(STICKER_DIR, uuid))) {
if (!tempFile.renameTo(File(appContext.STICKER_DIR, uuid))) {
tempFile.deleteRecursively()
}
ImageFormatChecker.saveMimeType(format = imageFormat, stickerUuid = uuid)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.skyd.rays.model.respository

import com.skyd.rays.appContext
import com.skyd.rays.base.BaseRepository
import com.skyd.rays.config.PROVIDER_THUMBNAIL_DIR
import com.skyd.rays.model.db.dao.cache.StickerShareTimeDao
Expand All @@ -26,7 +27,7 @@ class DataRepository @Inject constructor(

suspend fun requestDeleteDocumentsProviderThumbnails(): Flow<Long> {
return flowOnIo {
emit(measureTimeMillis { PROVIDER_THUMBNAIL_DIR.deleteRecursively() })
emit(measureTimeMillis { appContext.PROVIDER_THUMBNAIL_DIR.deleteRecursively() })
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ class ImportExportFilesRepository @Inject constructor(
val startTime = System.currentTimeMillis()

// 清空导入所需的临时目录
IMPORT_FILES_DIR.deleteRecursively()
appContext.IMPORT_FILES_DIR.deleteRecursively()

// 检查文件最后四个字节是不是 0x0D000721
appContext.contentResolver.openFileDescriptor(backupFileUri, "r").use { descriptor ->
Expand All @@ -70,7 +70,7 @@ class ImportExportFilesRepository @Inject constructor(
unzip(
context = appContext,
zipFile = backupFileUri,
location = IMPORT_FILES_DIR,
location = appContext.IMPORT_FILES_DIR,
onEach = { index, file ->
emitProgressData(
current = index,
Expand All @@ -85,7 +85,7 @@ class ImportExportFilesRepository @Inject constructor(
emitProgressData(
msg = appContext.getString(R.string.import_files_screen_progress_checking_backup_format),
)
val stickerWithTagsAndFileList = checkBackupUnzipFiles(IMPORT_FILES_DIR)
val stickerWithTagsAndFileList = checkBackupUnzipFiles(appContext.IMPORT_FILES_DIR)

// 移动表情包文件并保存信息到数据库
emitProgressData(
Expand Down Expand Up @@ -124,15 +124,15 @@ class ImportExportFilesRepository @Inject constructor(
}
val totalCount = allStickerWithTagsList.size
var currentCount = 0
EXPORT_FILES_DIR.deleteRecursively()
appContext.EXPORT_FILES_DIR.deleteRecursively()
allStickerWithTagsList.forEach {
if (excludeClickCount) it.sticker.clickCount = 0L
if (excludeShareCount) it.sticker.shareCount = 0L
if (excludeCreateTime) it.sticker.createTime = 0L
if (excludeModifyTime) it.sticker.modifyTime = 0L
stickerWithTagsToJsonFile(it)
stickerUuidToFile(it.sticker.uuid)
.copyTo(File("$EXPORT_FILES_DIR/$BACKUP_STICKER_DIR", it.sticker.uuid))
.copyTo(File("${appContext.EXPORT_FILES_DIR}/$BACKUP_STICKER_DIR", it.sticker.uuid))
emitProgressData(
current = ++currentCount,
total = totalCount,
Expand All @@ -149,7 +149,7 @@ class ImportExportFilesRepository @Inject constructor(
zip(
context = appContext,
zipFile = zipFileUri,
files = EXPORT_FILES_DIR.listFiles().orEmpty().toList(),
files = appContext.EXPORT_FILES_DIR.listFiles().orEmpty().toList(),
onEach = { index, file ->
emitProgressData(
current = index,
Expand Down Expand Up @@ -180,7 +180,7 @@ class ImportExportFilesRepository @Inject constructor(
}

private fun stickerWithTagsToJsonFile(stickerWithTags: StickerWithTags): File {
val file = File("$EXPORT_FILES_DIR/$BACKUP_DATA_DIR", stickerWithTags.sticker.uuid)
val file = File("${appContext.EXPORT_FILES_DIR}/$BACKUP_DATA_DIR", stickerWithTags.sticker.uuid)
if (!file.exists()) {
if (file.parentFile?.exists() == false) {
file.parentFile?.mkdirs()
Expand Down
3 changes: 2 additions & 1 deletion app/src/main/java/com/skyd/rays/ui/component/RaysImage.kt
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,8 @@ fun RaysImage(
imageLoader: ImageLoader = rememberRaysImageLoader(),
contentScale: ContentScale = ContentScale.FillWidth,
) {
val file = remember(uuid) { File(STICKER_DIR, uuid) }
val context = LocalContext.current
val file = remember(uuid) { File(context.STICKER_DIR, uuid) }
RaysImage(
model = file,
blur = blur,
Expand Down
6 changes: 3 additions & 3 deletions app/src/main/java/com/skyd/rays/util/StickerUtil.kt
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ private fun File.deleteDirs(
}
}

fun Bitmap.shareToFile(outputDir: File = TEMP_STICKER_DIR): File {
fun Bitmap.shareToFile(outputDir: File = appContext.TEMP_STICKER_DIR): File {
if (!outputDir.exists()) {
outputDir.mkdirs()
}
Expand All @@ -182,7 +182,7 @@ fun Bitmap.shareToFile(outputDir: File = TEMP_STICKER_DIR): File {
* 把表情包复制到临时目录
*/
fun File.copyStickerToTempFolder(fileExtension: Boolean = true): File {
val outputDir = TEMP_STICKER_DIR
val outputDir = appContext.TEMP_STICKER_DIR
check(outputDir.exists() || outputDir.mkdirs())
val resultFileName = name + "_" + Random.nextInt(0, Int.MAX_VALUE) + if (fileExtension) {
inputStream().use { ImageFormatChecker.check(it, name).toString() }
Expand Down Expand Up @@ -212,7 +212,7 @@ fun externalShareStickerUuidToFile(uuid: String): File = stickerUuidToFile(uuid)
/**
* 针对内部操作,针对原图片本身
*/
fun stickerUuidToFile(uuid: String): File = File(STICKER_DIR, uuid)
fun stickerUuidToFile(uuid: String): File = File(appContext.STICKER_DIR, uuid)

fun externalShareStickerUuidToUri(uuid: String): Uri =
Uri.fromFile(externalShareStickerUuidToFile(uuid))
Expand Down

0 comments on commit b505bc0

Please sign in to comment.