package xyz.stream.api.database;

import a4.s;
import android.net.Uri;
import androidx.media3.exoplayer.rtsp.RtspHeaders;
import androidx.room.w0;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import xyz.stream.api.database.entity.IptvEntity;
import xyz.stream.api.database.entity.ServerEntity;

/* JADX INFO: loaded from: classes3.dex */
public final class f {

    /* JADX INFO: renamed from: f, reason: collision with root package name */
    public static volatile f f35806f;

    /* JADX INFO: renamed from: g, reason: collision with root package name */
    public static final Pattern f35807g = Pattern.compile("^(([A-Za-z0-9-]+\\.)+[A-Za-z]{2,}|localhost|[A-Za-z0-9-]+(?=:\\d)|\\d{1,3}(\\.\\d{1,3}){3})(:\\d+)?([/?#].*)?$|^\\[[0-9A-Fa-f:]+\\](:\\d+)?([/?#].*)?$");

    /* JADX INFO: renamed from: a, reason: collision with root package name */
    public AppDatabase f35808a;

    /* JADX INFO: renamed from: c, reason: collision with root package name */
    public int f35810c = 0;

    /* JADX INFO: renamed from: d, reason: collision with root package name */
    public int f35811d = 0;

    /* JADX INFO: renamed from: e, reason: collision with root package name */
    public int f35812e = 0;

    /* JADX INFO: renamed from: b, reason: collision with root package name */
    public final ExecutorService f35809b = Executors.newFixedThreadPool(5);

    public static String a(String str, HashMap map) {
        if (map.isEmpty()) {
            return str;
        }
        StringBuilder sb = new StringBuilder(str);
        sb.append(str.contains("|") ? "&" : "|");
        boolean z10 = !str.contains("|") || str.endsWith("|");
        for (Map.Entry entry : map.entrySet()) {
            if (!z10) {
                sb.append("&");
            }
            sb.append(Uri.encode((String) entry.getKey()));
            sb.append("=");
            sb.append(Uri.encode((String) entry.getValue()));
            z10 = false;
        }
        return sb.toString();
    }

    public static String b(String str, String str2, String str3) {
        if (!f(str) || !f(str2) || !f(str3)) {
            return str;
        }
        try {
            Uri uri = Uri.parse(str);
            Uri.Builder builderClearQuery = uri.buildUpon().clearQuery();
            for (String str4 : uri.getQueryParameterNames()) {
                if (!str2.equalsIgnoreCase(str4)) {
                    builderClearQuery.appendQueryParameter(str4, uri.getQueryParameter(str4));
                }
            }
            builderClearQuery.appendQueryParameter(str2, str3);
            return builderClearQuery.build().toString();
        } catch (Exception unused) {
            return str;
        }
    }

    public static int c(int i10, List list, HashMap map) {
        String strTrim;
        int iIndexOf;
        while (i10 < list.size()) {
            String strTrim2 = ((String) list.get(i10)).trim();
            if (!strTrim2.isEmpty()) {
                if (strTrim2.startsWith("#EXTINF:")) {
                    return -1;
                }
                if (strTrim2.startsWith("#EXTVLCOPT:")) {
                    if (map != null && (iIndexOf = (strTrim = strTrim2.substring(11).trim()).indexOf(61)) > 0) {
                        String lowerCase = strTrim.substring(0, iIndexOf).trim().toLowerCase(Locale.US);
                        String strTrim3 = strTrim.substring(iIndexOf + 1).trim();
                        if (!strTrim3.isEmpty()) {
                            if ("http-referrer".equals(lowerCase) || "http-referer".equals(lowerCase)) {
                                map.put("Referer", strTrim3);
                            } else if ("http-user-agent".equals(lowerCase)) {
                                map.put(RtspHeaders.USER_AGENT, strTrim3);
                            } else if ("http-cookie".equals(lowerCase)) {
                                map.put("Cookie", strTrim3);
                            }
                        }
                    }
                } else if (!strTrim2.startsWith("#")) {
                    return i10;
                }
            }
            i10++;
        }
        return -1;
    }

    public static f d() {
        if (f35806f == null) {
            synchronized (f.class) {
                try {
                    if (f35806f == null) {
                        f35806f = new f();
                    }
                } finally {
                }
            }
        }
        return f35806f;
    }

    public static boolean f(String str) {
        return (str == null || str.trim().isEmpty()) ? false : true;
    }

    public static boolean h(String str) {
        if (str == null) {
            return false;
        }
        String lowerCase = str.toLowerCase(Locale.US);
        return lowerCase.startsWith("file://") || lowerCase.startsWith("content://") || lowerCase.startsWith("storage://") || str.startsWith("/");
    }

    public static String i(String str) {
        if (str == null) {
            return null;
        }
        String strTrim = str.trim();
        if (strTrim.isEmpty()) {
            return null;
        }
        if (h(strTrim)) {
            return strTrim;
        }
        for (int i10 = 0; i10 < strTrim.length(); i10++) {
            if (Character.isWhitespace(strTrim.charAt(i10))) {
                return null;
            }
        }
        if (strTrim.toLowerCase(Locale.US).matches("^[a-z][a-z0-9+.-]*://.*")) {
            return strTrim;
        }
        if (f35807g.matcher(strTrim).matches()) {
            return "http://".concat(strTrim);
        }
        return null;
    }

    public static void k(String str, String str2, HashMap map) {
        if (f(str) && f(str2)) {
            map.put(str.trim(), str2.trim());
        }
    }

    public final List e() {
        try {
            return (List) this.f35809b.submit(new s(this, 3)).get();
        } catch (Exception e10) {
            u.a.g(e10, new StringBuilder("getServerList error: "));
            return null;
        }
    }

    public final int g(ServerEntity serverEntity) {
        try {
            return ((Integer) this.f35809b.submit(new androidx.media3.datasource.c(this, serverEntity, 3)).get()).intValue();
        } catch (Exception e10) {
            u.a.g(e10, new StringBuilder("insertOrUpdateServer error: "));
            return -1;
        }
    }

    /* JADX WARN: Multi-variable type inference failed */
    /* JADX WARN: Removed duplicated region for block: B:127:0x02e3  */
    /* JADX WARN: Removed duplicated region for block: B:258:? A[RETURN, SYNTHETIC] */
    /* JADX WARN: Removed duplicated region for block: B:58:0x014c  */
    /* JADX WARN: Type inference failed for: r0v37, types: [l3.h, l3.j] */
    /* JADX WARN: Type inference failed for: r0v39, types: [l3.h, l3.j] */
    /* JADX WARN: Type inference failed for: r14v2 */
    /* JADX WARN: Type inference failed for: r14v22, types: [int] */
    /* JADX WARN: Type inference failed for: r14v23 */
    /* JADX WARN: Type inference failed for: r14v3 */
    /* JADX WARN: Type inference failed for: r15v13, types: [java.lang.String] */
    /* JADX WARN: Type inference failed for: r15v21 */
    /* JADX WARN: Type inference failed for: r15v22 */
    /* JADX WARN: Type inference failed for: r15v6, types: [java.lang.String] */
    /* JADX WARN: Type inference failed for: r15v7, types: [java.lang.String] */
    /* JADX WARN: Type inference failed for: r15v8, types: [java.lang.String] */
    /* JADX WARN: Type inference failed for: r29v0 */
    /* JADX WARN: Type inference failed for: r29v1 */
    /* JADX WARN: Type inference failed for: r29v2 */
    /* JADX WARN: Type inference failed for: r29v3 */
    /* JADX WARN: Type inference failed for: r29v4 */
    /* JADX WARN: Type inference failed for: r7v17, types: [boolean] */
    /* JADX WARN: Type inference failed for: r8v10 */
    /* JADX WARN: Type inference failed for: r8v11 */
    /* JADX WARN: Type inference failed for: r8v12 */
    /* JADX WARN: Type inference failed for: r8v13 */
    /* JADX WARN: Type inference failed for: r8v15 */
    /* JADX WARN: Type inference failed for: r8v16 */
    /* JADX WARN: Type inference failed for: r8v17 */
    /* JADX WARN: Type inference failed for: r8v19 */
    /* JADX WARN: Type inference failed for: r8v20 */
    /* JADX WARN: Type inference failed for: r8v3 */
    /* JADX WARN: Type inference failed for: r8v35 */
    /* JADX WARN: Type inference failed for: r8v36 */
    /* JADX WARN: Type inference failed for: r8v37 */
    /* JADX WARN: Type inference failed for: r8v38 */
    /* JADX WARN: Type inference failed for: r8v4 */
    /* JADX WARN: Type inference failed for: r8v5 */
    /* JADX WARN: Type inference failed for: r8v6, types: [java.lang.String] */
    /* JADX WARN: Type inference failed for: r8v7 */
    /*
        Code decompiled incorrectly, please refer to instructions dump.
    */
    public final ServerEntity j(Integer num, String str, String str2, String str3, e eVar) {
        ?? r14;
        int i10;
        ?? r82;
        ?? r83;
        List list;
        ?? r29;
        char c6;
        ?? r84;
        String strTrim;
        String string;
        String string2;
        String string3;
        ArrayList<IptvEntity> arrayList;
        int i11;
        int i12;
        eVar.i(0, str);
        ArrayList arrayList2 = new ArrayList();
        String strTrim2 = "";
        HashMap map = null;
        char c10 = 2;
        int i13 = 1;
        if (str2.endsWith(".txt")) {
            try {
                String[] strArrSplit = str3.split("\n");
                ArrayList arrayList3 = new ArrayList();
                for (String str4 : strArrSplit) {
                    String strTrim3 = str4.trim();
                    if (!strTrim3.isEmpty()) {
                        String[] strArrSplit2 = strTrim3.split(",");
                        if (strArrSplit2.length == 2 && strArrSplit2[1].startsWith("#") && strArrSplit2[1].endsWith("#")) {
                            strTrim2 = strArrSplit2[0].trim();
                        } else if (strArrSplit2.length >= 2) {
                            arrayList3.add(new IptvEntity(strArrSplit2[0].trim(), "", strArrSplit2[1].trim(), strTrim2, "", 0, 0, 0));
                            eVar.i(arrayList3.size(), str);
                        }
                    }
                }
                arrayList2 = arrayList3;
            } catch (Exception e10) {
                xyz.stream.utils.h.c("parseSimpleTxt error: " + e10.getMessage());
                arrayList2 = new ArrayList();
            }
            i10 = 1;
            r14 = 2;
        } else if (str3 == null) {
            r14 = 2;
            i10 = 1;
            arrayList2.add(new IptvEntity(str, "", str2, "", "", 0, 0, 0));
        } else {
            String[] strArrSplit3 = str3.split("\n");
            ArrayList arrayList4 = new ArrayList();
            for (String str5 : strArrSplit3) {
                arrayList4.add(str5.trim());
            }
            ArrayList arrayList5 = new ArrayList();
            for (int i14 = 0; i14 < arrayList4.size(); i14++) {
                if (((String) arrayList4.get(i14)).startsWith("#EXTINF:")) {
                    arrayList5.add(Integer.valueOf(i14));
                }
            }
            if (arrayList5.size() > 1) {
                Iterator it = arrayList5.iterator();
                int i15 = 0;
                while (it.hasNext()) {
                    int iC = c(((Integer) it.next()).intValue() + 1, arrayList4, map);
                    if (iC >= 0) {
                        String strTrim4 = ((String) arrayList4.get(iC)).trim();
                        if (strTrim4.startsWith("http") || strTrim4.startsWith("rtmp") || strTrim4.endsWith(".m3u8")) {
                            i15++;
                        }
                    }
                    map = null;
                }
                if (i15 > arrayList5.size() / 2 && !str2.endsWith(".mpd")) {
                    try {
                        List listAsList = Arrays.asList(str3.split("\\r?\\n"));
                        if (listAsList.isEmpty()) {
                            arrayList2 = new ArrayList();
                            r83 = 2;
                        } else {
                            ArrayList arrayList6 = new ArrayList();
                            Pattern patternCompile = Pattern.compile("([a-zA-Z0-9_\\-]+)\\s*=\\s*\"([^\"]*)\"");
                            int i16 = 0;
                            ?? r85 = "#EXTINF:";
                            while (i16 < listAsList.size()) {
                                ?? Trim = ((String) listAsList.get(i16)).trim();
                                if (Trim.startsWith(r85)) {
                                    try {
                                        int iLastIndexOf = Trim.lastIndexOf(44);
                                        if (iLastIndexOf >= 0) {
                                            try {
                                                strTrim = Trim.substring(iLastIndexOf + 1).trim();
                                            } catch (Exception e11) {
                                                e = e11;
                                                r84 = 2;
                                                i13 = 1;
                                                r82 = r84;
                                                xyz.stream.utils.h.c("parseIptv error: " + e.getMessage());
                                                arrayList2 = new ArrayList();
                                                r83 = r82;
                                                r14 = r83;
                                                i10 = i13;
                                                arrayList = arrayList2;
                                                if (arrayList.isEmpty()) {
                                                }
                                            }
                                        } else {
                                            strTrim = "";
                                        }
                                        if (iLastIndexOf >= 0) {
                                            Trim = Trim.substring(0, iLastIndexOf);
                                        }
                                        int iIndexOf = Trim.indexOf(58);
                                        ?? Trim2 = Trim;
                                        if (iIndexOf >= 0) {
                                            Trim2 = Trim.substring(iIndexOf + 1).trim();
                                        }
                                        String[] strArrSplit4 = Trim2.split("\\s+", 2);
                                        String str6 = strArrSplit4.length == 2 ? strArrSplit4[1] : "";
                                        HashMap map2 = new HashMap();
                                        int iC2 = c(i16 + 1, listAsList, map2);
                                        if (iC2 < 0) {
                                            list = listAsList;
                                            r29 = r85;
                                            c6 = 2;
                                        } else {
                                            String strA = a(((String) listAsList.get(iC2)).trim(), map2);
                                            HashMap map3 = new HashMap();
                                            Matcher matcher = patternCompile.matcher(str6);
                                            while (matcher.find()) {
                                                List list2 = listAsList;
                                                ?? r292 = r85;
                                                r85 = 2;
                                                try {
                                                    map3.put(matcher.group(1).toLowerCase(), matcher.group(2));
                                                    listAsList = list2;
                                                    r85 = r292;
                                                } catch (Exception e12) {
                                                    e = e12;
                                                    r84 = r85;
                                                    i13 = 1;
                                                    r82 = r84;
                                                    xyz.stream.utils.h.c("parseIptv error: " + e.getMessage());
                                                    arrayList2 = new ArrayList();
                                                    r83 = r82;
                                                    r14 = r83;
                                                    i10 = i13;
                                                    arrayList = arrayList2;
                                                    if (arrayList.isEmpty()) {
                                                    }
                                                }
                                            }
                                            list = listAsList;
                                            r29 = r85;
                                            c6 = 2;
                                            if (map3.get("group-title") != null) {
                                                Object obj = map3.get("group-title");
                                                Objects.requireNonNull(obj);
                                                string = obj.toString();
                                            } else {
                                                string = "";
                                            }
                                            if (map3.get("tvg-name") != null) {
                                                Object obj2 = map3.get("tvg-name");
                                                Objects.requireNonNull(obj2);
                                                string2 = obj2.toString();
                                            } else {
                                                string2 = "";
                                            }
                                            if (map3.get("tvg-logo") != null) {
                                                Object obj3 = map3.get("tvg-logo");
                                                Objects.requireNonNull(obj3);
                                                string3 = obj3.toString();
                                            } else {
                                                string3 = "";
                                            }
                                            arrayList6.add(new IptvEntity(strTrim, string3, strA, string, string2, 0, 0, 0));
                                            eVar.i(arrayList6.size(), str);
                                            i16 = iC2;
                                        }
                                    } catch (Exception e13) {
                                        e = e13;
                                        r84 = c10;
                                    }
                                } else {
                                    list = listAsList;
                                    r29 = r85;
                                    c6 = c10;
                                }
                                i13 = 1;
                                i16++;
                                listAsList = list;
                                c10 = c6;
                                r85 = r29;
                            }
                            r83 = c10;
                            arrayList2 = arrayList6;
                        }
                    } catch (Exception e14) {
                        e = e14;
                        r82 = 2;
                    }
                    r14 = r83;
                    i10 = i13;
                }
            }
        }
        arrayList = arrayList2;
        if (arrayList.isEmpty()) {
            return null;
        }
        int iNextInt = new Random().nextInt(50000000);
        if (num != null) {
            iNextInt = num.intValue();
        }
        ServerEntity serverEntity = new ServerEntity(iNextInt, str, Integer.valueOf(((int) System.currentTimeMillis()) / 1000), Integer.valueOf((int) (System.currentTimeMillis() / 1000)), str2, "", "", "", 10, "", Integer.valueOf(i10));
        Integer numValueOf = Integer.valueOf(g(serverEntity));
        if (numValueOf.intValue() < 0) {
            return null;
        }
        vf.i iVar = (vf.i) this.f35808a.iptvDao();
        iVar.getClass();
        ?? r72 = i10;
        List<IptvEntity> list3 = (List) androidx.room.util.b.b(iVar.f33973a, r72, false, new w0(7));
        HashMap map4 = new HashMap();
        if (list3 != null) {
            for (IptvEntity iptvEntity : list3) {
                map4.put(iptvEntity.getName() + "-" + iptvEntity.getLogo() + "-" + iptvEntity.getUrl() + "-" + iptvEntity.getGroupTitle() + "-" + iptvEntity.getServerId(), iptvEntity);
            }
        }
        ArrayList<IptvEntity> arrayList7 = new ArrayList();
        ArrayList arrayList8 = new ArrayList();
        int iCurrentTimeMillis = (int) (System.currentTimeMillis() / 1000);
        for (IptvEntity iptvEntity2 : arrayList) {
            iptvEntity2.setServerId(numValueOf);
            this.f35810c += r72 == true ? 1 : 0;
            String str7 = iptvEntity2.getName() + "-" + iptvEntity2.getLogo() + "-" + iptvEntity2.getUrl() + "-" + iptvEntity2.getGroupTitle() + "-" + iptvEntity2.getServerId();
            if (!map4.containsKey(str7) || map4.get(str7) == null) {
                map4.put(str7, iptvEntity2);
                arrayList7.add(iptvEntity2);
            } else {
                IptvEntity iptvEntity3 = (IptvEntity) map4.get(str7);
                Objects.requireNonNull(iptvEntity3);
                iptvEntity2.setId(iptvEntity3.getId());
                iptvEntity2.setUpdatedAt(Integer.valueOf(iCurrentTimeMillis));
                arrayList8.add(iptvEntity2);
            }
        }
        try {
            l3.b bVarC = this.f35808a.getOpenHelper().c();
            bVarC.f();
            try {
                ?? O = bVarC.o("UPDATE iptv_entity SET name = ?, logo = ?, url = ?, group_title = ?, extra = ?, server_id = ?, updated_at = ?, created_at = ? WHERE id = ?");
                Iterator it2 = arrayList8.iterator();
                while (true) {
                    i11 = 5;
                    i12 = 4;
                    if (!it2.hasNext()) {
                        break;
                    }
                    IptvEntity iptvEntity4 = (IptvEntity) it2.next();
                    if (iptvEntity4.getId() != null) {
                        O.F();
                        if (iptvEntity4.getName() != null) {
                            O.l(r72 == true ? 1 : 0, iptvEntity4.getName());
                        } else {
                            O.d(r72 == true ? 1 : 0);
                        }
                        if (iptvEntity4.getLogo() != null) {
                            O.l(r14, iptvEntity4.getLogo());
                        } else {
                            O.d(r14);
                        }
                        if (iptvEntity4.getUrl() != null) {
                            O.l(3, iptvEntity4.getUrl());
                        } else {
                            O.d(3);
                        }
                        if (iptvEntity4.getGroupTitle() != null) {
                            O.l(4, iptvEntity4.getGroupTitle());
                        } else {
                            O.d(4);
                        }
                        if (iptvEntity4.getExtra() != null) {
                            O.l(5, iptvEntity4.getExtra());
                        } else {
                            O.d(5);
                        }
                        O.a(6, iptvEntity4.getServerId().intValue());
                        O.a(7, iptvEntity4.getUpdatedAt().intValue());
                        O.a(8, iptvEntity4.getCreatedAt().intValue());
                        O.a(9, iptvEntity4.getId().intValue());
                        O.n();
                    }
                }
                ?? O2 = bVarC.o("INSERT INTO iptv_entity (name, logo, url, group_title, extra, server_id, updated_at, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                for (IptvEntity iptvEntity5 : arrayList7) {
                    O2.F();
                    if (iptvEntity5.getName() != null) {
                        O2.l(r72 == true ? 1 : 0, iptvEntity5.getName());
                    } else {
                        O2.d(r72 == true ? 1 : 0);
                    }
                    if (iptvEntity5.getLogo() != null) {
                        O2.l(r14, iptvEntity5.getLogo());
                    } else {
                        O2.d(r14);
                    }
                    if (iptvEntity5.getUrl() != null) {
                        O2.l(3, iptvEntity5.getUrl());
                    } else {
                        O2.d(3);
                    }
                    if (iptvEntity5.getGroupTitle() != null) {
                        O2.l(i12, iptvEntity5.getGroupTitle());
                    } else {
                        O2.d(i12);
                    }
                    if (iptvEntity5.getExtra() != null) {
                        O2.l(i11, iptvEntity5.getExtra());
                    } else {
                        O2.d(i11);
                    }
                    O2.a(6, iptvEntity5.getServerId().intValue());
                    O2.a(7, iptvEntity5.getUpdatedAt().intValue());
                    O2.a(8, iptvEntity5.getCreatedAt().intValue());
                    O2.I();
                    i11 = 5;
                    i12 = 4;
                }
                bVarC.t();
                bVarC.z();
                return serverEntity;
            } finally {
                bVarC.z();
            }
        } catch (Exception e15) {
            u.a.g(e15, new StringBuilder("DB batch error: "));
            return null;
        }
    }

    public final void l(ServerEntity serverEntity, List list, e eVar) {
        Integer id2 = serverEntity.getId();
        String serverName = serverEntity.getServerName();
        String rootPath = serverEntity.getRootPath();
        tb.d dVar = new tb.d((Object) this, list, (Object) eVar, 8);
        String strI = i(rootPath);
        if (strI == null) {
            dVar.h("Invalid IPTV URL.");
            return;
        }
        boolean zH = h(strI);
        ExecutorService executorService = this.f35809b;
        if (zH) {
            executorService.execute(new xyz.netfly.ads.p(this, strI, dVar, id2, serverName, 5));
        } else {
            executorService.execute(new xyz.stream.api.p(this, dVar, serverName, strI, id2, new HashMap(new HashMap())));
        }
    }

    public final boolean m(Integer num) {
        try {
            return ((Boolean) this.f35809b.submit(new androidx.media3.datasource.c(this, num, 4)).get()).booleanValue();
        } catch (Exception e10) {
            u.a.g(e10, new StringBuilder("removeIptvServer error: "));
            return false;
        }
    }
}
