97 lines
2.6 KiB
Kotlin
97 lines
2.6 KiB
Kotlin
package xyz.pixelatedw.recipe.utils
|
|
|
|
import android.os.Build
|
|
import android.os.FileUtils
|
|
import android.os.Handler
|
|
import android.os.Looper
|
|
import androidx.annotation.RequiresApi
|
|
import androidx.documentfile.provider.DocumentFile
|
|
import xyz.pixelatedw.recipe.MainActivity
|
|
import java.io.BufferedOutputStream
|
|
import java.io.DataInputStream
|
|
import java.io.File
|
|
import java.io.FileOutputStream
|
|
import java.net.Socket
|
|
import java.nio.ByteBuffer
|
|
import java.nio.charset.StandardCharsets
|
|
import java.util.concurrent.Executors
|
|
|
|
|
|
fun sync(ctx: MainActivity) {
|
|
val executor = Executors.newSingleThreadExecutor()
|
|
val handler = Handler(Looper.getMainLooper())
|
|
|
|
executor.execute(Runnable() {
|
|
try {
|
|
val conn = Socket("192.168.0.100", 9696)
|
|
val stream = conn.getInputStream()
|
|
|
|
val inputStream = DataInputStream(stream)
|
|
|
|
var buffer = ByteArray(8)
|
|
inputStream.read(buffer)
|
|
val filesSent = ByteBuffer.wrap(buffer).getLong().toInt()
|
|
// println("files sent: $filesSent")
|
|
|
|
for(f in 0..<filesSent) {
|
|
buffer = ByteArray(8)
|
|
inputStream.read(buffer)
|
|
val nameBufLen = ByteBuffer.wrap(buffer).getLong().toInt()
|
|
|
|
buffer = ByteArray(nameBufLen)
|
|
inputStream.read(buffer)
|
|
val fileFullPath = StandardCharsets.UTF_8.decode(ByteBuffer.wrap(buffer)).toString();
|
|
val fileName = fileFullPath.split("/").last()
|
|
val filePath = fileFullPath.replace(fileName, "")
|
|
|
|
buffer = ByteArray(8)
|
|
inputStream.read(buffer)
|
|
val contentBufLen = ByteBuffer.wrap(buffer).getLong().toInt()
|
|
|
|
var parentDir = ctx.filesDir
|
|
if (filePath.isNotEmpty()) {
|
|
parentDir = File(ctx.filesDir, filePath)
|
|
parentDir.mkdirs()
|
|
}
|
|
|
|
val newFile = File(parentDir, fileName)
|
|
|
|
val fos = FileOutputStream(newFile, false)
|
|
var usedBytes = 0
|
|
var blockSize = 1024
|
|
while (usedBytes != contentBufLen) {
|
|
if (usedBytes + blockSize > contentBufLen) {
|
|
blockSize = contentBufLen - usedBytes
|
|
}
|
|
else if (blockSize > contentBufLen) {
|
|
blockSize = contentBufLen
|
|
}
|
|
|
|
val contentBuffer = ByteArray(blockSize)
|
|
val readBytes = inputStream.read(contentBuffer)
|
|
|
|
fos.write(contentBuffer, 0, readBytes)
|
|
fos.flush()
|
|
usedBytes += readBytes
|
|
}
|
|
fos.close()
|
|
|
|
// println("new file: ${newFile.absolutePath} | $contentBufLen | ${newFile.length()}")
|
|
}
|
|
|
|
val docDir = DocumentFile.fromFile(ctx.filesDir)
|
|
parseDir(ctx, docDir, "")
|
|
parseRecipeFiles(ctx)
|
|
|
|
} catch (e: Exception) {
|
|
e.printStackTrace()
|
|
}
|
|
|
|
handler.post(Runnable {
|
|
val recipes = ctx.db.recipeWithTagsDao().getAll()
|
|
ctx.recipeView.setRecipes(recipes)
|
|
println("syncing complete")
|
|
})
|
|
})
|
|
}
|