summaryrefslogtreecommitdiffstats
path: root/src/android/app/src/main/java/org/yuzu/yuzu_emu/fragments/ImportExportSavesFragment.kt
blob: 7a990d0cc87cec71b3e2e12037ea8a2e15c51225 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
// SPDX-FileCopyrightText: 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

package org.yuzu.yuzu_emu.fragments

import android.app.Dialog
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.DocumentsContract
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.documentfile.provider.DocumentFile
import androidx.fragment.app.DialogFragment
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.yuzu.yuzu_emu.R
import org.yuzu.yuzu_emu.YuzuApplication
import org.yuzu.yuzu_emu.features.DocumentProvider
import org.yuzu.yuzu_emu.getPublicFilesDir
import java.io.BufferedInputStream
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.FilenameFilter
import java.io.IOException
import java.io.InputStream
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.zip.ZipEntry
import java.util.zip.ZipInputStream
import java.util.zip.ZipOutputStream

class ImportExportSavesFragment : DialogFragment() {
    private val context = YuzuApplication.appContext
    private val savesFolder =
        "${context.getPublicFilesDir().canonicalPath}/nand/user/save/0000000000000000"

    // Get first subfolder in saves folder (should be the user folder)
    private val savesFolderRoot = File(savesFolder).listFiles()?.firstOrNull()?.canonicalPath ?: ""
    private var lastZipCreated: File? = null

    private lateinit var startForResultExportSave: ActivityResultLauncher<Intent>
    private lateinit var documentPicker: ActivityResultLauncher<Array<String>>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val activityResultRegistry = requireActivity().activityResultRegistry
        startForResultExportSave = activityResultRegistry.register(
            "startForResultExportSaveKey",
            ActivityResultContracts.StartActivityForResult()
        ) {
            File(context.getPublicFilesDir().canonicalPath, "temp").deleteRecursively()
        }
        documentPicker = activityResultRegistry.register(
            "documentPickerKey",
            ActivityResultContracts.OpenDocument()
        ) {
            it?.let { uri -> importSave(uri) }
        }
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        return if (savesFolderRoot == "") {
            MaterialAlertDialogBuilder(requireContext())
                .setTitle(R.string.manage_save_data)
                .setMessage(R.string.import_export_saves_no_profile)
                .setPositiveButton(android.R.string.ok, null)
                .show()
        } else {
            MaterialAlertDialogBuilder(requireContext())
                .setTitle(R.string.manage_save_data)
                .setMessage(R.string.manage_save_data_description)
                .setNegativeButton(R.string.export_saves) { _, _ ->
                    exportSave()
                }
                .setPositiveButton(R.string.import_saves) { _, _ ->
                    documentPicker.launch(arrayOf("application/zip"))
                }
                .setNeutralButton(android.R.string.cancel, null)
                .show()
        }
    }

    /**
     * Zips the save files located in the given folder path and creates a new zip file with the current date and time.
     * @return true if the zip file is successfully created, false otherwise.
     */
    private fun zipSave(): Boolean {
        try {
            val tempFolder = File(requireContext().getPublicFilesDir().canonicalPath, "temp")
            tempFolder.mkdirs()
            val saveFolder = File(savesFolderRoot)
            val outputZipFile = File(
                tempFolder,
                "yuzu saves - ${
                    LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"))
                }.zip"
            )
            outputZipFile.createNewFile()
            ZipOutputStream(BufferedOutputStream(FileOutputStream(outputZipFile))).use { zos ->
                saveFolder.walkTopDown().forEach { file ->
                    val zipFileName =
                        file.absolutePath.removePrefix(savesFolderRoot).removePrefix("/")
                    if (zipFileName == "")
                        return@forEach
                    val entry = ZipEntry("$zipFileName${(if (file.isDirectory) "/" else "")}")
                    zos.putNextEntry(entry)
                    if (file.isFile)
                        file.inputStream().use { fis -> fis.copyTo(zos) }
                }
            }
            lastZipCreated = outputZipFile
        } catch (e: Exception) {
            return false
        }
        return true
    }

    /**
     * Extracts the save files located in the given zip file and copies them to the saves folder.
     * @exception IOException if the file was being created outside of the target directory
     */
    private fun unzip(zipStream: InputStream, destDir: File): Boolean {
        val zis = ZipInputStream(BufferedInputStream(zipStream))
        var entry: ZipEntry? = zis.nextEntry
        while (entry != null) {
            val entryName = entry.name
            val entryFile = File(destDir, entryName)
            if (!entryFile.canonicalPath.startsWith(destDir.canonicalPath + File.separator)) {
                zis.close()
                throw IOException("Entry is outside of the target dir: " + entryFile.name)
            }
            if (entry.isDirectory) {
                entryFile.mkdirs()
            } else {
                entryFile.parentFile?.mkdirs()
                entryFile.createNewFile()
                entryFile.outputStream().use { fos -> zis.copyTo(fos) }
            }
            entry = zis.nextEntry
        }
        zis.close()
        return true
    }

    /**
     * Exports the save file located in the given folder path by creating a zip file and sharing it via intent.
     */
    private fun exportSave() {
        CoroutineScope(Dispatchers.IO).launch {
            val wasZipCreated = zipSave()
            val lastZipFile = lastZipCreated
            if (!wasZipCreated || lastZipFile == null) {
                withContext(Dispatchers.Main) {
                    Toast.makeText(context, "Failed to export save", Toast.LENGTH_LONG).show()
                }
                return@launch
            }

            withContext(Dispatchers.Main) {
                val file = DocumentFile.fromSingleUri(
                    context, DocumentsContract.buildDocumentUri(
                        DocumentProvider.AUTHORITY,
                        "${DocumentProvider.ROOT_ID}/temp/${lastZipFile.name}"
                    )
                )!!
                val intent = Intent(Intent.ACTION_SEND)
                    .setDataAndType(file.uri, "application/zip")
                    .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                    .putExtra(Intent.EXTRA_STREAM, file.uri)
                startForResultExportSave.launch(Intent.createChooser(intent, "Share save file"))
            }
        }
    }

    /**
     * Imports the save files contained in the zip file, and replaces any existing ones with the new save file.
     * @param zipUri The Uri of the zip file containing the save file(s) to import.
     */
    private fun importSave(zipUri: Uri) {
        val inputZip = context.contentResolver.openInputStream(zipUri)
        // A zip needs to have at least one subfolder named after a TitleId in order to be considered valid.
        var validZip = false
        val savesFolder = File(savesFolderRoot)
        val cacheSaveDir = File("${context.cacheDir.path}/saves/")
        cacheSaveDir.mkdir()

        if (inputZip == null) {
            Toast.makeText(context, context.getString(R.string.fatal_error), Toast.LENGTH_LONG)
                .show()
            return
        }

        val filterTitleId =
            FilenameFilter { _, dirName -> dirName.matches(Regex("^0100[\\dA-Fa-f]{12}$")) }

        try {
            CoroutineScope(Dispatchers.IO).launch {
                unzip(inputZip, cacheSaveDir)
                cacheSaveDir.list(filterTitleId)?.forEach { savePath ->
                    File(savesFolder, savePath).deleteRecursively()
                    File(cacheSaveDir, savePath).copyRecursively(File(savesFolder, savePath), true)
                    validZip = true
                }

                withContext(Dispatchers.Main) {
                    if (!validZip) {
                        MessageDialogFragment.newInstance(
                            R.string.save_file_invalid_zip_structure,
                            R.string.save_file_invalid_zip_structure_description
                        ).show(childFragmentManager, MessageDialogFragment.TAG)
                        return@withContext
                    }
                    Toast.makeText(
                        context,
                        context.getString(R.string.save_file_imported_success),
                        Toast.LENGTH_LONG
                    ).show()
                }

                cacheSaveDir.deleteRecursively()
            }
        } catch (e: Exception) {
            Toast.makeText(context, context.getString(R.string.fatal_error), Toast.LENGTH_LONG)
                .show()
        }
    }

    companion object {
        const val TAG = "ImportExportSavesFragment"
    }
}