2020-02-03 04:04:11 +01:00
package eu.kanade.tachiyomi.util.storage
2017-01-20 21:18:15 +01:00
import android.content.Context
import android.net.Uri
2023-11-05 00:36:25 +01:00
import android.os.Build
2020-01-05 17:29:27 +01:00
import androidx.core.content.FileProvider
2023-11-05 00:36:25 +01:00
import androidx.core.net.toUri
2017-01-20 21:18:15 +01:00
import eu.kanade.tachiyomi.BuildConfig
import java.io.File
2022-03-19 21:46:23 +01:00
val Context . cacheImageDir : File
get ( ) = File ( cacheDir , " shared_image " )
2021-06-02 00:36:06 +02:00
2017-01-20 21:18:15 +01:00
/ * *
* Returns the uri of a file
*
* @param context context of application
* /
fun File . getUriCompat ( context : Context ) : Uri {
2023-11-05 00:36:25 +01:00
return if ( Build . VERSION . SDK _INT >= Build . VERSION_CODES . N ) {
FileProvider . getUriForFile ( context , BuildConfig . APPLICATION _ID + " .provider " , this )
} else {
this . toUri ( )
}
2017-01-20 21:18:15 +01:00
}
2023-10-13 05:04:40 +02:00
/ * *
* Copies this file to the given [ target ] file while marking the file as read - only .
*
* @see File . copyTo
* /
fun File . copyAndSetReadOnlyTo ( target : File , overwrite : Boolean = false , bufferSize : Int = DEFAULT _BUFFER _SIZE ) : File {
if ( ! this . exists ( ) ) {
throw NoSuchFileException ( file = this , reason = " The source file doesn't exist. " )
}
if ( target . exists ( ) ) {
if ( ! overwrite ) {
2023-11-05 04:28:41 +01:00
throw FileAlreadyExistsException (
file = this ,
other = target ,
reason = " The destination file already exists. " ,
)
2023-10-13 05:04:40 +02:00
} else if ( ! target . delete ( ) ) {
2023-11-05 04:28:41 +01:00
throw FileAlreadyExistsException (
file = this ,
other = target ,
reason = " Tried to overwrite the destination, but failed to delete it. " ,
)
2023-10-13 05:04:40 +02:00
}
}
if ( this . isDirectory ) {
if ( ! target . mkdirs ( ) ) {
throw FileSystemException ( file = this , other = target , reason = " Failed to create target directory. " )
}
} else {
target . parentFile ?. mkdirs ( )
this . inputStream ( ) . use { input ->
target . outputStream ( ) . use { output ->
// Set read-only
target . setReadOnly ( )
input . copyTo ( output , bufferSize )
}
}
}
return target
}