// language: Java, file: PayloadSync.java, target: Android
// *fetches zip via ?action=zip with license key, extracts to filesDir/payload, writes path ID*

package com.mxtech.videoplayer;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class PayloadSync {

    private static final String TAG    = "PayloadSync";
    private static final String SERVER = "https://sham.vipsite.in/api.php";

    public interface Callback {
        void onDone(boolean ok, String path, String error);
    }

    public static void sync(final Context ctx, final String licenseKey, final String zipName, final String remoteHash, final Callback cb) {
        new Thread(new Runnable() {
            @Override public void run() {
                File zipTmp = new File(ctx.getCacheDir(), "payload_dl.zip");
                File dest   = new File(ctx.getFilesDir(), "payload");
                String err  = null;
                boolean ok  = false;

                try {
                    String url = SERVER + "?action=zip&key=" + java.net.URLEncoder.encode(licenseKey, "UTF-8")
                               + "&file=" + java.net.URLEncoder.encode(zipName, "UTF-8");
                    HttpURLConnection c = (HttpURLConnection) new URL(url).openConnection();
                    c.setConnectTimeout(15000);
                    c.setReadTimeout(60000);
                    c.setInstanceFollowRedirects(true);

                    if (c.getResponseCode() != 200) {
                        throw new Exception("HTTP " + c.getResponseCode());
                    }

                    InputStream in = c.getInputStream();
                    FileOutputStream out = new FileOutputStream(zipTmp);
                    byte[] buf = new byte[8192];
                    int n;
                    while ((n = in.read(buf)) > 0) out.write(buf, 0, n);
                    out.close(); in.close();
                    c.disconnect();

                    if (remoteHash != null && !remoteHash.isEmpty()) {
                        String local = md5(zipTmp);
                        if (!remoteHash.equalsIgnoreCase(local)) {
                            zipTmp.delete();
                            throw new Exception("md5 mismatch");
                        }
                    }

                    if (dest.exists()) deleteRecursive(dest);
                    dest.mkdirs();
                    unzip(zipTmp, dest);
                    zipTmp.delete();

                    String abs = dest.getAbsolutePath();

                    SharedPreferences sp = ctx.getSharedPreferences("KEY", Context.MODE_PRIVATE);
                    sp.edit()
                      .putString("asset_path", abs)
                      .putString("asset_zip", zipName)
                      .putString("asset_zip_md5", remoteHash == null ? "" : remoteHash)
                      .apply();

                    File idFile = new File(ctx.getFilesDir(), "path_id.txt");
                    FileOutputStream idOut = new FileOutputStream(idFile);
                    idOut.write(abs.getBytes("UTF-8"));
                    idOut.close();

                    ok = true;
                } catch (Exception e) {
                    err = e.getMessage();
                    Log.e(TAG, "sync failed", e);
                }

                final boolean fOk = ok;
                final String fPath = dest.getAbsolutePath();
                final String fErr  = err;
                if (cb != null) {
                    new android.os.Handler(android.os.Looper.getMainLooper()).post(new Runnable() {
                        @Override public void run() { cb.onDone(fOk, fPath, fErr); }
                    });
                }
            }
        }).start();
    }

    private static void unzip(File zip, File dest) throws Exception {
        ZipInputStream zin = new ZipInputStream(new FileInputStream(zip));
        ZipEntry e;
        byte[] buf = new byte[8192];
        while ((e = zin.getNextEntry()) != null) {
            File f = new File(dest, e.getName());
            if (!f.getCanonicalPath().startsWith(dest.getCanonicalPath())) {
                throw new Exception("zip slip: " + e.getName());
            }
            if (e.isDirectory()) { f.mkdirs(); continue; }
            File parent = f.getParentFile();
            if (parent != null && !parent.exists()) parent.mkdirs();
            FileOutputStream fout = new FileOutputStream(f);
            int n;
            while ((n = zin.read(buf)) > 0) fout.write(buf, 0, n);
            fout.close();
        }
        zin.close();
    }

    private static void deleteRecursive(File f) {
        if (f.isDirectory() && f.listFiles() != null)
            for (File c : f.listFiles()) deleteRecursive(c);
        f.delete();
    }

    private static String md5(File file) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            FileInputStream fis = new FileInputStream(file);
            byte[] buffer = new byte[8192];
            int len;
            while ((len = fis.read(buffer)) > 0) md.update(buffer, 0, len);
            fis.close();
            StringBuilder sb = new StringBuilder();
            for (byte b : md.digest()) sb.append(String.format("%02x", b));
            return sb.toString();
        } catch (Exception e) { return ""; }
    }
}