Created
June 1, 2020 16:08
-
-
Save Apsaliya/bdfbf2413d8862470b2b73995247e6ca to your computer and use it in GitHub Desktop.
Restore from stream
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
suspend fun restoreFromInputStream(context: Context, | |
contentStream: InputStream): Boolean { | |
return withContext(Dispatchers.IO) { | |
var result = false | |
var toBeRestoredZipFile: File? = null | |
var extractedFilesDir: File? = null | |
try { | |
val dbFile = context.getDatabasePath("dbName.db") | |
val parentDbFile = dbFile.parentFile | |
val dataDir = requireNotNull(context.filesDir.parentFile) | |
toBeRestoredZipFile = File(dataDir.absolutePath + "/toBeRestored.zip") //zip file that is going to be restored | |
extractedFilesDir = File(dataDir.absolutePath + "/toBeRestoredDir") // directory used to temporary extract all files | |
extractedFilesDir.mkdir() | |
IOUtils.copy(contentStream, toBeRestoredZipFile.outputStream()) //Copy stream into temporary file | |
val preparedZipFile = | |
ZipFile(toBeRestoredZipFile.absolutePath, getFinalZipPass("password").toCharArray()) | |
preparedZipFile.extractAll(extractedFilesDir.absolutePath) // extract all the files inside the zip file | |
//delete existing data directories. these will be replaced with the ones in zip file | |
val sharedPrefDirePath = dataDir.absolutePath + "/shared_prefs" | |
val sharedPrefDir = File(sharedPrefDirePath) | |
sharedPrefDir.deleteRecursively() | |
parentDbFile?.listFiles() | |
?.forEach { | |
it.deleteRecursively() | |
} | |
context.filesDir.listFiles()?.forEach { | |
it.deleteRecursively() | |
} | |
// copy all the files that were extracted from zip and place them under `data` directory | |
if (extractedFilesDir.exists()) { | |
val toBeRestoredFolders = extractedFilesDir.listFiles() | |
toBeRestoredFolders?.forEach { | |
val contentFolderInData = File(dataDir.absolutePath + "/" + it.name) | |
if (!contentFolderInData.exists()) { | |
contentFolderInData.mkdir() | |
} | |
it.copyRecursively(contentFolderInData) | |
} | |
result = true | |
} | |
} catch (e: ZipException) { | |
if (e.type == ZipException.Type.WRONG_PASSWORD) { | |
// Provided password is wrong for the zip hence it can not be extracted | |
//throw IncorrectPasswordException("Invalid password", e) | |
} | |
throw e | |
} finally { | |
if (extractedFilesDir?.exists() == true) { | |
extractedFilesDir.deleteRecursively() // delete directory used to extract all files | |
} | |
if (toBeRestoredZipFile?.exists() == true) { | |
toBeRestoredZipFile.delete() // delete actual .zip file that was restored | |
} | |
} | |
return@withContext result | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment