package xyz.pixelatedw.recipe.utils import android.content.Context import android.os.Handler import android.os.Looper import androidx.documentfile.provider.DocumentFile import androidx.navigation.NavHostController import xyz.pixelatedw.recipe.MainActivity import java.io.DataInputStream import java.io.File import java.io.FileOutputStream import java.net.InetSocketAddress import java.net.Socket import java.net.SocketTimeoutException import java.nio.ByteBuffer import java.nio.charset.StandardCharsets import java.util.concurrent.Executors const val DEFAULT_SYNC_SERVER_IP = "192.168.0.100" const val DEFAULT_SYNC_SERVER_PORT = 9696 const val CONNECTION_TIMEOUT = 1_000 // 1 seconds fun sync(ctx: MainActivity, nav: NavHostController) { val executor = Executors.newSingleThreadExecutor() val handler = Handler(Looper.getMainLooper()) executor.execute { try { val prefs = ctx.getPreferences(Context.MODE_PRIVATE) val syncServerIp = prefs.getString("syncServerIp", DEFAULT_SYNC_SERVER_IP) val syncServerPort = prefs.getInt("syncServerPort", DEFAULT_SYNC_SERVER_PORT) val conn = Socket() conn.connect(InetSocketAddress(syncServerIp, syncServerPort), CONNECTION_TIMEOUT) val stream = conn.getInputStream() val inputStream = DataInputStream(stream) var buffer = ByteArray(8) inputStream.read(buffer) val filesSent = ByteBuffer.wrap(buffer).getLong().toInt() for (f in 0.. 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) { ctx.importError = when (e) { is SocketTimeoutException -> "Connection timed out" else -> "Error occurred: ${e.javaClass.canonicalName}" } e.printStackTrace() } handler.post { if (ctx.importError.isEmpty()) { val recipes = ctx.db.recipeWithTagsDao().getAll() ctx.recipeView.setRecipes(recipes) nav.navigate("list") // println("syncing complete") } else { println(ctx.importError) } } } }