"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
class TForChangeOptions {
    constructor() {
        this.side_coords = [{}, {}];
        this.bIsDialogOpen = false;
    }
}
function CreateBrowsDialogWindows(nInd, sUrlL, sUrlR, oSideCoords) {
    if (!sCurrJob || IsJobActive(sCurrJob)) {
        return false;
    }
    if (oSideCoords) {
        if (nInd === 0) {
            ListFileSystemsRequest({ conn: oSideCoords[0].conn, key: oSideCoords[0].sAcctKeyA }, 0, sUrlR);
        }
        else {
            ListFileSystemsRequest({ conn: oSideCoords[1].conn, key: oSideCoords[1].sAcctKeyA }, 1, sUrlL);
        }
    }
    SetStretchEl();
    return true;
}
function OpenFolderInExplorer(text, aPaths) {
    return __awaiter(this, void 0, void 0, function* () {
        if (aPaths.path_arr.length != 1) {
            return;
        }
        const oJobInList = aGlobJobArray.find(item => item.name == sCurrJob);
        if (oJobInList && oJobInList.oSideCoords) {
            const ind = (text == "Cmd_OpenLFolder") ? 0 : 1;
            const oConnCpy = CopyObject(oJobInList.oSideCoords[ind].conn);
            oConnCpy.sUrlA += "/" + aPaths.path_arr[0];
            try {
                const oListFs = yield AsyncUnicSendRecivePostApiWithRetry("ListFileSystems", {});
                BrowseDialogForSideUrlChange(oListFs.file_systems, { bExplore: true, oIFDD: { conn: oConnCpy, key: oJobInList.oSideCoords[ind].sAcctKeyA } });
            }
            catch (oErr) {
                if (oErr && oErr.message) {
                    ErrorMsgShow("ListFileSystems:", oErr.message, "msgbox");
                }
            }
        }
    });
}
function SetFsBranch(oBrCont, oData) {
    if ((!oData.properties || oData.properties.hide_in_fs_list == "1") && !bShowHiddenFs) {
        return null;
    }
    let sIcon = oData.icon_url;
    sIcon = sIcon.trim();
    if (sIcon.substring(sIcon.length - 1) == "/") {
        sIcon = "C_Ena_Que_Fil";
    }
    else if (location.pathname == sLocPathName) {
    }
    else if (location.pathname.endsWith("WebGSExplorer.html")) {
        sIcon = location.pathname.replace(/static\/WebGSExplorer\.html$/, '') + sIcon.replace(/\/web-ui\//, '');
    }
    else {
        sIcon = location.pathname + sIcon.replace(/\/web-ui\//, '');
    }
    const tmp = {
        sFs: oData.plain_url,
        icon: sIcon,
        display_name: oData.display_name,
        comment: "" + oData.long_description,
        size: "",
        tMod_s: -1,
        bContServList: oData.properties.can_list_servers === "1",
        bHasNoServAddr: oData.properties.no_server_addr === "1",
        bUserIdInHostname: oData.properties.has_userid_in_hostname === "1",
        bAuthOauth2: oData.properties.auth_oauth2 === "1",
        menu: (oData.plain_url.toLowerCase() == "file://" || oData.plain_url.toLowerCase() == "mtp://") ? "" : "new-account-16",
    };
    oBrCont.cont = [];
    oBrCont.folder = 0;
    return tmp;
}
let funcForAccounts = [
    function (oBranch, oDTP) {
        const oData = oBranch.fGetData();
        oData.oConn.sUrlA = oData.sUrl;
        ListServersRequest(oData.oConn, null, { DTP: oDTP, Branch: oBranch });
    },
    function (oBranch, oDTP) {
        const oData = oBranch.fGetData();
        oData.oConn.sUrlA = oData.sUrl;
        if (oData.oBookmarkAcc && oData.sFsHandle && oData.sFsHandle2) {
            if (oData.bIgnoreBookmark) {
                ListDirForExplorerRequest(oData.sFsHandle, oData.sHomePath, [], { Branch: oBranch, DTP: oDTP });
            }
            else {
                ListDirForExplorerRequest(oData.sFsHandle, "", [], { Branch: oBranch, DTP: oDTP });
            }
        }
        else {
            ConnectFsRequest(oData.oConn, null, { DTP: oDTP, Branch: oBranch }, { bWasAccessDenay: true });
        }
    }
];
function SetAccFields(oBranch) {
    let sComment = oBranch.AcctConn.sDisplayNameA;
    if (oBranch.AcctConn.sUserEmailA && sComment) {
        sComment += " (" + oBranch.AcctConn.sUserEmailA + ")";
    }
    if (!sComment) {
        sComment = oBranch.AcctConn.sUserIdA;
    }
    let sDisplayName = oBranch.DisplayName;
    if (!sDisplayName) {
        sDisplayName = GetSummary(oBranch.AcctConn);
    }
    return { sDispName: sDisplayName + oBranch.HomePath, sComment: sComment, sUrl: oBranch.AcctConn.sUrlA, sHomePath: oBranch.HomePath };
}
function GetFieldValWithDrillUp(oTBC, sFieldName) {
    const oData = oTBC.fGetData();
    if (sFieldName in oData) {
        return oData[sFieldName];
    }
    if (oTBC.pParent) {
        return GetFieldValWithDrillUp(oTBC.pParent, sFieldName);
    }
    return "";
}
function ProcessAccBranch(oBranch, bAccContainServerList, bAccReadOnly, oBrCont) {
    const oAccFields = SetAccFields(oBranch);
    const oBrowsTreeData = {
        display_name: oAccFields.sDispName,
        comment: oAccFields.sComment,
        sUrl: oAccFields.sUrl,
        sHomePath: oAccFields.sHomePath,
        size: "",
        tMod_s: -1,
        sAccKey: oBranch.Key,
        bContServList: bAccContainServerList,
        bAccReadOnly: bAccReadOnly,
        oConn: oBranch.AcctConn,
        icon: "account-16",
        menu: "menu",
        fGetFsHandle: function (oCurrTBC, oFirstTBR, oAbort) {
            return __awaiter(this, void 0, void 0, function* () {
                const oThatBranch = oCurrTBC.fGetData();
                if (oFirstTBR === null) {
                    delete oThatBranch.oBranchUseFsHandle;
                    return "";
                }
                if (oThatBranch.sFsHandle) {
                    while (oAbort && !oAbort.aborted) {
                        if (!oThatBranch.oBranchUseFsHandle || !oThatBranch.oBranchUseFsHandle.oIsWaiting) {
                            oThatBranch.oBranchUseFsHandle = oFirstTBR;
                            return oThatBranch.sFsHandle;
                        }
                        yield new Promise(resolve => setTimeout(resolve, 1000));
                    }
                }
                throw "";
            });
        },
        fSetFsHandle: function (sFsHandle) { this.sFsHandle = sFsHandle; },
        fGetAccKey: function () { return this.sAccKey; },
        fGetUrl: function () { return this.sUrl; },
        fGetPathAndName: function (oBrowsBranch, bIsEnc) {
            if (this.oBookmarkAcc && !this.bIgnoreBookmark) {
                if (bIsEnc) {
                    return this.sHomePath;
                }
                return "";
            }
            return this.sHomePath;
        }
    };
    const aBookmarks = GetEncOrComressBookmarks(oBranch, oBrowsTreeData);
    if (aBookmarks) {
        oBrowsTreeData.aBookmarks = aBookmarks;
        oBrCont.bEncOrZip = true;
    }
    return oBrowsTreeData;
}
function GetEncOrComressBookmarks(oBranch, oBrowsTreeData) {
    const aBookmarks = [];
    if (oBranch.UnnamedBookmarks && oBranch.UnnamedBookmarks.length) {
        for (const bm of oBranch.UnnamedBookmarks) {
            if (bm.Opts.nCompressType > 1 || bm.Opts.bEncryptBodies || bm.Opts.bEncryptPaths) {
                aBookmarks.push(bm);
                if (bm.BmkKey == oBrowsTreeData.sHomePath) {
                    oBrowsTreeData.icon = "account-enc";
                    oBrowsTreeData.oBookmarkAcc = aBookmarks[aBookmarks.length - 1];
                }
            }
        }
    }
    if (aBookmarks.length > 0) {
        return aBookmarks;
    }
}
function AccountRightBtn(e, nCurrRow, oDTP) {
    let zInd = Number(e.target.style.zIndex);
    if (!zInd)
        zInd = 0;
    TableRowClick(oDTP, oDTP.aDeploedTable[nCurrRow]._branch_);
    CreateDropMenuItems(jsBrowseDialogAccMenu, e.clientX, e.clientY, e.clientX, e.target, false, { "Branch": oDTP.aDeploedTable[nCurrRow]._branch_, "DTP": oDTP });
}
function ProcessAccBranchForTable(oBrCont, data) {
    oBrCont.fOpenFolder = data.bContServList ? funcForAccounts[0] : funcForAccounts[1];
    oBrCont.fRightBtn = AccountRightBtn;
    oBrCont.cont = [];
    oBrCont.folder = 0;
    oBrCont.bNoSelectWithShiftOrCtrl = true;
    return data;
}
function ProcessFolderBranchForTable(oBrCont, data) {
    if ("oConn" in data) {
        oBrCont.cont = [];
        oBrCont.folder = 0;
    }
    return data;
}
function ProcessServerBranchForTable(oBrCont, data) {
    oBrCont.cont = [];
    oBrCont.folder = 0;
    return data;
}
function FindAccountBranch(treeBr, sAccKey) {
    for (let item of treeBr._branch_.fGetData().__cont__) {
        if (item.Kyy == sAccKey)
            return item;
    }
}
function SetBrowsTreeAccounts(aBranchArr, xHint, oTreeBranchs) {
    const oBrowsTreeData = [];
    for (const oBranch of aBranchArr) {
        let bAccContainServerList = false;
        let bAccReadOnly = false;
        if (typeof xHint === "boolean") {
            bAccContainServerList = xHint;
        }
        else {
            const oHint = xHint.find(item => item.AccountKey == oBranch.Key);
            if (oHint) {
                bAccContainServerList = oHint.hint_properties.list_servers;
                bAccReadOnly = oHint.hint_properties.read_only;
            }
        }
        oBrowsTreeData.push(ProcessAccBranch(oBranch, bAccContainServerList, bAccReadOnly, oTreeBranchs));
    }
    return oBrowsTreeData;
}
function SetBrowsTreeServers(aBranchArr, oTreeBranchs, sUrlA, oConn, oClass) {
    const func = {
        fRightBtn: function (e, nCurrRow, oDTP) {
            TableRowClick(oDTP, oDTP.aDeploedTable[nCurrRow]._branch_);
            CreateDropMenuItems(jsBrowseDialogServerMenu, e.clientX, e.clientY, e.clientX, e.target, false, {
                "Branch": oDTP.aDeploedTable[nCurrRow]._branch_, "DTP": oDTP
            });
        },
        fOpenFolder: function (oBranch, oDTP) {
            ConnectFsRequest(oBranch.fGetData().oConn, null, { DTP: oDTP, Branch: oBranch }, {});
        },
    };
    const aBTD = [];
    for (const oBranch of aBranchArr) {
        let sDispName = oBranch.sDisplayNameA;
        if (!sDispName && sDispName == "") {
            sDispName = oBranch.sUrlA;
        }
        const oTmpConn = CopyObject(oConn);
        oTmpConn.sUrlA = oBranch.sUrlA;
        let sIcon = "unknown-os";
        if (oBranch.sCommentA.toLowerCase().includes("[linux]")) {
            sIcon = "linux";
        }
        else if (oBranch.sCommentA.toLowerCase().includes("[windows]")) {
            sIcon = "windows";
        }
        else if (oBranch.sCommentA.toLowerCase().includes("[macos]")) {
            sIcon = "apple";
        }
        const oBrData = {
            sUrl: oBranch.sUrlA,
            oConn: oTmpConn,
            icon: sIcon,
            display_name: sDispName,
            size: "",
            tMod_s: (oBranch.tMod_s == 0) ? -1 : oBranch.tMod_s,
            comment: oBranch.sCommentA,
            bIsServer: true,
            menu: "menu",
            fGetUrl: function () { return this.sUrl; },
            fGetFsHandle: function (oCurrTBC, oFirstTBR, oAbort) {
                return __awaiter(this, void 0, void 0, function* () {
                    const oThatBranch = oCurrTBC.fGetData();
                    if (oThatBranch.sFsHandle) {
                        if (oFirstTBR === null) {
                            delete oThatBranch.oBranchUseFsHandle;
                            return "";
                        }
                        while (oAbort && !oAbort.aborted) {
                            if (!oThatBranch.oBranchUseFsHandle || !oThatBranch.oBranchUseFsHandle.oIsWaiting) {
                                oThatBranch.oBranchUseFsHandle = oFirstTBR;
                                return oThatBranch.sFsHandle;
                            }
                            yield new Promise(resolve => setTimeout(resolve, 1000));
                        }
                    }
                    if (oThatBranch.fGetFsHandle && oCurrTBC.pParent) {
                        try {
                            return yield oThatBranch.fGetFsHandle(oCurrTBC.pParent, oFirstTBR, oAbort);
                        }
                        catch (_a) {
                            throw "";
                        }
                    }
                    throw "";
                });
            },
            fSetFsHandle: function (sFsHandle) { this.sFsHandle = sFsHandle; },
            fGetAccKey: function (oBrowsBranch) {
                const oData = oTreeBranchs.fGetData();
                if (oData.fGetAccKey)
                    return oData.fGetAccKey();
                return "";
            },
            fGetPathAndName: function (oBrowsBranch, bIsEnc) {
                let ret = "";
                if (oBrowsBranch.pParent) {
                    const oData = oBrowsBranch.pParent.fGetData();
                    if (oData.fGetPathAndName) {
                        ret = oData.fGetPathAndName(oBrowsBranch.pParent, bIsEnc);
                    }
                }
                return ret;
            }
        };
        aBTD.push(oBrData);
    }
    return oTreeBranchs.fAddDataArr(aBTD, { oFunc: func, fDataProcessor: ProcessServerBranchForTable, bNoSelectWithShiftOrCtrl: true, sPathFieldName: "sUrl", "sSpecValue": sUrlA, oTdProperties: oClass });
}
let aFreeSpacePlacesId = [];
let pGettingFsHandleAbort = null;
function AsyncFreeSpaceRequest(oTBC, sPath) {
    return __awaiter(this, void 0, void 0, function* () {
        const oTarget = oTBC.fGetData();
        if (!oTarget.fGetFsHandle)
            return;
        try {
            const sFsHandle = yield oTarget.fGetFsHandle(oTBC, oTBC, pGettingFsHandleAbort);
            const oFreeSpaceData = yield AsyncUnicSendRecivePostApiWithRetry("GetFreeDiskSpace", { "filesys_handle": sFsHandle, "path": sPath });
            oTarget.fGetFsHandle(oTBC, null);
            const oDiscSpaces = ConvertBytes(oFreeSpaceData.total, oFreeSpaceData.available);
            if (!Number.isNaN(oDiscSpaces.nSpace1)) {
                oTarget.comment += (oTarget.comment ? ", " : "") + "Total: " + RoundTo3Digits(oDiscSpaces.nSpace1) + " " + oDiscSpaces.unit;
            }
            if (!Number.isNaN(oDiscSpaces.nSpace2)) {
                oTarget.comment += (oTarget.comment ? ", " : "") + "Free: " + RoundTo3Digits(oDiscSpaces.nSpace2) + " " + oDiscSpaces.unit;
            }
        }
        catch (oErr) {
            let x = 0;
        }
    });
}
function ShowFreeSpace(oDTP) {
    return __awaiter(this, void 0, void 0, function* () {
        if (!aFreeSpacePlacesId || aFreeSpacePlacesId.length <= 0)
            return;
        for (const it of aFreeSpacePlacesId) {
            if (it.branch.cont && it.branch.cont.length > it.ind) {
                const oRealBranch = it.branch.cont.find(br => br.indJs == it.ind);
                if (oRealBranch) {
                    it.branch = oRealBranch;
                }
            }
            yield AsyncFreeSpaceRequest(it.branch, it.path);
        }
        aFreeSpacePlacesId = [];
        if (oDTP) {
            oDTP.ShowTable();
        }
    });
}
function IsFolderInBookmarks(sPath, oTreeBranchs) {
    let sServerAndPath = "";
    while (oTreeBranchs) {
        const oData = oTreeBranchs.fGetData();
        if (oData.bIsServer) {
            sServerAndPath = oData.sUrl;
        }
        if (oData.aBookmarks) {
            sServerAndPath =
                GetServerName(oData.oConn.sUrlA, sServerAndPath, oData.oConn.sUserIdA)
                    + sPath;
            const oTmpBm = oData.aBookmarks.find(it => it.BmkKey === sServerAndPath);
            if (oTmpBm) {
                const oConn1 = CopyObject(oData.oConn);
                oConn1.sUrlA += sPath;
                const oBm = new TBookmark;
                SetSameObjFields(oTmpBm, oBm);
                oBm.opts = oTmpBm.Opts;
                if (!oBm.sServerDirA) {
                    oBm.sServerDirA = oTmpBm.BmkKey;
                }
                return { bm: oBm, conn: oConn1 };
            }
            return;
        }
        oTreeBranchs = oTreeBranchs.pParent;
    }
}
function IsBookmarkInFolder(oBDE) {
    const oData = oBDE.Branch.fGetData();
    return (!oData.oBookmark && !oData.oBookmarkAcc) ? (oData.bIgnoreBookmark ? -1 : 0) : (oData.bIgnoreBookmark ? 1 : 2);
}
function AddBookmarkToAcc(oBM, oTreeBranchs) {
    while (oTreeBranchs) {
        const oData = oTreeBranchs.fGetData();
        if (oData.sAcctKeyA) {
            if (!oData.aBookmarks) {
                oData.aBookmarks = [];
            }
            oData.aBookmarks.push(oBM);
            return;
        }
        oTreeBranchs = oTreeBranchs.pParent;
    }
}
function GetBookmarkInFolder(sPath, oTreeBranchs) {
    const oData = oTreeBranchs.fGetData();
    if (oData.oBookmark) {
        const oConn1 = CopyObject(oData.oConn);
        oConn1.sUrlA = sPath;
        return { bm: oData.oBookmark, conn: oConn1 };
    }
}
function GetBaseFsHandle(oBr) {
    while (oBr.pParent) {
        const oData = oBr.pParent.fGetData();
        if (oData.sFsHandle && (oData.sAccKey || oData.bIsServer)) {
            return oData.sFsHandle;
        }
        oBr = oBr.pParent;
    }
    return "";
}
const MIN_BAD_ENC_ITEM = 3;
const MAX_CHECK_ENC_ITEM = 3000;
function GsFolderLooksEncrypted(alsItems, nMaxBadNamesPercent = 100) {
    const nItemsEff = alsItems.length;
    if (nItemsEff < 1) {
        return "";
    }
    const nCheckingItems = Math.min(nItemsEff, MAX_CHECK_ENC_ITEM);
    const nStep = nItemsEff / nCheckingItems;
    const nBadNamesThreshold = (nCheckingItems < MIN_BAD_ENC_ITEM * 2) ?
        Math.floor(nCheckingItems / 2) :
        Math.max(((nMaxBadNamesPercent >= 100) ?
            0 : (1 - nMaxBadNamesPercent * 0.01)) * nCheckingItems, MIN_BAD_ENC_ITEM);
    let nBadNames = 0;
    let i = 0;
    let nCnt = 0;
    for (; i < nItemsEff;) {
        if (!alsItems[i].sNameA.endsWith(".gszip")) {
            nBadNames++;
            if (nBadNames > nBadNamesThreshold) {
                break;
            }
        }
        nCnt += nStep;
        i = Math.floor(nCnt);
    }
    if (i >= nItemsEff) {
        return "gszip";
    }
    i = 0;
    nCnt = 0;
    for (; i < nItemsEff;) {
        if (!GsItemNameLooksEncrypted(alsItems[i].sNameA)) {
            nBadNames++;
            if (nBadNames > nBadNamesThreshold) {
                return "";
            }
        }
        nCnt += nStep;
        i = Math.floor(nCnt);
    }
    return "encrypted";
}
function GsItemNameLooksEncrypted(sItemName) {
    if (sItemName.length < 23) {
        return false;
    }
    return /^[A-Za-z0-9+\/_-]*$/.test(sItemName);
}
function SetBrowsTreeFolders(aBranchArr, sPath, oTreeBranchs, aExcludeNames, bWOFiles) {
    const aBrTreeData = [];
    const aFunc = [];
    const oData = oTreeBranchs.fGetData();
    if (!oData.oBookmark && !oData.oBookmarkAcc && !IsIntoEncOrZip(oTreeBranchs)) {
        switch (GsFolderLooksEncrypted(aBranchArr)) {
            case "gszip":
                {
                    if (oData.icon.startsWith("account")) {
                        oData.icon = "account-prob-zip";
                    }
                    else {
                        oData.icon = "gs-prob-zip";
                    }
                    oData.bIgnoreBookmark = true;
                    oTreeBranchs.bEncOrZip = true;
                }
                break;
            case "encrypted":
                {
                    if (oData.icon.startsWith("account")) {
                        oData.icon = "account-prob-enc";
                    }
                    else {
                        oData.icon = "folder-prob-enc";
                    }
                    oData.bIgnoreBookmark = true;
                    oTreeBranchs.bEncOrZip = true;
                }
                break;
        }
    }
    else {
        oTreeBranchs.bEncOrZip = true;
    }
    for (const oBranch of aBranchArr) {
        if (bWOFiles && oBranch.bIsFile || aExcludeNames.includes(oBranch.sNameA)) {
            continue;
        }
        let sDispName = oBranch.sDisplayName + "";
        if (sDispName == "") {
            sDispName = "" + oBranch.sNameA;
        }
        let sComment = oBranch.sComment + "";
        if (!sPath)
            sPath = "";
        const sfPathAndName = sPath + "/" + oBranch.sNameA;
        if (oBranch.bIsLink) {
            sComment = "->" + sComment;
        }
        let oBrTreeData;
        const func = {};
        if (oBranch.bIsFile) {
            oBrTreeData = {
                icon: GetFileExtension(oBranch.sNameA),
                display_name: sDispName,
                size: oBranch.size,
                tMod_s: (oBranch.tMod_s == 0) ? -1 : oBranch.tMod_s,
                comment: sComment,
                sName: oBranch.sNameA,
                menu: "menu",
                bIsFile: true
            };
            func.fRightBtn = function (e, nCurrRow, oDTP) {
                const oBranch = oDTP.aDeploedTable[nCurrRow]._branch_;
                oFileDowloadData.oBranch = oBranch;
                oFileDowloadData.oDTP = oDTP;
                TableRowClick(oDTP, oBranch);
                CreateDropMenuItems(jsBrowseDialogFileMenu, e.clientX, e.clientY, e.clientX, e.target, false, { "Branch": oBranch, "DTP": oDTP });
            };
        }
        else {
            oBrTreeData = {
                oConn: oData.oConn,
                icon: "folder",
                display_name: sDispName,
                comment: sComment,
                sName: oBranch.sNameA,
                size: oBranch.size,
                tMod_s: (oBranch.tMod_s == 0) ? -1 : oBranch.tMod_s,
                menu: "menu",
            };
            const oBm = IsFolderInBookmarks(sfPathAndName, oTreeBranchs);
            if (oBm) {
                if (oBm.bm.opts.nCompressType > 0) {
                    if (oBrTreeData.icon.startsWith("account")) {
                        oBrTreeData.icon = "account-prob-zip";
                    }
                    else {
                        oBrTreeData.icon = "gs-zip";
                    }
                }
                else {
                    if (oBrTreeData.icon.startsWith("account")) {
                        oBrTreeData.icon = "account-prob-enc";
                    }
                    else {
                        oBrTreeData.icon = "folder-enc";
                    }
                }
                oBrTreeData.oBookmark = oBm.bm;
            }
            else if (oBranch.bIsLink) {
                oBrTreeData.icon = "folder_link";
            }
            func.fRightBtn = function (e, nCurrRow, oDTP) {
                TableRowClick(oDTP, oDTP.aDeploedTable[nCurrRow]._branch_);
                oFileDowloadData.oBranch = oDTP.aDeploedTable[nCurrRow]._branch_;
                oFileDowloadData.oDTP = oDTP;
                CreateDropMenuItems(jsBrowseDialogFolderMenu, e.clientX, e.clientY, e.clientX, e.target, false, { "Branch": oDTP.aDeploedTable[nCurrRow]._branch_, "DTP": oDTP });
            };
            func.fOpenFolder = function (oBranch, oDTP, sNameForMark) {
                const oDataOpen = oBranch.fGetData();
                ListDirForExplorerRequest("", oDataOpen.fGetPathAndName(oBranch), null, { "DTP": oDTP, "Branch": oBranch }, sNameForMark);
            };
        }
        oBrTreeData.fGetPathAndName = function (oBrowsBranch, bIsEnc) {
            if (!("sName" in this) || this.oBookmark && !this.bIgnoreBookmark) {
                if (bIsEnc && this.oBookmark && this.oBookmark.BmkKey) {
                    return this.oBookmark.BmkKey;
                }
                return "";
            }
            let ret = "/" + this.sName;
            if (oBrowsBranch.pParent) {
                const oData = oBrowsBranch.pParent.fGetData();
                if (oData.fGetPathAndName) {
                    ret = oData.fGetPathAndName(oBrowsBranch.pParent, bIsEnc) + ret;
                }
            }
            return ret;
        };
        oBrTreeData.fGetUrl = function () {
            if (oData.fGetUrl)
                return oData.fGetUrl();
            return "";
        };
        oBrTreeData.fSetFsHandle = function (sFsHandleInp, bLocalFsHandle) {
            if (bLocalFsHandle) {
                this.sFsHandle = sFsHandleInp;
            }
            else {
                oData.fSetFsHandle(sFsHandleInp);
            }
        };
        oBrTreeData.fGetAccKey = function () {
            if (oData.fGetAccKey)
                return oData.fGetAccKey();
            return "";
        };
        oBrTreeData.fGetFsHandle = function (oCurrTBC, oFirstTBR, oAbort) {
            return __awaiter(this, void 0, void 0, function* () {
                if (!oCurrTBC)
                    return "";
                const oThatBranch = oCurrTBC.fGetData();
                if (oFirstTBR === null) {
                    if (oThatBranch.fGetFsHandle && oCurrTBC.pParent) {
                        oThatBranch.fGetFsHandle(oCurrTBC.pParent, null);
                    }
                    delete oThatBranch.oBranchUseFsHandle;
                    return "";
                }
                if (oThatBranch.sFsHandle && (!oThatBranch.bIgnoreBookmark || oThatBranch.sFsHandle2)) {
                    while (oAbort && !oAbort.aborted) {
                        if (oThatBranch.oBranchUseFsHandle && oThatBranch.oBranchUseFsHandle.oIsWaiting) {
                            yield new Promise(resolve => setTimeout(resolve, 1000));
                        }
                        else {
                            oThatBranch.oBranchUseFsHandle = oFirstTBR;
                            return oThatBranch.sFsHandle;
                        }
                    }
                }
                if (oThatBranch.fGetFsHandle && oCurrTBC.pParent) {
                    try {
                        return yield oThatBranch.fGetFsHandle(oCurrTBC.pParent, oFirstTBR, oAbort);
                    }
                    catch (_a) { }
                }
                throw "";
            });
        };
        if (oBranch.dwAbilities & GS_AB_IS_DISK) {
            aFreeSpacePlacesId.push({ branch: oTreeBranchs, path: sfPathAndName, ind: aBrTreeData.length });
        }
        aBrTreeData.push(oBrTreeData);
        aFunc.push(func);
    }
    return { aData: aBrTreeData, aFunc: aFunc };
}
function AddErrorToTree(error, oBDE) {
    if (!oBDE.DTP || !oBDE.Branch) {
        ErrorMsgShow("Job Tree error: ", error.message, "both");
    }
    else {
        const bFolderOpen = oBDE.Branch.folder == 1;
        oBDE.Branch.fClear();
        let tmp = {
            icon: "C_Ena_Att_Fill",
            display_name: "<div style='color:red; white-space: normal;'>" + error.message + "</div>",
            comment: (error.data && error.data.error_num) ? "<div style='color:red;'>Error " + error.data.error_num + "</div>" : "",
            menu: "",
        };
        oBDE.Branch.fAddData(tmp, {});
        if (bFolderOpen) {
            oBDE.Branch.folder = 1;
            oBDE.DTP.ShowTable();
        }
        oBDE.Branch.bError = true;
    }
}
function CleanAndCloseBranch(oBDE) {
    if (oBDE.Branch) {
        oBDE.Branch.fClear();
        oBDE.Branch.folder = 0;
    }
    oBDE.DTP.ShowTable();
}
function RefreshAcc(oBDE) {
    const oData = oBDE.Branch.fGetData();
    const oConn = { conn: oData.oConn, key: oData.sAccKey };
    oConn.conn.sUrlA = oData.sUrl + oData.fGetPathAndName(oBDE.Branch);
    oBDE.Branch = GetEldestParent(oBDE.Branch);
    CleanAndCloseBranch(oBDE);
    ListAccForExplorerRequest(oConn, oBDE);
}
function ReconnectFs(oBDE, sFolderName) {
    CleanAndCloseBranch(oBDE);
    const oData = oBDE.Branch.fGetData();
    oData.oConn.sUrlA = oData.fGetUrl();
    ConnectFsRequest(oData.oConn, null, oBDE, { sPathForReconnect: oData.fGetPathAndName(oBDE.Branch), sFolderName });
}
function GetEldestParent(oBranch) {
    if (oBranch.pParent) {
        return GetEldestParent(oBranch.pParent);
    }
    else {
        return oBranch;
    }
}
let nWaitBoxFilling = 0;
function WaitBoxFilling() {
    let aWaitBoxes = document.getElementsByClassName("waiting_box");
    nWaitBoxFilling++;
    for (const el of aWaitBoxes) {
        const domEl = el;
        SetWaitingSimbols1(domEl, nWaitBoxFilling);
    }
}
setInterval(WaitBoxFilling, 1000);
function ShowWaitingTimer(text, oBDE) {
    oBDE.Branch.fWaitingExit = function () {
        if (oBDE.Branch.fGetData().__oAbort__) {
            oBDE.Branch.fGetData().__oAbort__.abort();
        }
        oBDE.Branch.fClear();
        oBDE.DTP.ShowTable();
    };
    oBDE.Branch.fSetWaitingTimer(text);
    oBDE.Branch.folder = 1;
    oBDE.DTP.ShowTable();
}
const oFCO = new TForChangeOptions;
function ClearFCO() {
    delete oFCO["eJobDirection"];
    oFCO.side_coords = [{}, {}];
    oFCO.bIsDialogOpen = false;
}
function SetUrlToDom(dom, sUrl) {
    if (dom.tagName.toUpperCase() == "INPUT") {
        const input = dom;
        input.value = sUrl;
        input.dispatchEvent(new Event('input'));
    }
    else {
        dom.innerHTML = sUrl;
    }
}
function SetBrowseDialogErr(dom, sErr) {
    dom.innerHTML = "<div class='job_errors'>" + sErr + "</div>";
}
function SetNewJobUrl(oTableBranch, dom, ind, sUrl2, domResume, domSaveBtn) {
    if (!dom) {
        return "";
    }
    const oData = oTableBranch.fGetData();
    if (oData.bIsFile) {
        if (domSaveBtn) {
            domSaveBtn.disabled = true;
        }
        return "";
    }
    let sUrl = GetFieldValWithDrillUp(oTableBranch, "sFs");
    let sfPathAndName = "";
    if (oData.fGetPathAndName) {
        sfPathAndName = oData.fGetPathAndName(oTableBranch, true);
    }
    if (oData.oConn && IsFsGST(oData.oConn.sUrlA)) {
        const sServerName = GetGstServerName(oData.oConn.sUrlA, oData.oConn.sUserIdA);
        if (sServerName && sfPathAndName.startsWith(sServerName)) {
            sfPathAndName = sfPathAndName.slice(sServerName.length);
        }
    }
    if (oData.fGetUrl) {
        sUrl = oData.fGetUrl() + sfPathAndName;
        if (oData.sName) {
            SetUrlToDom(dom, GetPathForShow(sUrl));
        }
        else {
            SetUrlToDom(dom, sUrl);
        }
    }
    else {
        SetUrlToDom(dom, sUrl);
    }
    if (!oData.oBookmark && !oData.oBookmarkAcc && (oTableBranch.fFindEl("", "oBookmark", "up") || oTableBranch.fFindEl("", "oBookmarkAcc", "up"))) {
        if (domSaveBtn) {
            domSaveBtn.disabled = true;
        }
        SetDomDisplayAndInnerHtml(domResume, "", { text: GetLocaleText("Browse_Hint_CryptLevel"), class: "job_errors", img: "error" });
        return sUrl;
    }
    if (!oData.bCanCreateFolders && !oData.sName) {
        if (domSaveBtn) {
            domSaveBtn.disabled = true;
        }
        SetDomDisplayAndInnerHtml(domResume, "", { text: GetLocaleText("Browse_Hint_BadLevel"), class: "job_errors", img: "error" });
        return sUrl;
    }
    if (DoJobPathsContainsOneAnother(sUrl, sUrl2)) {
        SetDomDisplayAndInnerHtml(domResume, "", {
            text: GetLocaleText("Str_ErrOfChsePahs") + "<br/>" +
                GetLocaleText("Browse_Hint_AnotherSide") + GetPathForShow(sUrl2),
            class: "err_above_tree non_term_error_cell", img: "warning"
        });
    }
    else {
        SetDomDisplayAndInnerHtml(domResume, "", { text: GetLocaleText("Browse_Hint_Select"), class: "job_success", img: "success" });
    }
    if (IsFsGST(GetFieldValWithDrillUp(oTableBranch, "sFs"))) {
        sfPathAndName = ExtractSubstring(sUrl, "://", "." + oData.oConn.sUserIdA) + sfPathAndName;
    }
    if (domSaveBtn) {
        domSaveBtn.disabled = false;
    }
    ClearFCO();
    if (oData.oBookmark || oData.oBookmarkAcc) {
        oFCO.side_coords[ind].opts = oData.oBookmark ? oData.oBookmark.opts : oData.oBookmarkAcc.opts;
    }
    oFCO.side_coords[ind].conn = CopyObject(oData.oConn);
    oFCO.side_coords[ind].conn.sUrlA = sUrl;
    oFCO.side_coords[ind].sAcctKeyA = oData.fGetAccKey();
    oFCO.side_coords[ind].sServerDirA = sfPathAndName;
    oFCO.side_coords[ind].sPasswordEncMasterA = oData.sPasswordEncMasterA;
    return sUrl;
}
function SetNewUrlForExplorer(oTableBranch, dom) {
    if (!dom)
        return;
    const oData = oTableBranch.fGetData();
    let sfPathAndName = "";
    if (oData.fGetPathAndName) {
        sfPathAndName = oData.fGetPathAndName(oTableBranch, true);
    }
    if (oData.oConn && IsFsGST(oData.oConn.sUrlA)) {
        const sServerName = GetGstServerName(oData.oConn.sUrlA, oData.oConn.sUserIdA);
        if (sServerName && sfPathAndName.startsWith(sServerName)) {
            sfPathAndName = sfPathAndName.slice(sServerName.length);
        }
    }
    if (oData.fGetUrl) {
        SetUrlToDom(dom, GetPathForShow(oData.fGetUrl() + sfPathAndName));
    }
    else {
        SetUrlToDom(dom, GetPathForShow(GetFieldValWithDrillUp(oTableBranch, "sFs")));
    }
}
function GetPathForShow(oJobUrlAndPath) {
    if (!oJobUrlAndPath) {
        return "";
    }
    if (oJobUrlAndPath.startsWith("\/")) {
        return oJobUrlAndPath.substring(1);
    }
    else if (oJobUrlAndPath.startsWith("file:\/\/")) {
        return oJobUrlAndPath.substring(8);
    }
    return oJobUrlAndPath;
}
function GetPathFromShow(oJobUrlAndPath) {
    if (!oJobUrlAndPath) {
        return "";
    }
    if (!oJobUrlAndPath.includes("://")) {
        return "file://" + oJobUrlAndPath;
    }
    return oJobUrlAndPath;
}
function RefreshBrowseBranch(sType, oBDE, sFolderName) {
    if (!oBDE.Branch || !oBDE.DTP)
        return;
    oBDE.Branch.fClear();
    oBDE.Branch.folder = 1;
    switch (sType) {
        case "Normal":
            {
                const oData = oBDE.Branch.fGetData();
                if (oData.sFsHandle2 && !oData.bIgnoreBookmark) {
                    const tmp = oData.sFsHandle2;
                    oData.sFsHandle2 = oData.sFsHandle;
                    oData.sFsHandle = tmp;
                }
                oData.bIgnoreBookmark = true;
            }
            break;
        case "Encrypt":
            {
                const oData = oBDE.Branch.fGetData();
                if (oData.sFsHandle2 && oData.bIgnoreBookmark) {
                    const tmp = oData.sFsHandle2;
                    oData.sFsHandle2 = oData.sFsHandle;
                    oData.sFsHandle = tmp;
                }
                if (oData.icon.includes("-err-") || oData.icon.includes("-prob-")) {
                    const oFO = new TOpts;
                    oFO.sRawPasswd = "";
                    oFO.sRepPasswd = "";
                    const oBM = new TBookmark;
                    const sUrlA = oData.fGetPathAndName(oBDE.Branch);
                    oBM.BmkKey = sUrlA;
                    oBM.sServerDirA = sUrlA;
                    oBM.sAcctKeyA = oData.fGetAccKey();
                    const oMeta = { conn: oData.oConn, sServerDirA: sUrlA, sAcctKeyA: oBM.sAcctKeyA };
                    if (oData.icon == "gs-prob-zip") {
                        oFO.nCompressType = 2;
                        jsFloatMenu["BookmarkZipOptions"].meta = oMeta;
                        CreateFloatMenu(jsFloatMenu["BookmarkZipOptions"], { width: "650px", top: "30%" }, oFO, { minWidth: "450px", minHeight: "200px" }).promise.then(data => {
                            oFO.sRepPasswd = oFO.sRawPasswd;
                            if (data.command == "save") {
                                ProcessingChangeFolderOptions(oFO, oBM, sUrlA, -1, oBDE);
                            }
                        }).catch(() => { }).finally(() => { delete jsFloatMenu["BookmarkZipOptions"].meta; });
                    }
                    else {
                        oFO.nCompressType = 1;
                        jsFloatMenu["BookmarkEncOptions"].meta = oMeta;
                        CreateFloatMenu(jsFloatMenu["BookmarkEncOptions"], { width: "650px", top: "30%" }, oFO, { minWidth: "450px", minHeight: "200px" }).promise.then(data => {
                            oFO.sRepPasswd = oFO.sRawPasswd;
                            if (data.command == "save") {
                                ProcessingChangeFolderOptions(oFO, oBM, sUrlA, -1, oBDE);
                            }
                        }).catch(() => { }).finally(() => { delete jsFloatMenu["BookmarkEncOptions"].meta; });
                    }
                    return;
                }
                oData.bIgnoreBookmark = false;
            }
            break;
    }
    if ("fOpenFolder" in oBDE.Branch) {
        oBDE.Branch.fClear();
        oBDE.Branch.fOpenFolder(oBDE.Branch, oBDE.DTP, sFolderName);
    }
    else if ("fOpenFolder" in oBDE.DTP) {
        oBDE.Branch.fClear();
        oBDE.DTP.fOpenFolder(oBDE.Branch, oBDE.DTP, sFolderName);
    }
}
function FolderAndFileInfoProcessing(oInfo) {
    if (!oInfo) {
        return null;
    }
    const oSize = ConvertBytes(oInfo.size);
    const ret = {
        "dwBitAttrs": oInfo.dwBitAttrs,
        "dwAbilities": oInfo.dwAbilities,
        "tCre_s": GetDTString(oInfo.tCre_s),
        "tMod_s": GetDTString(oInfo.tMod_s),
        "sSize": RoundTo3Digits(oSize.nSpace1) + " " + oSize.unit,
        "eObjectType": oInfo.bIsLink ? (oInfo.bIsFile ? "link to file" : "link to folder") : (oInfo.bIsFile ? "file" : "folder")
    };
    if (oInfo.sNameA) {
        ret.sNameA = oInfo.sNameA;
    }
    if (oInfo.sDisplayName) {
        ret.sDisplayName = oInfo.sDisplayName;
    }
    if (oInfo.sComment) {
        ret.sComment = oInfo.sComment;
    }
    if (oInfo.sErr) {
        ret.sErr = oInfo.sErr;
    }
    return ret;
}
function OnChangeBDT(el, oMenu) {
    if (!oMenu)
        return;
    const domSaveBtn = document.getElementById("save_btn_" + oMenu.id);
    if (domSaveBtn) {
        domSaveBtn.disabled = oMenu.blockSaveBtmMap.size > 0;
    }
    const domTestBtn = document.getElementById("test_btn_" + oMenu.id);
    if (domTestBtn) {
        domTestBtn.disabled = false;
    }
}
function GetFormForCodeEnter(sPrompt, bSms) {
    const aCont = [
        { type: "text", title: sPrompt, id: "prompt" },
        { type: "textfield", title: "", value: "s2FACode", },
    ];
    if (bSms) {
        aCont.push({ type: "button", title: "Btn_SendSms", command: "Request2FaSms", value: "conn" });
    }
    return { title: "Title_CodeFor2FA",
        bottom_box: [
            { title: "Btn_Send", close: true, "command": "save", default: true },
            { title: "Btn_Cancel", close: true, }
        ], cont: [
            { title: "", cont: aCont }
        ]
    };
}
function Request2FaSms(sId, conn) {
    return __awaiter(this, void 0, void 0, function* () {
        const domPrompt = document.getElementById("prompt_" + sId);
        try {
            const oTwoFactor = yield AsyncUnicSendRecivePostApiWithRetry("StartTwoFactorAuth", { "conn": conn, "channel": "sms" });
            if (domPrompt) {
                domPrompt.innerHTML = oTwoFactor.prompt;
            }
        }
        catch (oErr) {
            if (oErr && oErr.error && oErr.error.message) {
                SetDomDisplayAndInnerHtml(domPrompt, "", { text: oErr.error.message, class: "job_errors", img: "error" });
            }
            else {
                SetDomDisplayAndInnerHtml(domPrompt, "", { text: GetLocaleText("Str_AuthSmthngWntWrng"), class: "job_errors", img: "error" });
            }
        }
    });
}
function Send2FACode(obj2FACode, sPrompt) {
    return __awaiter(this, void 0, void 0, function* () {
        const bSms = obj2FACode.conn.sUrlA.startsWith("icloud://");
        const oMenu = CreateFloatMenu(GetFormForCodeEnter(sPrompt, bSms), { width: "400px", top: "30%" }, obj2FACode);
        try {
            yield oMenu.promise;
            yield AsyncUnicSendRecivePostApiWithRetry("CompleteTwoFactorAuth", { "conn": obj2FACode.conn, "code": obj2FACode.s2FACode });
            return;
        }
        catch (oErr) {
            if (oErr && oErr.error) {
                if (oErr.error.data && oErr.error.data.error_str == "needs_custom_gui_auth") {
                    try {
                        yield Send2FACode(obj2FACode, oErr.error.message);
                        return;
                    }
                    catch (_a) { }
                }
                else if (oErr.error.message) {
                    HtmlErrBox(oErr.error.message, GetLocaleText("Err_AccountCreationError"));
                }
                else {
                    HtmlErrBox(GetLocaleText("Str_AuthSmthngWntWrng"), GetLocaleText("Err_AccountCreationError"));
                }
            }
            else {
                HtmlErrBox(GetLocaleText("Str_AuthSmthngWntWrng"), GetLocaleText("Err_AccountCreationError"));
            }
        }
        throw null;
    });
}
function StartTwoFactorAuth(oConn) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const o2FARes = yield AsyncUnicSendRecivePostApiWithRetry("StartTwoFactorAuth", { "conn": oConn });
            const obj2FACode = { s2FACode: "", conn: oConn };
            yield Send2FACode(obj2FACode, o2FARes.prompt);
        }
        catch (oErr) {
            if (oErr && oErr.error && oErr.error.message) {
                HtmlErrBox(oErr.error.message, GetLocaleText("Err_AccountCreationError"));
            }
            throw null;
        }
    });
}
function SetRealURL(oConn, obj) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            if (IsFsGST(oConn.sUrlA) && IsServAddr(oConn.sUrlA) || !IsFsGST(oConn.sUrlA) && (!obj.bContServList || !obj.bHasNoServAddr)) {
                return oConn;
            }
            const data = yield AsyncUnicSendRecivePostApiWithRetry("ListServers", { "conn": oConn });
            if (data.servers && data.servers.length > 0) {
                if (IsFsGST(oConn.sUrlA)) {
                    data.out_conn.sUrlA = obj.sFsName + data.out_conn.sUserIdA + ".goodsync";
                    return data.out_conn;
                }
                else {
                    oConn.sUrlA = data.servers[0].sUrlA;
                    return oConn;
                }
            }
            else {
                throw null;
            }
        }
        catch (oErr) {
            if (oErr && oErr.error && oErr.error.data && oErr.error.data.error_str == "needs_custom_gui_auth") {
                try {
                    yield StartTwoFactorAuth(oConn);
                    return oConn;
                }
                catch (oErr2) {
                    throw oErr2;
                }
            }
            else {
                throw oErr;
            }
        }
    });
}
function ChangeWaitBox(id, bSet) {
    const dom = document.getElementById(id);
    if (dom) {
        if (bSet) {
            dom.classList.add("waiting_box");
        }
        else {
            dom.classList.remove("waiting_box");
        }
    }
    return dom;
}
function CreateAccWithCheck(oConn, bListServ, pMenu, sHomePath, oDTE, jsAccData) {
    return __awaiter(this, void 0, void 0, function* () {
        let sKey = "";
        if (jsAccData && jsAccData.Key) {
            sKey = jsAccData.Key;
        }
        try {
            if (bListServ) {
                yield AsyncUnicSendRecivePostApiWithRetry("ListServers", { "conn": oConn });
            }
            else {
                yield AsyncUnicSendRecivePostApiWithRetry("ConnectFS", { "folder_coords": { "conn": oConn, "sAcctKeyA": sKey } });
            }
            yield CreateAccountRequest(oConn, sHomePath, oDTE, { pMenu, jsAccData });
        }
        catch (oErr) {
            if (oErr && oErr.error) {
                if (oErr.error.data && oErr.error.data.error_str == "needs_custom_gui_auth") {
                    try {
                        yield StartTwoFactorAuth(oConn);
                        yield CreateAccountRequest(oConn, sHomePath, oDTE, { pMenu, jsAccData });
                    }
                    catch (oErr2) {
                        if (oErr2 && oErr2.error && oErr2.error.message) {
                            HtmlErrBox(oErr2.error.message, GetLocaleText("Err_AccountCreationError"));
                        }
                        CloseFloatMenu(pMenu);
                    }
                }
                else if (oErr.error.data && oErr.error.data.error_str == "auth_rejected") {
                    HtmlErrBox(oErr.error.message, GetLocaleText("Err_AccountCreationError"));
                    if (pMenu) {
                        ChangeWaitBox("test_results_" + pMenu.id);
                    }
                }
                else {
                    if (oErr.error.message) {
                        HtmlErrBox(oErr.error.message, GetLocaleText("Err_AccountCreationError"));
                    }
                    CloseFloatMenu(pMenu);
                }
            }
        }
    });
}
function CreateAccRealUrlGetting(oConnBefore, sHomePath, oBDE, obj, pMenu, jsAccData) {
    SetRealURL(oConnBefore, obj).then(oConnAfter => {
        if (obj.bAuthOauth2) {
            CreateAccountRequest(oConnAfter, sHomePath, oBDE, { pMenu, jsAccData });
        }
        else if (IsFsGST(oConnAfter.sUrlA) && (!IsServAddr(oConnAfter.sUrlA) || oConnAfter.sUrlA.endsWith(":\/\/" + oConnAfter.sUserIdA + ".goodsync"))) {
            CreateAccWithCheck(oConnAfter, true, pMenu, sHomePath, oBDE, jsAccData);
        }
        else {
            CreateAccWithCheck(oConnAfter, false, pMenu, sHomePath, oBDE, jsAccData);
        }
    }).catch((oErr) => {
        if (oErr) {
            HtmlErrBox(oErr.error.message, GetLocaleText("Err_AccountCreationError"));
        }
        CloseFloatMenu(pMenu);
    });
}
function AccTestWithServList(oConn, obj, sId, domPlace) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const oData = yield AsyncUnicSendRecivePostApiWithRetry("ListServers", { "conn": oConn });
            HtmlMsgbox(GetLocaleText("Browse_Account_TestSuccess"), "", { class: "short_message" });
            obj.conn = oData.out_conn;
            if (IsFsGST(obj.sFsName)) {
                obj.conn.sUrlA = obj.sFsName + obj.conn.sUserIdA + ".goodsync";
            }
            if (domPlace) {
                domPlace.classList.remove("waiting_box");
                if (oData.servers && oData.servers.length > 0) {
                    domPlace.innerHTML = oData.servers.map(server => server.sUrlA).join('<br/>');
                }
                else {
                    domPlace.innerHTML = "";
                }
            }
            if (oData.servers && oData.servers.length > 0) {
                const domTestBtn = document.getElementById("test_btn_" + sId);
                if (domTestBtn) {
                    domTestBtn.disabled = true;
                }
            }
        }
        catch (oErr) {
            if (oErr && oErr.error) {
                if (oErr.error.data && oErr.error.data.error_str == "needs_custom_gui_auth") {
                    try {
                        yield StartTwoFactorAuth(oConn);
                        yield AccTestWithServList(oConn, obj, sId, domPlace);
                    }
                    catch (_a) {
                        SetDomDisplayAndInnerHtml(domPlace, "", { delClass: "waiting_box" });
                    }
                }
                else if (domPlace && oErr.error.message) {
                    domPlace.classList.remove("waiting_box");
                    domPlace.innerHTML = "<span class='term_error_cell'>" + oErr.error.message + "</span>";
                }
            }
        }
    });
}
function AccTestWithConnectFs(oConn, obj, sId, domPlace) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const data = yield AsyncUnicSendRecivePostApiWithRetry("ConnectFS", { "folder_coords": { "conn": obj.conn, "sAcctKeyA": "" } });
            const data2 = yield AsyncUnicSendRecivePostApiWithRetry("ListDir", { "filesys_handle": data.filesys_handle, "path": obj.sHomePath, "max_items": 1000 });
            HtmlMsgbox(GetLocaleText("Browse_Account_TestSuccess"), "", { class: "short_message" });
            if (domPlace) {
                domPlace.classList.remove("waiting_box");
                let sResults = "";
                if (data2.items && data2.items.length > 0) {
                    for (const it of data2.items) {
                        let img = "<span style='display: inline-block; min-width:1.25rem'>&nbsp;</span>";
                        if (it.bIsFolder) {
                            if (it.bIsLink) {
                                img = DynamicSvg.folder_link + "<span style='display: inline-block; min-width:0.25rem'>&nbsp;</span>";
                            }
                            else {
                                img = DynamicSvg.folder + "<span style='display: inline-block; min-width:0.25rem'>&nbsp;</span>";
                            }
                        }
                        let s = it.sDisplayName;
                        if (!s)
                            s = it.sNameA;
                        if (s)
                            sResults += "<div class='line_for_acc_create_dialog'>" + img + s + "</div>";
                    }
                }
                if (sResults) {
                    domPlace.innerHTML = GetLocaleText("Browse_Account_TestResults") + "<div class='folders_for_acc_create_dialog'>" + sResults + "</div>";
                }
                else {
                    domPlace.innerHTML = GetLocaleText("Browse_Account_TestResults") + " " + GetLocaleText("Str_FolderIsEmpty");
                }
                SetStretchEl();
            }
            const domTestBtn = document.getElementById("test_btn_" + sId);
            if (domTestBtn) {
                domTestBtn.disabled = true;
            }
        }
        catch (oErr) {
            if (oErr && oErr.error) {
                if (oErr.error.data && oErr.error.data.error_str == "needs_custom_gui_auth") {
                    yield StartTwoFactorAuth(oConn);
                    yield AccTestWithConnectFs(oConn, obj, sId, domPlace);
                }
                else {
                    if (oErr.error.message) {
                        if (domPlace) {
                            domPlace.classList.remove("waiting_box");
                            domPlace.innerHTML = "<span class='term_error_cell'>" + oErr.error.message + "</span>";
                        }
                    }
                }
            }
        }
    });
}
function UniversalTest(sId, obj) {
    return __awaiter(this, void 0, void 0, function* () {
        const domPlace = ChangeWaitBox("test_results_" + sId, true);
        SetUrlA(obj, obj.sFsName);
        SetSameObjFields(obj, obj.conn);
        try {
            if (obj.sPassword) {
                obj.conn.sPasswordEncMasterA = yield EncryptStringWithKey(obj.sPassword, oWebGuSettings.key, oWebGuSettings.iv);
            }
            if (obj.sPrivateKey) {
                obj.conn.sPrivateKeyEncMasterA = yield EncryptStringWithKey(obj.sPrivateKey, oWebGuSettings.key, oWebGuSettings.iv);
            }
            const oConnAfter = yield SetRealURL(obj.conn, obj);
            if (IsFsGST(oConnAfter.sUrlA) && (!IsServAddr(oConnAfter.sUrlA) || oConnAfter.sUrlA.endsWith(":\/\/" + oConnAfter.sUserIdA + ".goodsync"))) {
                AccTestWithServList(oConnAfter, obj, sId, domPlace);
            }
            else {
                AccTestWithConnectFs(oConnAfter, obj, sId, domPlace);
            }
        }
        catch (oErr) {
            if (oErr && oErr.error && oErr.error.message) {
                HtmlErrBox(oErr.error.message, GetLocaleText("Err_AccountCreationError"));
            }
            SetDomDisplayAndInnerHtml(domPlace, "", { delClass: "waiting_box" });
        }
    });
}
function SetUrlA(obj, sFileSystem) {
    if (!obj.conn)
        return;
    if (obj.bSecureConn && sFileSystem != "ftps://" && sFileSystem != "https://") {
        sFileSystem = sFileSystem.slice(0, -3) + "s://";
    }
    if (IsFsGST(sFileSystem) && !obj.sUrl && obj.sUserIdA && obj.sUserIdA.endsWith("@siber.com")) {
        const sTmp = obj.sUserIdA.replaceAll("@siber.com", "-siber-com");
        obj.sUserEmailA = obj.sUserIdA;
        obj.sUserIdA = sTmp;
        obj.sUrlA = sFileSystem + sTmp + ".goodsync";
        return;
    }
    if ("sUrl" in obj && (typeof obj.sUrl === 'string')) {
        obj.conn.sUrlA = sFileSystem + CutProtocol(obj.sUrl);
    }
    else if (!obj.conn.sUrlA) {
        obj.conn.sUrlA = sFileSystem;
    }
    const url = ParseUrl(obj.conn.sUrlA);
    obj.conn.sUrlA = url.protocol + url.hostname + url.port;
    if (!obj.sHomePath) {
        obj.sHomePath = url.pathname;
    }
    else {
        obj.sHomePath = NormalizePath(obj.sHomePath);
        if (!obj.sHomePath.startsWith("\/")) {
            obj.sHomePath = "\/" + obj.sHomePath;
        }
    }
}
function CreateNewAccount(oDTE) {
    return __awaiter(this, void 0, void 0, function* () {
        const oData = oDTE.Branch.fGetData();
        const oCreateAccData = GetAccCreateDialog(GetFieldValWithDrillUp(oDTE.Branch, "sFs"));
        oCreateAccData.js.bottom_box[0].command = "SaveAccount";
        oCreateAccData.obj.bContServList = oData.bContServList;
        oCreateAccData.obj.bHasNoServAddr = oData.bHasNoServAddr;
        oCreateAccData.obj.bUserIdInHostname = oData.bUserIdInHostname;
        oCreateAccData.obj.bAuthOauth2 = oData.bAuthOauth2;
        oCreateAccData.obj.conn = new TConn;
        if (!oCreateAccData.js.title) {
            alert("For this FS has not created an account form yet");
            return;
        }
        const oCreateAccMenu = CreateFloatMenu(oCreateAccData.js, { width: "550px", height: -80 }, { "obj": oCreateAccData.obj }, { fontSize: "16px", fOnChangeFM: OnChangeBDT, minWidth: "30rem", minHeight: "20rem", icon: oCreateAccData.icon, xArgs: oDTE });
        oCreateAccMenu.promise.then(() => { }).catch(() => { });
    });
}
function SaveFromShowAccount(oMenu) {
    return __awaiter(this, void 0, void 0, function* () {
        const jsAccData = oMenu.xArgs.accData;
        if (!jsAccData)
            return;
        const obj = oMenu.jsFloatMenuDescr.obj;
        SetUrlA(obj, obj.sFsName);
        SetSameObjFields(obj, jsAccData.AcctConn);
        jsAccData.HomePath = obj.sHomePath ? obj.sHomePath : "";
        jsAccData.DisplayName = obj.DisplayNameA;
        try {
            if (obj.sPassword) {
                obj.conn.sPasswordEncMasterA = yield EncryptStringWithKey(obj.sPassword, oWebGuSettings.key, oWebGuSettings.iv);
            }
            if (obj.sPrivateKey) {
                obj.conn.sPrivateKeyEncMasterA = yield EncryptStringWithKey(obj.sPrivateKey, oWebGuSettings.key, oWebGuSettings.iv);
            }
            CreateAccRealUrlGetting(obj.conn, jsAccData.HomePath, oMenu.xArgs.bde, obj, oMenu, jsAccData);
        }
        catch (oErr) {
            CloseFloatMenu(oMenu);
        }
    });
}
function SaveAccount(oMenu) {
    return __awaiter(this, void 0, void 0, function* () {
        const oDTE = oMenu.xArgs;
        if (!oDTE)
            return;
        const domUrl = document.getElementById("require_url_" + oMenu.id);
        if (domUrl && !domUrl.value) {
            domUrl.style.border = "solid 1px red";
            return;
        }
        const domPlace = document.getElementById("test_results_" + oMenu.id);
        SetWaitingBox(domPlace, GetLocaleText("Str_AccountCreating"));
        const obj = oMenu.jsFloatMenuDescr.obj;
        SetUrlA(obj, GetFieldValWithDrillUp(oDTE.Branch, "sFs"));
        SetSameObjFields(obj, obj.conn);
        try {
            yield ListAccForExplorerRequest(null, oDTE);
        }
        catch (_a) { }
        try {
            if (obj.sPassword) {
                obj.conn.sPasswordEncMasterA = yield EncryptStringWithKey(obj.sPassword, oWebGuSettings.key, oWebGuSettings.iv);
            }
            if (obj.sPrivateKey) {
                obj.conn.sPrivateKeyEncMasterA = yield EncryptStringWithKey(obj.sPrivateKey, oWebGuSettings.key, oWebGuSettings.iv);
            }
            for (const oAcc of oDTE.Branch.jsBody) {
                if (CompareAcc(obj, oAcc)) {
                    ChangeWaitBox("test_results_" + oMenu.id);
                    HtmlErrBox(GetLocaleText("Str_Msg_CannotCreateAccount", [oAcc.display_name]), GetLocaleText("Title_Error"), { bNoCurrJobName: true });
                    return;
                }
            }
            CreateAccRealUrlGetting(obj.conn, obj.sHomePath ? obj.sHomePath : "", oDTE, obj, oMenu);
        }
        catch (_b) {
            CloseFloatMenu(oMenu);
        }
    });
}
function CompareAcc(acc1, acc2) {
    const sHomePath1 = acc1.sHomePath ? acc1.sHomePath.toLowerCase() : "";
    const sHomePath2 = acc2.sHomePath ? acc2.sHomePath.toLowerCase() : "";
    const sPass1 = acc1.conn ? acc1.conn.sPasswordEncMasterA : "";
    const sPass2 = acc2.oConn ? acc2.oConn.sPasswordEncMasterA : "";
    const sPrivKey1 = acc1.conn ? acc1.conn.sPrivateKeyEncMasterA : "";
    const sPrivKey2 = acc2.oConn ? acc2.oConn.sPrivateKeyEncMasterA : "";
    if (sHomePath1 !== sHomePath2 || sPass1 !== sPass2 || sPrivKey1 !== sPrivKey2)
        return false;
    for (const key of Object.keys(acc1.conn)) {
        if ((key in acc2.oConn) && (key in acc1) && acc1.conn[key] !== acc2.oConn[key])
            return false;
    }
    return true;
}
function ShowAccount(sFileSystem, jsAccData, oBDE) {
    return __awaiter(this, void 0, void 0, function* () {
        const oCreateAccData = GetAccCreateDialog(sFileSystem);
        oCreateAccData.js.bottom_box[0].command = "SaveFromShowAccount";
        oCreateAccData.obj.conn = jsAccData.AcctConn;
        if (!oCreateAccData.js.title) {
            alert("For this FS has not created an account form yet");
            return;
        }
        SetSameObjFields(jsAccData.AcctConn, oCreateAccData.obj);
        if ("sUrl" in oCreateAccData.obj && jsAccData.AcctConn.sUrlA) {
            oCreateAccData.obj.sUrl = jsAccData.AcctConn.sUrlA;
            if (jsAccData.AcctConn.sUrlA.startsWith("ftps://") || jsAccData.AcctConn.sUrlA.startsWith("https://")) {
                oCreateAccData.obj.bSecureConn = true;
            }
        }
        try {
            if (jsAccData.AcctConn.sPasswordEncMasterA) {
                oCreateAccData.obj.sPassword = yield DecryptStringWithKey(jsAccData.AcctConn.sPasswordEncMasterA, oWebGuSettings.key, oWebGuSettings.iv);
            }
            if ("sPrivateKey" in oCreateAccData.obj && jsAccData.AcctConn.sPrivateKeyEncMasterA) {
                oCreateAccData.obj.sPrivateKey = yield DecryptStringWithKey(jsAccData.AcctConn.sPrivateKeyEncMasterA, oWebGuSettings.key, oWebGuSettings.iv);
            }
            oCreateAccData.obj.sFsName = sFileSystem;
            oCreateAccData.obj.DisplayNameA = jsAccData.DisplayName ? jsAccData.DisplayName :
                jsAccData.AcctConn.sDisplayNameA ? jsAccData.AcctConn.sDisplayNameA :
                    jsAccData.AcctConn.sUserIdA ? jsAccData.AcctConn.sUserIdA : jsAccData.AcctConn.sUserEmailA;
            oCreateAccData.obj.sHomePath = jsAccData.HomePath;
            oCreateAccData.obj.AccKey = jsAccData.Key;
            oCreateAccData.obj.Timestamp = jsAccData.Timestamp;
            oCreateAccData.obj.sUrl = (jsAccData.AcctConn.sUrlA.indexOf(sFileSystem) === 0) ? jsAccData.AcctConn.sUrlA.substring(sFileSystem.length) : jsAccData.AcctConn.sUrlA;
            oCreateAccData.obj.UrlB = jsAccData.AcctConn.sUrlA;
            oCreateAccData.js.cont[0].cont.push({ type: "hidden_group", title: "Account Details", cont: oCreateAccData.add, class: "float_menu_hidden_group_body acc_details_group" });
            const oShowAccMenu = CreateFloatMenu(oCreateAccData.js, { width: "550px", height: -80 }, { "obj": oCreateAccData.obj }, {
                fontSize: "16px",
                fOnChangeFM: OnChangeBDT,
                minWidth: "30rem",
                minHeight: "20rem",
                icon: oCreateAccData.icon,
                xArgs: { accData: jsAccData, bde: oBDE }
            });
            oShowAccMenu.promise.then(() => { }).catch(() => { });
        }
        catch (oErr) {
        }
    });
}
function DeleteAccount(xAddArgs) {
    if (IsAccReadOnly(xAddArgs))
        return;
    const oData = xAddArgs.Branch.fGetData();
    let sAccName = oData.sUrl + oData.sHomePath;
    if (oData.display_name) {
        sAccName = oData.display_name + " (" + sAccName + ") ";
    }
    HtmlConfirm(GetLocaleText("Str_AskDeleteAccount", [sAccName]), "", 1, { sFontSize: "16px", bNoCurrJobName: true })
        .then(() => {
        DelteAccountRequest(xAddArgs.Branch.fGetData().sAccKey, xAddArgs);
    }).catch(() => { });
}
function OAuth2Connect(sId, obj) {
    if (obj.sUrlA) {
        SetSameObjFields(obj, obj.conn);
        OAuth2ConnectRequest(obj.conn);
        oOAuth2.SetAuthFormId(sId);
    }
}
function GetAccCreateDialog(sFileSystem) {
    const jsCredentials = { title: "", cont: [], bottom_box: [
            { title: "Btn_Save", id: "save_btn", default: true, nofinal: true },
            { title: "Btn_Cancel", close: true, },
        ] };
    let oCreateAccDialogh = {};
    let aAccDetales = [
        { type: "textfield", title: "Browse_Str_Account_Name", value: "obj['DisplayNameA']", readOnly: true, title_width: "160px", el_class: "acc_delails" },
        { type: "textfield", title: "Browse_Account_Key", value: "obj['AccKey']", readOnly: true, title_width: "160px", el_class: "acc_delails" },
        { type: "textfield", title: "Browse_Account_URL", value: "obj['UrlB']", readOnly: true, title_width: "160px", el_class: "acc_delails" },
        { type: "textfield", title: "Browse_Str_Account_ModTime", value: "obj['Timestamp']", readOnly: true, title_width: "160px", el_class: "acc_delails", time: true },
    ];
    let icon = "";
    switch (sFileSystem) {
        case "afpd://":
        case "smb://":
        case "smbd://":
            {
                jsCredentials.title = GetLocaleText("Title_NewAccount", ["Net Shares (" + sFileSystem + ")"]);
                jsCredentials.cont = [
                    { title: "", cont: [
                            { type: "text", title: "Browse_Account_ServerAddress", class: "text_above_field" },
                            { type: "textfield", title: "", value: "obj['sUrl']", id: "require_url", non_empty: true },
                            { type: "text", title: "Browse_Account_ShareName", class: "text_above_field" },
                            { type: "textfield", title: "", value: "obj['sHomePath']", optional: true },
                            { type: "option_group", title: "Browse_Account_Credentials", cont: [
                                    { type: "text", title: "Browse_Account_UserID", class: "text_above_field" },
                                    { type: "textfield", title: "", value: "obj['sUserIdA']", id: "require_user_id", non_empty: true, },
                                    { type: "text", title: "Browse_Account_Password", class: "text_above_field" },
                                    { type: "password", title: "", value: "obj['sPassword']", },
                                ] },
                            { type: "row", "h": "15px", cont: [] },
                            { type: "button", title: "test", command: "UniversalTest", value: "obj", id: "test_btn" },
                            { type: "place", title: "Test Results", id: "test_results" },
                        ] }
                ];
                oCreateAccDialogh = { sUrl: "", sHomePath: "", sUserIdA: "", sPassword: "" };
                icon = (sFileSystem == "afpd://") ? "fs_sibafp" : (sFileSystem == "smbd://") ? "fs_smbd" : "fs_winnet";
            }
            break;
        case "gstps://":
            {
                jsCredentials.title = GetLocaleText("Title_NewAccount", ["GoodSync Connect"]);
                jsCredentials.cont = [
                    { title: "", cont: [
                            { type: "option_group", title: "Browse_Account_Credentials", cont: [
                                    { type: "text", title: "Browse_Account_Email", class: "text_above_field" },
                                    { type: "textfield", title: "", value: "obj['sUserIdA']", },
                                    { type: "text", title: "Browse_Account_Password", class: "text_above_field" },
                                    { type: "password", title: "", value: "obj['sPassword']", },
                                ] },
                            { type: "row", "h": "15px", cont: [] },
                            { type: "button", title: "test", command: "UniversalTest", value: "obj", id: "test_btn" },
                            { type: "place", title: "Test Results", id: "test_results" },
                            { type: "hidden_group", title: "Advanced Options", cont: [
                                    { type: "textfield", title: "Browse_Str_DirectGstp", value: "obj['sUrl']", title_width_group: "2" },
                                    { type: "checkbox", title: "Browse_Str_GstpPlainDirect", value: "obj['bGstpPlainDirect']" },
                                    { type: "textfield", title: "Browse_Str_ClientCert", value: "obj['sPrivateKeyPath']", title_width_group: "2" },
                                    { type: "checkbox", title: "Browse_Str_Use_Proxy", value: "obj['bUseProxy']" },
                                ] },
                        ] }
                ];
                oCreateAccDialogh = { sUserIdA: "", sPassword: "", sUrl: "", sPrivateKeyPath: "", bGstpPlainDirect: false, bUseProxy: true };
                icon = "fs_gstp";
            }
            break;
        case "gstore://":
            {
                jsCredentials.title = GetLocaleText("Title_NewAccount", ["GoodSync Storage"]);
                jsCredentials.cont = [
                    { title: "", cont: [
                            { type: "option_group", title: "Browse_Account_Credentials", cont: [
                                    { type: "text", title: "Browse_Account_Email", class: "text_above_field" },
                                    { type: "textfield", title: "", value: "obj['sUserIdA']", },
                                    { type: "text", title: "Browse_Account_Password", class: "text_above_field" },
                                    { type: "password", title: "", value: "obj['sPassword']", },
                                ] },
                            { type: "row", "h": "15px", cont: [] },
                            { type: "button", title: "test", command: "UniversalTest", value: "obj", id: "test_btn" },
                            { type: "place", title: "Test Results", id: "test_results", class: "test_account_results" },
                        ] }
                ];
                oCreateAccDialogh = { sUserIdA: "", sPassword: "" };
                icon = "fs_gstp";
            }
            break;
        case "ftps://":
        case "ftp://":
            {
                jsCredentials.title = GetLocaleText("Title_NewAccount", ["FTP"]);
                jsCredentials.cont = [
                    { title: "", cont: [
                            { type: "text", title: "Browse_Short_Tip_FTP" },
                            { type: "text", title: "Browse_Account_ServerAddress", class: "text_above_field" },
                            { type: "textfield", title: "", value: "obj['sUrl']" },
                            { type: "text", title: "Browse_Account_HomeFolder", class: "text_above_field" },
                            { type: "textfield", title: "", value: "obj['sHomePath']", optional: true },
                            { type: "option_group", title: "Browse_Account_Credentials", cont: [
                                    { type: "text", title: "Browse_Account_UserID", class: "text_above_field" },
                                    { type: "textfield", title: "", value: "obj['sUserIdA']", },
                                    { type: "text", title: "Browse_Account_Password", class: "text_above_field" },
                                    { type: "password", title: "", value: "obj['sPassword']", },
                                    { type: "checkbox", title: "Str_SSL_SecureConnection", value: "obj['bSecureConn']" },
                                ] },
                            { type: "button", title: "test", command: "UniversalTest", value: "obj", id: "test_btn" },
                            { type: "place", title: "Test Results", id: "test_results", class: "test_account_results" },
                            { type: "hidden_group", title: "Advanced Options", cont: [
                                    { type: "checkbox", title: "Browse_Str_UTF8_encoding", value: "obj['bEncodeUTF8']" },
                                    { type: "checkbox", title: "Browse_Str_Use_Proxy", value: "obj['bUseProxy']" },
                                    { type: "checkbox", title: "Browse_Str_IgnoreBadCerts", value: "obj['bIgnoreBadCerts']" },
                                    { type: "checkbox", title: "Browse_Str_ActiveMode", value: "obj['bActiveMode']" },
                                    { type: "checkbox", title: "Browse_Str_UseEPSV_FTP", value: "obj['bUseEPSV']" },
                                    { type: "checkbox", title: "Browse_Str_ImplicitMode", value: "obj['bImplicitMode']" },
                                    { type: "checkbox", title: "Browse_Str_UseMDTM_FTP", value: "obj['bUseMDTM']" },
                                    { type: "checkbox", title: "Browse_Str_UseMLSD_FTP", value: "obj['bUseMLSD']" },
                                    { type: "checkbox", title: "Browse_Str_FtpListLa", value: "obj['bUseListLA']" },
                                    { type: "checkbox", title: "Browse_Str_MoveLevelOnly", value: "obj['bMoveLevelOnly']" },
                                    { type: "checkbox", title: "Browse_Str_SessionReuse", value: "obj['bDataConnSessionReuse']" },
                                ] },
                        ] }
                ];
                oCreateAccDialogh = { sUserIdA: "", sPassword: "", sHomePath: "", sUrl: "", bSecureConn: false,
                    bEncodeUTF8: true, bUseProxy: true, bIgnoreBadCerts: false, bActiveMode: false, bUseEPSV: false, bImplicitMode: false,
                    bUseMDTM: false, bUseMLSD: true, bUseListLA: false, bMoveLevelOnly: false, bDataConnSessionReuse: true
                };
                icon = "fs_sftp";
            }
            break;
        case "sftp://":
            {
                jsCredentials.title = GetLocaleText("Title_NewAccount", ["SFTP"]);
                jsCredentials.cont = [
                    { title: "", cont: [
                            { type: "text", title: "Browse_Short_Tip_SecureFTP" },
                            { type: "text", title: "Browse_Account_ServerAddress", class: "text_above_field" },
                            { type: "textfield", title: "", value: "obj['sUrl']" },
                            { type: "text", title: "Browse_Account_HomeFolder", class: "text_above_field" },
                            { type: "textfield", title: "", value: "obj['sHomePath']", optional: true },
                            { type: "option_group", title: "Browse_Account_Credentials", cont: [
                                    { type: "text", title: "Browse_Account_UserID", class: "text_above_field" },
                                    { type: "textfield", title: "", value: "obj['sUserIdA']", },
                                    { type: "text", title: "Browse_Str_SecureFTP_Passwd", class: "text_above_field" },
                                    { type: "password", title: "", value: "obj['sPassword']", },
                                    { type: "text", title: "Browse_Str_PrivKey", class: "text_above_field" },
                                    { type: "textarea", title: "Browse_Str_PrivKey", value: "obj['sPrivateKey']", id: "private_key" },
                                    { type: "fileload", title: "", command: "LoadTextToTextarea('private_key_' + oMenu.id, text)", value: "obj['sPrivateKey']" },
                                ] },
                            { type: "button", title: "test", command: "UniversalTest", value: "obj", id: "test_btn" },
                            { type: "place", title: "Test Results", id: "test_results", class: "test_account_results" },
                            { type: "hidden_group", title: "Advanced Options", cont: [
                                    { type: "checkbox", title: "Browse_Str_Use_Proxy", value: "obj['bUseProxy']" },
                                    { type: "checkbox", title: "Browse_Str_UTF8_encoding", value: "obj['bEncodeUTF8']" },
                                    { type: "checkbox", title: "Browse_Str_IgnoreHostKeys", value: "obj['bIgnoreBadCerts']" },
                                ] },
                        ] }
                ];
                oCreateAccDialogh = { sUserIdA: "", sPassword: "", sPrivateKey: "", sUrl: "", sHomePath: "", bEncodeUTF8: true, bUseProxy: true, bIgnoreBadCerts: false };
                icon = "fs_sftp";
            }
            break;
        case "s3s://":
            {
                jsCredentials.title = GetLocaleText("Title_NewAccount", ["Amazon S3"]);
                jsCredentials.cont = [
                    { title: "", cont: [
                            { type: "text", title: "Browse_Short_Tip_AmazonS3" },
                            { type: "text", title: "Browse_Account_ServerAddress", class: "text_above_field" },
                            { type: "textfield", title: "", value: "obj['sUrl']" },
                            { type: "text", title: "Browse_Account_S3_InitPath_Cap", class: "text_above_field" },
                            { type: "textfield", title: "", value: "obj['sHomePath']", optional: true },
                            { type: "option_group", title: "Browse_Account_Credentials", cont: [
                                    { type: "text", title: "Browse_Str_AmazonS3_UserID", class: "text_above_field" },
                                    { type: "textfield", title: "", value: "obj['sUserIdA']", },
                                    { type: "text", title: "Browse_Str_AmazonS3_Passwd", class: "text_above_field" },
                                    { type: "password", title: "", value: "obj['sPassword']", },
                                ] },
                            { type: "row", "h": "15px", cont: [] },
                            { type: "button", title: "test", command: "UniversalTest", value: "obj", id: "test_btn" },
                            { type: "place", title: "Test Results", id: "test_results", class: "test_account_results" },
                            { type: "hidden_group", title: "Advanced Options", cont: [
                                    { type: "checkbox", title: "Browse_Str_HostBasedAddr", value: "obj['bHostBasedAddr']" },
                                    { type: "checkbox", title: "Browse_Str_UsGovCloud", value: "obj['bUsGovCloud']" },
                                    { type: "droplist", title: "Browse_Str_S3StorageClass", value: "obj['sStorageClassA']", "list": aStorageClass, str: true },
                                    { type: "checkbox", title: "Browse_Str_RequireCheckSum", value: "obj['bRequireCheckSum']", class: "long_label" },
                                    { type: "checkbox", title: "Browse_Str_CacheFileModTime", value: "obj['bCacheFileModTime']" },
                                    { type: "numberfield", title: "Browse_Str_UploadChunksThreads", value: "obj['nUploadChunksThreads']" },
                                    { type: "droplist", title: "Browse_Str_GeoLocation", value: "obj['sGeoLocationA']", "list": aPreferredRegion, str: true },
                                    { type: "textfield", title: "Browse_Str_SpecifyACP", value: "obj['sAccessPolicyA']" },
                                    { type: "checkbox", title: "Browse_Str_ServerEncrypt", value: "obj['bServerSideEncryption']" },
                                    { type: "textfield", title: "Browse_Str_ServerEncrKey", value: "obj['sServerEncrKeyA']" },
                                ] },
                        ] }
                ];
                oCreateAccDialogh = { sUrl: "s3.amazonaws.com", sHomePath: "", sUserIdA: "", sPassword: "", nUploadChunksThreads: 5, sServerEncrKeyA: "", sAccessPolicyA: "",
                    sStorageClassA: "", sGeoLocationA: "",
                    bUsGovCloud: false, bHostBasedAddr: true, bRequireCheckSum: false, bCacheFileModTime: false, bServerSideEncryption: false };
                icon = "fs_s3";
            }
            break;
        case "gcp://":
            {
                jsCredentials.title = GetLocaleText("Title_NewAccount", ["Google Cloud Storage"]);
                jsCredentials.cont = [
                    { title: "", cont: [
                            { type: "text", title: "Browse_Tip_GCloudStor", class: "text_above_field" },
                            { type: "row", "h": "15px", cont: [] },
                            { type: "text", title: "Browse_Account_GCP_InitPath_Str", class: "text_above_field" },
                            { type: "textfield", title: "", value: "obj['sHomePath']", optional: true },
                            { type: "option_group", title: "Browse_Account_Authorization", cont: [
                                    { type: "text", title: "Browse_Account_OAuth_GoogleSignIn" },
                                    { type: "button", img: "google-logo", title: "Browse_Account_OAuth_GoogleSignInBtn", command: "Nothing", value: "obj", id: "connect_btn" },
                                    { type: "text", title: "Browse_Account_GCP_UserID_Str", class: "text_above_field" },
                                    { type: "textfield", title: "", value: "obj['sUserIdA']", },
                                    { type: "text", title: "Browse_Str_PrivKey", class: "text_above_field" },
                                    { type: "textarea", title: "Browse_Str_PrivKey", value: "obj['sPrivateKey']", id: "private_key" },
                                    { type: "fileload", title: "", command: "LoadTextToTextarea('private_key_' + oMenu.id, text)", value: "obj['sPrivateKey']" },
                                ] },
                            { type: "row", "h": "15px", cont: [] },
                            { type: "button", title: "test", command: "UniversalTest", value: "obj", id: "test_btn" },
                            { type: "place", title: "Test Results", id: "test_results", class: "test_account_results" },
                            { type: "hidden_group", title: "Advanced Options", cont: [
                                    { type: "textfield", title: "Browse_Str_GeoLocation", value: "obj['sGeoLocationA']" },
                                    { type: "numberfield", title: "Browse_Str_UploadChunksThreads", value: "obj['nUploadChunksThreads']" },
                                ] },
                        ] }
                ];
                oCreateAccDialogh = { sHomePath: "", sUserIdA: "", sPrivateKey: "", sGeoLocationA: "", nUploadChunksThreads: 5 };
                icon = "fs_gcloud";
            }
            break;
        case "gcs://":
            {
                jsCredentials.title = GetLocaleText("Title_NewAccount", ["Google Cloud via S3"]);
                jsCredentials.cont = [
                    { title: "", cont: [
                            { type: "text", title: "Browse_Short_Tip_GCloud_S3" },
                            { type: "text", title: "Browse_Account_S3_InitPath_Cap", class: "text_above_field" },
                            { type: "textfield", title: "", value: "obj['sHomePath']", optional: true },
                            { type: "option_group", title: "Browse_Account_Credentials", cont: [
                                    { type: "text", title: "Browse_Str_GCloud_S3_UserID", class: "text_above_field" },
                                    { type: "textfield", title: "", value: "obj['sUserIdA']", },
                                    { type: "text", title: "Browse_Str_GCloud_S3_Passwd", class: "text_above_field" },
                                    { type: "password", title: "", value: "obj['sPassword']", },
                                ] },
                            { type: "row", "h": "15px", cont: [] },
                            { type: "button", title: "test", command: "UniversalTest", value: "obj", id: "test_btn" },
                            { type: "place", title: "Test Results", id: "test_results", class: "test_account_results" },
                            { type: "hidden_group", title: "Advanced Options", cont: [
                                    { type: "textfield", title: "Browse_Str_GeoLocation", value: "obj['sGeoLocationA']" },
                                ] },
                        ] }
                ];
                oCreateAccDialogh = { sHomePath: "", sUserIdA: "", sPassword: "", sGeoLocationA: "" };
                icon = "fs_gcloud";
            }
            break;
        case "mega://":
            {
                jsCredentials.title = GetLocaleText("Title_NewAccount", ["MEGA"]);
                jsCredentials.cont = [
                    { title: "", cont: [
                            { type: "text", title: "Browse_Short_Tip_Mega" },
                            { type: "option_group", title: "Browse_Account_Credentials", cont: [
                                    { type: "text", title: "Browse_Str_Mega_UserID", class: "text_above_field" },
                                    { type: "textfield", title: "", value: "obj['sUserIdA']", },
                                    { type: "text", title: "Browse_Str_Mega_Passwd", class: "text_above_field" },
                                    { type: "password", title: "", value: "obj['sPassword']", },
                                ] },
                            { type: "row", "h": "15px", cont: [] },
                            { type: "button", title: "test", command: "UniversalTest", value: "obj", id: "test_btn" },
                            { type: "place", title: "Test Results", id: "test_results", class: "test_account_results" },
                        ] }
                ];
                oCreateAccDialogh = { sUserIdA: "myaccount", sPassword: "", sUrlA: "mega:\/\/g.api.mega.co.nz" };
                icon = "fs_mega";
            }
            break;
        case "azures://":
            {
                jsCredentials.title = GetLocaleText("Title_NewAccount", ["MS Azure Blobs"]);
                jsCredentials.cont = [
                    { title: "", cont: [
                            { type: "text", title: "Browse_Short_Tip_WindowsAzure" },
                            { type: "text", title: "Browse_Account_S3_InitPath_Cap", class: "text_above_field" },
                            { type: "textfield", title: "", value: "obj['sHomePath']", optional: true },
                            { type: "option_group", title: "Browse_Account_Credentials", cont: [
                                    { type: "text", title: "Browse_Str_WindowsAzure_UserID", class: "text_above_field" },
                                    { type: "textfield", title: "", value: "obj['sUserIdA']", },
                                    { type: "text", title: "Browse_Str_WindowsAzure_Passwd", class: "text_above_field" },
                                    { type: "password", title: "", value: "obj['sPassword']", },
                                ] },
                            { type: "row", "h": "15px", cont: [] },
                            { type: "button", title: "test", command: "UniversalTest", value: "obj", id: "test_btn" },
                            { type: "place", title: "Test Results", id: "test_results", class: "test_account_results" },
                            { type: "hidden_group", title: "Advanced Options", cont: [
                                    { type: "checkbox", title: "Browse_Str_UsGovCloud", value: "obj['bUsGovCloud']" },
                                    { type: "droplist", title: "Browse_Str_StorageClass", value: "obj['sStorageClassA']", "list": ["Default", "cold", "archive"], str: true },
                                    { type: "numberfield", title: "Browse_Str_UploadChunksThreads", value: "obj['nUploadChunksThreads']" },
                                ] },
                        ] }
                ];
                oCreateAccDialogh = { sHomePath: "", sUrlA: sFileSystem, sUserIdA: "", sPassword: "", sGeoLocationA: "", bUsGovCloud: false, sStorageClassA: "", nUploadChunksThreads: 5 };
                icon = "fs_azure";
            }
            break;
        case "azurefiles://":
            {
                jsCredentials.title = GetLocaleText("Title_NewAccount", ["MS Azure Files"]);
                jsCredentials.cont = [
                    { title: "", cont: [
                            { type: "text", title: "Browse_Short_Tip_AzureFiles" },
                            { type: "option_group", title: "Browse_Account_Credentials", cont: [
                                    { type: "text", title: "Browse_Str_WindowsAzure_UserID", class: "text_above_field" },
                                    { type: "textfield", title: "", value: "obj['sUserIdA']", },
                                    { type: "text", title: "Browse_Str_WindowsAzure_Passwd", class: "text_above_field" },
                                    { type: "password", title: "", value: "obj['sPassword']", },
                                ] },
                            { type: "row", "h": "15px", cont: [] },
                            { type: "button", title: "test", command: "UniversalTest", value: "obj", id: "test_btn" },
                            { type: "place", title: "Test Results", id: "test_results", class: "test_account_results" },
                            { type: "hidden_group", title: "Advanced Options", cont: [
                                    { type: "checkbox", title: "Browse_Str_UsGovCloud", value: "obj['bUsGovCloud']" },
                                ] },
                        ] }
                ];
                oCreateAccDialogh = { sUserIdA: "", sPassword: "", bUsGovCloud: false, sUrlA: sFileSystem };
                icon = "fs_azure";
            }
            break;
        case "pcloud://":
            {
                jsCredentials.title = GetLocaleText("Title_NewAccount", ["pCloud"]);
                jsCredentials.cont = [
                    { title: "", cont: [
                            { type: "text", title: "Browse_Short_Tip_pCloud" },
                            { type: "option_group", title: "Browse_Account_Credentials", cont: [
                                    { type: "text", title: "Browse_Account_Email", class: "text_above_field" },
                                    { type: "textfield", title: "", value: "obj['sUserIdA']", },
                                    { type: "text", title: "Browse_Account_Password", class: "text_above_field" },
                                    { type: "password", title: "", value: "obj['sPassword']", },
                                ] },
                            { type: "row", "h": "15px", cont: [] },
                            { type: "button", title: "test", command: "UniversalTest", value: "obj", id: "test_btn" },
                            { type: "place", title: "Test Results", id: "test_results", class: "test_account_results" },
                            { type: "hidden_group", title: "Advanced Options", cont: [
                                    { type: "numberfield", title: "Browse_Str_UploadChunksThreads", value: "obj['nUploadChunksThreads']" },
                                ] },
                        ] }
                ];
                oCreateAccDialogh = { sUserIdA: "", sPassword: "", nUploadChunksThreads: 5, sUrlA: "pcloud:\/\/pcloud.com" };
                icon = "fs_pcloud";
            }
            break;
        case "backblaze://":
            {
                jsCredentials.title = GetLocaleText("Title_NewAccount", ["Backblaze B2"]);
                jsCredentials.cont = [
                    { title: "", cont: [
                            { type: "text", title: "Browse_Short_Tip_Backblaze" },
                            { type: "option_group", title: "Browse_Account_Credentials", cont: [
                                    { type: "text", title: "Browse_Str_Backblaze_UserID", class: "text_above_field" },
                                    { type: "textfield", title: "", value: "obj['sUserIdA']", },
                                    { type: "text", title: "Browse_Str_Backblaze_Passwd", class: "text_above_field" },
                                    { type: "password", title: "", value: "obj['sPassword']", },
                                ] },
                            { type: "row", "h": "15px", cont: [] },
                            { type: "button", title: "test", command: "UniversalTest", value: "obj", id: "test_btn" },
                            { type: "place", title: "Test Results", id: "test_results", class: "test_account_results" },
                            { type: "hidden_group", title: "Advanced Options", cont: [
                                    { type: "numberfield", title: "Browse_Str_UploadChunksThreads", value: "obj['nUploadChunksThreads']" },
                                ] },
                        ] }
                ];
                oCreateAccDialogh = { sUserIdA: "", sPassword: "", nUploadChunksThreads: 5, sUrlA: sFileSystem };
                icon = "fs_backblaze";
            }
            break;
        case "https://":
        case "http://":
            {
                jsCredentials.title = GetLocaleText("Title_NewAccount", ["WebDAV"]);
                jsCredentials.cont = [
                    { title: "", cont: [
                            { type: "text", title: "Browse_Short_Tip_WebDav" },
                            { type: "text", title: "Browse_Account_ServerAddress", class: "text_above_field" },
                            { type: "textfield", title: "", value: "obj['sUrl']" },
                            { type: "text", title: "Browse_Account_DavRoot", class: "text_above_field" },
                            { type: "textfield", title: "", value: "obj['sHomePath']", optional: true },
                            { type: "option_group", title: "Browse_Account_Credentials", cont: [
                                    { type: "text", title: "Browse_Account_UserID", class: "text_above_field" },
                                    { type: "textfield", title: "", value: "obj['sUserIdA']", },
                                    { type: "text", title: "Browse_Account_Password", class: "text_above_field" },
                                    { type: "password", title: "", value: "obj['sPassword']", },
                                    { type: "checkbox", title: "Str_SSL_SecureConnection", value: "obj['bSecureConn']" },
                                ] },
                            { type: "row", "h": "15px", cont: [] },
                            { type: "button", title: "test", command: "UniversalTest", value: "obj", id: "test_btn" },
                            { type: "place", title: "Test Results", id: "test_results", class: "test_account_results" },
                            { type: "hidden_group", title: "Advanced Options", cont: [
                                    { type: "textfield", title: "Browse_Str_ClientCert", value: "obj['sPrivateKeyPath']" },
                                    { type: "checkbox", title: "Browse_Str_WinInet", value: "obj['bWinInet']" },
                                    { type: "checkbox", title: "Browse_Str_Use_Proxy", value: "obj['bUseProxy']" },
                                    { type: "checkbox", title: "Browse_Str_UTF8_encoding", value: "obj['bEncodeUTF8']" },
                                    { type: "checkbox", title: "Browse_Str_IgnoreBadCerts", value: "obj['bIgnoreBadCerts']" },
                                ] },
                        ] }
                ];
                oCreateAccDialogh = { sUrl: "", sHomePath: "", sUserIdA: "", sPassword: "", sPrivateKeyPath: "",
                    bWinInet: false, bSecureConn: false, bUseProxy: true, bEncodeUTF8: true, bIgnoreBadCerts: false
                };
                icon = "fs_dav";
            }
            break;
        case "msgraph://":
            {
                const sName = "OneDrive Office365 SharePoint";
                jsCredentials.title = GetLocaleText("Title_NewAccount", [sName]);
                jsCredentials.cont = [
                    { title: "", cont: [
                            { type: "text", title: "Browse_Short_Tip_MsGraph" },
                            { type: "option_group", title: "Browse_Account_Authorization", cont: [
                                    { type: "text", title: GetLocaleText("Browse_Account_OAuthNeeded", [sName]), class: "small_text" },
                                ] },
                            { type: "row", "h": "15px", cont: [] },
                            { type: "button", img: "fs_msgraph", title: GetLocaleText("Browse_Account_OAuthConnectApp", [sName]), command: "OAuth2Connect", value: "obj", id: "connect_btn" },
                            { type: "place", title: "Test Results", id: "test_results", class: "test_account_results" },
                            { type: "hidden_group", title: "Advanced Options", cont: [
                                    { type: "checkbox", title: "Browse_Str_Graph_GroupRead", value: "obj['bGraphGroupReadPermissions']" },
                                    { type: "checkbox", title: "Browse_Str_Graph_DirectoryRead", value: "obj['bGraphDirectoryReadPerms']" },
                                    { type: "textfield", title: "Browse_Str_Graph_Tenant", value: "obj['sTenant']" },
                                ] },
                        ] }
                ];
                oCreateAccDialogh = { sUrlA: sFileSystem, sTenant: "", bGraphGroupReadPermissions: false, bGraphDirectoryReadPerms: false };
            }
            break;
        case "dropbox://":
            {
                const sName = "Dropbox";
                jsCredentials.title = GetLocaleText("Title_NewAccount", [sName]);
                jsCredentials.cont = [
                    { title: "", cont: [
                            { type: "text", title: "Browse_Short_Tip_Dropbox" },
                            { type: "option_group", title: "Browse_Account_Authorization", cont: [
                                    { type: "text", title: GetLocaleText("Browse_Account_OAuthNeeded", [sName]), class: "small_text" },
                                ] },
                            { type: "row", "h": "15px", cont: [] },
                            { type: "button", img: "fs_dropbox", title: GetLocaleText("Browse_Account_OAuthConnectApp", [sName]), command: "OAuth2Connect", value: "obj", id: "connect_btn" },
                            { type: "place", title: "Test Results", id: "test_results", class: "test_account_results" },
                            { type: "hidden_group", title: "Advanced Options", cont: [
                                    { type: "numberfield", title: "Browse_Str_UploadChunksThreads", value: "obj['nUploadChunksThreads']" },
                                ] },
                        ] }
                ];
                oCreateAccDialogh = { sUrlA: sFileSystem, nUploadChunksThreads: 5 };
            }
            break;
        case "gteamdrive://":
        case "goodrive://":
            {
                let sName = "Google Team Drive";
                let sTip = "Browse_Short_Tip_GTeamDrive";
                if (sFileSystem == "goodrive://") {
                    sName = "Google All Drive";
                    sTip = "Browse_Tip_GAllDrive";
                }
                jsCredentials.title = GetLocaleText("Title_NewAccount", [sName]);
                jsCredentials.cont = [
                    { title: "", cont: [
                            { type: "text", title: sTip },
                            { type: "option_group", title: "Browse_Account_Authorization", cont: [
                                    { type: "text", title: GetLocaleText("Browse_Account_OAuthNeeded", [sName]), class: "small_text" },
                                ] },
                            { type: "row", "h": "15px", cont: [] },
                            { type: "button", img: "fs_gdrive3", title: GetLocaleText("Browse_Account_OAuthConnectApp", [sName]), command: "OAuth2Connect", value: "obj", id: "connect_btn" },
                            { type: "place", title: "Test Results", id: "test_results", class: "test_account_results" },
                            { type: "hidden_group", title: "Advanced Options", cont: [
                                    { type: "checkbox", title: "Browse_Str_ExportNativeDocs", value: "obj['bExportNativeDocs']" },
                                ] },
                        ] }
                ];
                oCreateAccDialogh = { sUrlA: sFileSystem, bExportNativeDocs: false };
                icon = "fs_gdrive3";
            }
            break;
        case "gdrive://":
            {
                const sName = "Google Drive";
                jsCredentials.title = GetLocaleText("Title_NewAccount", [sName]);
                jsCredentials.cont = [
                    { title: "", cont: [
                            { type: "text", title: "Browse_Short_Tip_GDrive" },
                            { type: "option_group", title: "Browse_Account_Authorization", cont: [
                                    { type: "text", title: GetLocaleText("Browse_Account_OAuthNeeded", [sName]), class: "small_text" },
                                ] },
                            { type: "row", "h": "15px", cont: [] },
                            { type: "button", img: "fs_gdrive3", title: GetLocaleText("Browse_Account_OAuthConnectApp", [sName]), command: "OAuth2Connect", value: "obj", id: "connect_btn" },
                            { type: "place", title: "Test Results", id: "test_results", class: "test_account_results" },
                        ] }
                ];
                oCreateAccDialogh = { sUrlA: sFileSystem, bExportNativeDocs: false };
            }
            break;
        case "gphotos://":
            {
                const sName = "Google Photos";
                jsCredentials.title = GetLocaleText("Title_NewAccount", [sName]);
                jsCredentials.cont = [
                    { title: "", cont: [
                            { type: "text", title: "Browse_Short_Tip_GPhotos" },
                            { type: "option_group", title: "Browse_Account_Authorization", cont: [
                                    { type: "text", title: GetLocaleText("Browse_Account_OAuthNeeded", [sName]), class: "small_text" },
                                ] },
                            { type: "row", "h": "15px", cont: [] },
                            { type: "button", img: "fs_gphotos", title: GetLocaleText("Browse_Account_OAuthConnectApp", [sName]), command: "OAuth2Connect", value: "obj", id: "connect_btn" },
                            { type: "place", title: "Test Results", id: "test_results", class: "test_account_results" },
                        ] }
                ];
                oCreateAccDialogh = { sUrlA: sFileSystem, bExportNativeDocs: false };
            }
            break;
        case "gdocs3://":
            {
                const sName = "Google Docs";
                jsCredentials.title = GetLocaleText("Title_NewAccount", [sName]);
                jsCredentials.cont = [
                    { title: "", cont: [
                            { type: "text", title: "Browse_Short_Tip_GNativeDocs" },
                            { type: "option_group", title: "Browse_Account_Authorization", cont: [
                                    { type: "text", title: GetLocaleText("Browse_Account_OAuthNeeded", [sName]), class: "small_text" },
                                ] },
                            { type: "row", "h": "15px", cont: [] },
                            { type: "button", img: "fs_gdrive3", title: GetLocaleText("Browse_Account_OAuthConnectApp", [sName]), command: "OAuth2Connect", value: "obj", id: "connect_btn" },
                            { type: "place", title: "Test Results", id: "test_results", class: "test_account_results" },
                        ] }
                ];
                oCreateAccDialogh = { sUrlA: sFileSystem, bExportNativeDocs: false };
            }
            break;
        case "box://":
            {
                const sName = "Box.com";
                jsCredentials.title = GetLocaleText("Title_NewAccount", [sName]);
                jsCredentials.cont = [
                    { title: "", cont: [
                            { type: "text", title: "Browse_Short_Tip_BoxCom" },
                            { type: "option_group", title: "Browse_Account_Authorization", cont: [
                                    { type: "text", title: GetLocaleText("Browse_Account_OAuthNeeded", [sName]), class: "small_text" },
                                ] },
                            { type: "row", "h": "15px", cont: [] },
                            { type: "button", img: "fs_boxcom", title: GetLocaleText("Browse_Account_OAuthConnectApp", [sName]), command: "OAuth2Connect", value: "obj", id: "connect_btn" },
                            { type: "place", title: "Test Results", id: "test_results", class: "test_account_results" },
                        ] }
                ];
                oCreateAccDialogh = { sUrlA: sFileSystem, bExportNativeDocs: false };
            }
            break;
        case "icloud://":
        case "iphotos://":
            {
                let sFsName = (sFileSystem == "iphotos://") ? "Apple iCloud Drive" : "Apple iCloud Drive";
                let sFsTip = (sFileSystem == "iphotos://") ? "Browse_Short_Tip_ICloudPhotos" : "Browse_Short_Tip_ICloudDrive";
                jsCredentials.title = GetLocaleText("Title_NewAccount", [sFsName]);
                jsCredentials.cont = [
                    { title: "", cont: [
                            { type: "text", title: sFsTip },
                            { type: "option_group", title: "Browse_Account_Credentials", cont: [
                                    { type: "text", title: "Browse_Account_UserID", class: "text_above_field" },
                                    { type: "textfield", title: "", value: "obj['sUserIdA']", },
                                    { type: "text", title: "Browse_Account_Password", class: "text_above_field" },
                                    { type: "password", title: "", value: "obj['sPassword']", },
                                ] },
                            { type: "row", "h": "15px", cont: [] },
                            { type: "button", title: "test", command: "UniversalTest", value: "obj", id: "test_btn" },
                            { type: "place", title: "Test Results", id: "test_results" },
                            { type: "hidden_group", title: "Advanced Options", cont: [
                                    { type: "checkbox", title: "Browse_Str_CnICloud", value: "obj['bCnICloud']" },
                                ] },
                        ] }
                ];
                oCreateAccDialogh = { sUserIdA: "", sPassword: "", bCnICloud: false };
                icon = (sFileSystem == "iphotos://") ? "fs_iphotos" : "fs_icloud";
            }
            break;
    }
    oCreateAccDialogh.sFsName = sFileSystem;
    return { js: jsCredentials, obj: oCreateAccDialogh, add: aAccDetales, icon: icon };
}
function AddFillUrlForGSTx(account_data) {
    if (!account_data)
        return "";
    switch (account_data.sUrlA.toLowerCase()) {
        case 'gstp://':
        case 'gstps://':
        case 'gstore://': return account_data.sUrlA + account_data.sUserIdA + ".goodsync";
        default: return account_data.sUrlA;
    }
}
function GetServerName(sUrlA, sServerName, sUserName) {
    let nPos1 = sServerName.indexOf("://");
    if (nPos1 < 0)
        nPos1 = 0;
    else
        nPos1 += 3;
    if (IsFsGST(sUrlA)) {
        let nPos2 = sServerName.indexOf("." + sUserName + ".");
        if (nPos2 < 0)
            nPos2 = sServerName.length;
        return sServerName.slice(nPos1, nPos2);
    }
    else if (sUrlA.toLowerCase().startsWith("file://")) {
        return "";
    }
    let nPos3 = sServerName.indexOf("/", nPos1 + 1);
    if (nPos3 > 0) {
        return sServerName.slice(nPos1, nPos3);
    }
    return sServerName.slice(nPos1);
}
function IsFsGST(sUrlA) {
    if (!sUrlA)
        return false;
    sUrlA = sUrlA.toLowerCase();
    return /^(gstp:\/\/|gstps:\/\/|gstore:\/\/)+/.test(sUrlA);
}
function GetGstServerName(sUrl, sUserId) {
    if (!sUrl || !sUserId)
        return "";
    const arr = sUrl.split("." + sUserId);
    if (arr.length < 2)
        return "";
    const arr2 = arr[0].split("://");
    if (arr2.length < 2)
        return "";
    return arr2[1];
}
function IsServAddr(sUrlA) {
    try {
        const oUrl = ParseUrl(sUrlA);
        return !!oUrl.hostname;
    }
    catch (err) {
        return false;
    }
}
function IsFs(xAddArgs, aFs) {
    return aFs.includes(GetFieldValWithDrillUp(xAddArgs.Branch, "sFs"));
}
function IsAccHaveServerList(xAddArgs) {
    return xAddArgs.Branch.fGetData().bContServList;
}
function IsAccReadOnly(xAddArgs) {
    return xAddArgs.Branch.fGetData().bAccReadOnly;
}
function CanCreateFolder(xAddArgs) {
    return xAddArgs.Branch.fGetData().bCanCreateFolders;
}
function IsItBrowser() {
    return location.pathname.includes("WebGSExplorer.html");
}
function OpenInBrowser(xAddArgs, text) {
    return __awaiter(this, void 0, void 0, function* () {
        const urlWithPath = new URL(location.origin + location.pathname + '/static/WebGSExplorer.html');
        if (xAddArgs.Branch) {
            const oData = xAddArgs.Branch.fGetData();
            if (oData && oData.fGetPathAndName && oData.fGetUrl) {
                urlWithPath.searchParams.set('path', oData.fGetUrl() + oData.fGetPathAndName(xAddArgs.Branch, true));
                urlWithPath.searchParams.set('key', oData.fGetAccKey(xAddArgs.Branch));
            }
        }
        else if (xAddArgs.oJobInList) {
            const oJobInList = xAddArgs.oJobInList;
            urlWithPath.searchParams.set('path', xAddArgs.nInd ? oJobInList.right_url : oJobInList.left_url);
            urlWithPath.searchParams.set('key', oJobInList.oSideCoords[xAddArgs.nInd].sAcctKeyA);
        }
        else if (text) {
            const oJobInList = aGlobJobArray.find(item => item.name == sCurrJob);
            if (oJobInList) {
                const ind = (text == "Cmd_OpenLFolder") ? 0 : 1;
                urlWithPath.searchParams.set('path', oJobInList.oSideCoords[ind].conn.sUrlA + "/" + xAddArgs.oTreeRow._branch_.fGetPathStr("/"));
                urlWithPath.searchParams.set('key', oJobInList.oSideCoords[ind].sAcctKeyA);
            }
        }
        window.open(urlWithPath, '_blank');
    });
}
function NewFolder(xAddArgs) {
    return __awaiter(this, void 0, void 0, function* () {
        const aData = xAddArgs.Branch.fGetData();
        try {
            const jsFolderNameEnter = { "title": "Explorer_OpNewFolder",
                "bottom_box": [
                    { "title": "Str_CreateNewFolder", "close": true, command: "create", default: true },
                    { "title": "Cancel", "close": true },
                ], cont: [
                    { "title": "", cont: [
                            { type: "row", "h": "5px", cont: [] },
                            { type: "textfield", "title": "Str_FolderName", "value": "sNewFolderName" },
                            { type: "row", "h": "5px", cont: [] },
                        ] }
                ]
            };
            const obj = { sNewFolderName: "" };
            const oMenu = CreateFloatMenu(jsFolderNameEnter, { width: "600px", top: "30%" }, obj, { fontSize: "calc(var(--base-font-size) * 1.25);" });
            oMenu.promise
                .then((resalts) => __awaiter(this, void 0, void 0, function* () {
                let sFolderName = resalts.data.sNewFolderName;
                if (!sFolderName)
                    return;
                if (sFolderName.substring(0, 1) == "\\" || sFolderName.substring(0, 1) == "/") {
                    sFolderName = sFolderName.substring(1);
                }
                const oData = xAddArgs.Branch.fGetData();
                let sPath = "/" + sFolderName;
                if ("sHomePath" in oData) {
                    sPath = oData.sHomePath + "/" + sFolderName;
                }
                else if (oData.fGetPathAndName) {
                    sPath = oData.fGetPathAndName(xAddArgs.Branch) + "/" + sFolderName;
                }
                const sFsHandle = yield aData.fGetFsHandle(xAddArgs.Branch, xAddArgs.Branch, pGettingFsHandleAbort);
                yield AsyncMakeFolderRequest(sFsHandle, sPath, { "Branch": xAddArgs.Branch, "DTP": xAddArgs.DTP }, sFolderName);
            }))
                .catch(() => { })
                .finally(() => {
                aData.fGetFsHandle(xAddArgs.Branch, null);
            });
        }
        catch (_a) {
        }
    });
}
function RenameAccount(xAddArgs) {
    const aData = xAddArgs.Branch.fGetData();
    const sKey = aData.fGetAccKey();
    const sOldName = aData.display_name;
    if (sKey) {
        const jsFolderNameEnter = { title: "Str_ChangeAccountName",
            bottom_box: [
                { title: "Btn_Change", close: true, command: "create", default: true },
                { title: "Cancel", close: true },
            ], cont: [
                { title: "", cont: [
                        { type: "text", "title": GetLocaleText("Str_OldName", [sOldName]) },
                        { type: "row", "h": "5px", cont: [] },
                        { type: "textfield", title: "Str_NewName", value: "sNewName" },
                        { type: "row", h: "5px", cont: [] },
                    ] }
            ]
        };
        const obj = { sNewName: "" };
        CreateFloatMenu(jsFolderNameEnter, { width: "600px", top: "30%" }, obj, { fontSize: "calc(var(--base-font-size) * 1.25);" }).
            promise.then(resalts => {
            let sNewName = resalts.data.sNewName;
            if (!sNewName || sNewName == sOldName) {
                return;
            }
            RenameAccountRequest(sKey, sNewName, xAddArgs);
        }).catch(() => { });
    }
}
const FOLDER_OPTIONS_PSWD_MIN_LEN = 8;
function RemoveFolderCont(oMenu) {
    const sLockCurrJob = sCurrJob;
    HtmlConfirm(GetLocaleText("Str_AskREmoveAllFromFolder", [oMenu.jsMenuPart.meta.sSidePath]), GetLocaleText("Btn_Encrypt_EmptyFolder"), eMyConfDefBtn.cancel)
        .then(() => __awaiter(this, void 0, void 0, function* () {
        const jsWaitingFileListBox = {
            title: "Info_FolderContentsRemoving", bottom_box: [], cont: [
                { title: "", cont: [
                        { type: "text", title: "<b>Path: " + oMenu.jsMenuPart.meta.sSidePath + "</b></br>" },
                        { type: "place", title: "- Start of clearing -", id: "spop_state", class: "nowrap_nooverflow_ellipse" },
                    ] }
            ]
        };
        const oWaitingBox = CreateFloatMenu(jsWaitingFileListBox, { width: "40%", top: "30%" }, null);
        pGlobalWaitinBox = oWaitingBox.oMenu;
        oWaitingBox.promise.then(() => { }).catch(() => { });
        const domPlace = document.getElementById("spop_state_" + oWaitingBox.oMenu.id);
        domPlace.innerText = "- Start of clearing -";
        try {
            yield AsyncUnicSendRecivePostApiWithRetry("StartSpecOp", { "job_name": sLockCurrJob, "spop_type": (oMenu.jsMenuPart.meta.eSideNum ? 7 : 6) }, { "domMenu": pGlobalWaitinBox });
            const oJobInList = aGlobJobArray.find(item => item.name == sLockCurrJob);
            if (oJobInList) {
                oJobInList.pMenu = oMenu;
            }
        }
        catch (catchData) {
            if (!pGlobalWaitinBox || pGlobalWaitinBox.bSelfDeleted)
                return;
            CloseFloatMenu(pGlobalWaitinBox);
            if (catchData && catchData.error && catchData.error.message) {
                HtmlErrBox(catchData.error.message, "Error folder clearing");
            }
        }
    })).catch(() => {
        if (pGlobalWaitinBox) {
            CloseFloatMenu(pGlobalWaitinBox);
            pGlobalWaitinBox = null;
        }
    });
}
function FolderOptionsRequest(eSideNum) {
    AccountByKeyRequest(jsCurrJobOptions.side_coords[eSideNum], eSideNum);
}
function OpenFolderOptionSets(oBM, sUrlA, eSideNum, oFC) {
    jsFloatMenu["FolderOptions"].title = eSideNum ? "Cmd_RightSideOpts" : "Cmd_LeftSideOpts";
    if (sUrlA.indexOf("file://") === 0 || sUrlA.indexOf("smb://") === 0 || sUrlA.indexOf("gstp") === 0) {
        if (jsFloatMenu["FolderOptions"].cont[0].cont[0].title != "Str_Side_FileSystem") {
            jsFloatMenu["FolderOptions"].cont[0].cont.splice(0, 0, { type: "option_group", title: "Str_Side_FileSystem", cont: [
                    { type: "checkbox", title: "Browse_Str_PreferCompressed", value: "bPreferCompressed", },
                    { type: "checkbox", title: "Browse_Str_PreferEncrypted", value: "bPreferEncrypted", },
                    { type: "checkbox", title: "Browse_Str_FatLike", value: "bFatLike", },
                ] });
        }
    }
    else {
        if (jsFloatMenu["FolderOptions"].cont[0].cont[0].title == "Str_Side_FileSystem") {
            jsFloatMenu["FolderOptions"].cont[0].cont.splice(1, 0);
        }
    }
    jsFloatMenu["FolderOptions"].meta = {};
    jsFloatMenu["FolderOptions"].meta.sSidePath = oBM.sServerDirA;
    jsFloatMenu["FolderOptions"].meta.eSideNum = eSideNum;
    jsFloatMenu["FolderOptions"].meta.oFC = oFC;
    const oFO = CopyObject(oBM.opts);
    if (oFO.bEncryptBodies && oFO.bEncryptPaths && oFO.nCipherType === 0 && oFO.nCompressType === 0) {
        oFO.nCompressType = 1;
    }
    if (oFO.sEncryptionPasswdEncMasterA) {
        DecryptStringWithKey(oFO.sEncryptionPasswdEncMasterA, oWebGuSettings.key, oWebGuSettings.iv).then(sDecryptPass => {
            oFO.sRawPasswd = sDecryptPass;
            oFO.sRepPasswd = sDecryptPass;
            CreateFloatMenu(jsFloatMenu["FolderOptions"], { width: '650px', top: "30%" }, oFO, { minHeight: "20rem", minWidth: "30rem", bCurrJobName: true }).promise
                .then(data => {
                if (data.command == "save") {
                    ProcessingChangeFolderOptions(oFO, oBM, sUrlA, eSideNum);
                }
            }).catch(() => { });
        }).catch(() => { });
    }
    else {
        oFO.sRawPasswd = "";
        oFO.sRepPasswd = "";
        CreateFloatMenu(jsFloatMenu["FolderOptions"], { width: '650px', top: "30%" }, oFO, { minHeight: "20rem", minWidth: "30rem", bCurrJobName: true }).promise
            .then(data => {
            if (data.command == "save") {
                ProcessingChangeFolderOptions(oFO, oBM, sUrlA, eSideNum);
            }
        }).catch(() => { });
    }
}
function ProcessingChangeFolderOptions(oFO, oBM, sUrlA, eSide, oBDE) {
    if (oFO.nCompressType == 0 || oFO.nCompressType == 2 && oFO.nCipherType == 0) {
        oFO.sRawPasswd = "";
        oFO.sEncryptionPasswdEncMasterA = "";
    }
    if (oFO.nCompressType == 1 || oFO.nCompressType == 2 && oFO.nCipherType != 0) {
        if (!oFO.sRawPasswd) {
            HtmlMsgbox(GetLocaleText("Err_RequirePassword"), "<span style='color:red'>Error</span>");
            return;
        }
        else if (oFO.sRawPasswd !== oFO.sRepPasswd) {
            HtmlMsgbox(GetLocaleText("Err_NotMatchPassword"), "<span style='color:red'>Error</span>");
            return;
        }
        else if (oFO.sRawPasswd.length < FOLDER_OPTIONS_PSWD_MIN_LEN) {
            HtmlMsgbox(GetLocaleText("Err_ShortPassword", ["" + FOLDER_OPTIONS_PSWD_MIN_LEN]), "<span style='color:red'>Error</span>");
            return;
        }
    }
    let sOptChangeQuestions = "";
    if (oFO.bNoGsData !== oBM.opts.bNoGsData && !oBDE) {
        sOptChangeQuestions = (oFO.bNoGsData ? GetLocaleText("Warn_KeepGsData") : GetLocaleText("Warn_MoveGsData")) + "<p>";
    }
    oFO.bEncryptBodies = oFO.nCompressType === 1;
    oFO.bEncryptPaths = oFO.nCompressType === 1 || oFO.nCompressType === 2 && oFO.bEncryptPaths;
    if (oFO.nCompressType === 1) {
        oFO.nCompressType = 0;
        oFO.nCipherType = 0;
    }
    oBM.BmkKey = oBM.sServerDirA;
    if (oFO.sRawPasswd && oFO.sRepPasswd && oFO.sRawPasswd === oFO.sRepPasswd) {
        EncryptStringWithKey(oFO.sRawPasswd, oWebGuSettings.key, oWebGuSettings.iv).then(sEncryptPass => {
            if (oBM.opts.sEncryptionPasswdEncMasterA != sEncryptPass && !oBDE) {
                sOptChangeQuestions += GetLocaleText("Warn_Encrypt_Changed", [sUrlA], { bBold: true, sQuotes: "'" });
            }
            if (sOptChangeQuestions) {
                HtmlConfirm(sOptChangeQuestions, "", eMyConfDefBtn.cancel).then(() => {
                    if (eSide >= 0) {
                        DeleteGsDataFolderRequest(sCurrJob, eSide == 0);
                    }
                    SetSameObjFields(oFO, oBM.opts);
                    oBM.opts.sEncryptionPasswdEncMasterA = sEncryptPass;
                    SetUnnamedBookmarkRequest(oBM, oBDE);
                }).catch(() => { });
            }
            else {
                SetSameObjFields(oFO, oBM.opts);
                oBM.opts.sEncryptionPasswdEncMasterA = sEncryptPass;
                SetUnnamedBookmarkRequest(oBM, oBDE);
            }
        }).catch(() => { });
    }
    else {
        if (oBM.opts.sEncryptionPasswdEncMasterA) {
            sOptChangeQuestions += GetLocaleText("Warn_Encrypt_Changed", [sUrlA], { bBold: true, sQuotes: "'" });
        }
        if (sOptChangeQuestions && !oBDE) {
            HtmlConfirm(sOptChangeQuestions, GetLocaleText("Str_ChangeFolderOptions"), eMyConfDefBtn.ok).then(() => {
                if (eSide >= 0) {
                    DeleteGsDataFolderRequest(sCurrJob, eSide == 0);
                }
                SetSameObjFields(oFO, oBM.opts);
                oBM.opts.sEncryptionPasswdEncMasterA = "";
                SetUnnamedBookmarkRequest(oBM, oBDE);
            }).catch(() => { });
        }
        else {
            SetSameObjFields(oFO, oBM.opts);
            SetUnnamedBookmarkRequest(oBM, oBDE);
        }
    }
}
function GetAccWithCreds(oConn, oDTP, sUser) {
    const url = ParseUrl(oConn.sUrlA);
    const oFs = oDTP.root.fFindEl(url.protocol);
    if (oFs) {
        const aAcc = oFs.jsBody;
        let sAccKey = "";
        let pCommAcc;
        for (const oAcc of aAcc) {
            if (oAcc.sUrl == url.protocol) {
                pCommAcc = oAcc;
                continue;
            }
            if (IsFsGST(oConn.sUrlA) && url.hostname.endsWith(oAcc.oConn.sUserIdA + ".goodsync") ||
                (sUser && oAcc.oConn.sUserEmailA.startsWith(sUser) || !sUser) &&
                    DoJobPathsContainsOneAnother(oAcc.sUrl + oAcc.sHomePath, oConn.sUrlA, true)) {
                sAccKey = oAcc.sAccKey;
                break;
            }
        }
        if (sAccKey) {
            return oFs.fFindEl(sAccKey);
        }
        if (pCommAcc) {
            return oFs.fFindEl(pCommAcc.sAccKey);
        }
    }
}
function ExploreTableRowClick(oTableBranch, oBDP, pNewUrl, domSaveBtn) {
    SetNewUrlForExplorer(oTableBranch, pNewUrl);
    if (oBDP.fIsThisChoiceGood && !oBDP.fIsThisChoiceGood(oTableBranch.fGetData())) {
        if (domSaveBtn) {
            domSaveBtn.disabled = true;
        }
        if (pNewUrl) {
            pNewUrl.classList.add("err_in_field");
            if (oBDP.sErrHint)
                pNewUrl.title = GetLocaleText(oBDP.sErrHint);
        }
    }
    else {
        if (domSaveBtn) {
            domSaveBtn.disabled = false;
        }
        if (pNewUrl) {
            pNewUrl.classList.remove("err_in_field");
            pNewUrl.title = "";
        }
    }
}
function CreateBrowserTree(aFileSystems, oBDP, oResume) {
    const oDTP = new TDynamicTableProperties();
    oDTP.aHead = jsFloatMenuTableHeads.ExploreTableHead;
    oDTP.bIsTree = true;
    oDTP.nLevelNotSort = 1;
    oDTP.sSortCol = "display_name";
    oDTP.bNeedSort = true;
    oDTP.bStriped = true;
    if (oBDP.bWOFiles) {
        oDTP.fFiltr = Nothing;
    }
    oDTP.root.fAddDataArr(aFileSystems, {
        sPathFieldName: "plain_url",
        oFunc: {
            fOpenFolder: function (oBranch, oDTPx) {
                ListAccForExplorerRequest(null, { Branch: oBranch, DTP: oDTPx, domErr: oResume.pResume });
            },
            fRightBtn: function (e, nCurrRow, oDTPx) {
                TableRowClick(oDTPx, oDTPx.aDeploedTable[nCurrRow]._branch_);
                CreateDropMenuItems(jsBrowseDialogFsMenu, e.clientX, e.clientY, e.clientX, e.target, false, { "Branch": oDTPx.aDeploedTable[nCurrRow]._branch_, "DTP": oDTPx });
            }
        },
        fDataProcessor: SetFsBranch,
        bNoSelectWithShiftOrCtrl: true,
    });
    const oLocalFs = oDTP.root.cont.find(item => item.pathEl == "file://");
    if (oLocalFs) {
        oLocalFs.fOpenFolder = (Branch, DTP) => __awaiter(this, void 0, void 0, function* () {
            if (!Branch.cont || !Branch.cont.length) {
                const oData = Branch.fGetData();
                oData.fGetAccKey = () => { return "file://@"; };
                oData.fGetUrl = () => { return "file://"; };
                oData.fGetPathAndName = () => { return ""; };
                if (!oData.__oAbort__) {
                    oData.__oAbort__ = new AbortController();
                }
                ShowWaitingTimer("Getting Accounts list", { Branch, DTP });
                yield LocalFsSharesRequest(oData, Branch, DTP, null);
            }
        });
    }
    return oDTP;
}
function LocalFsSharesRequest(oData, Branch, DTP, aPath) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const oLocalAcc = yield AsyncUnicSendRecivePostApiWithRetry("ListAccounts", { fs_url: "file://" }, { oMultiPageArrs: { accounts: [], hints: [] }, abort: oData.__oAbort__ });
            if (!oLocalAcc || oLocalAcc.accounts.length < 1)
                throw null;
            oData.oConn = oLocalAcc.accounts[0].AcctConn;
            if (oLocalAcc.accounts[0].UnnamedBookmarks && oLocalAcc.accounts[0].UnnamedBookmarks.length) {
                const aBookmarks = [];
                for (const bm of oLocalAcc.accounts[0].UnnamedBookmarks) {
                    if (bm.Opts && (bm.Opts.nCompressType > 1 || bm.Opts.bEncryptBodies || bm.Opts.bEncryptPaths)) {
                        aBookmarks.push(bm);
                    }
                }
                if (aBookmarks.length > 0) {
                    oData.aBookmarks = aBookmarks;
                }
            }
            const oFolderCoords = { "conn": oData.oConn, "sAcctKeyA": "file://@" };
            const oConnectFsResult = yield AsyncUnicSendRecivePostApiWithRetry("ConnectFS", { "folder_coords": oFolderCoords }, { "abort": oData.__oAbort__ });
            oData.sFsHandle = oConnectFsResult.filesys_handle;
            oData.fSetFsHandle = function (sFsHandle) { this.sFsHandle = sFsHandle; };
            yield ListDirForExplorerRequest(oConnectFsResult.filesys_handle, "", aPath, { Branch, DTP });
        }
        catch (_a) { }
    });
}
function BrowseDialogForSideUrlChange(aFileSystems, oBDP) {
    if (!oBDP.ind) {
        oBDP.ind = 0;
    }
    if (!oBDP.sUrl2) {
        oBDP.sUrl2 = "";
    }
    const oResume = { pResume: null };
    const oDTP = CreateBrowserTree(aFileSystems, oBDP, oResume);
    oDTP.bOnlyOneSelRow = true;
    let sUrlForChange = "";
    if (oBDP.oIFDD && oBDP.oIFDD.conn.sUrlA) {
        sUrlForChange = oBDP.oIFDD.conn.sUrlA;
    }
    const obj = { oDTP: oDTP, sUrlForChange: GetPathForShow(sUrlForChange), sUrl2: GetPathForShow(oBDP.sUrl2) };
    if (oBDP.bExplore || oBDP.bSetPath) {
        let oBrowseDialog;
        if (oBDP.bSetPath) {
            if (oBDP.sDialogTitile) {
                jsFloatMenu["ChoiceFileDialog"].title = oBDP.sDialogTitile;
            }
            oBrowseDialog = CreateFloatMenu(jsFloatMenu["ChoiceFileDialog"], { width: "60%", height: -60 }, obj);
        }
        else {
            const oDTP2 = CreateBrowserTree(aFileSystems, oBDP, oResume);
            obj.oDTP2 = oDTP2;
            obj.sUrl2 = "";
            pGettingFsHandleAbort = {};
            oBrowseDialog = CreateFloatMenu(jsFloatMenu["ExploreDialog"], { width: "98%", height: -98 }, obj);
            DeactivateElById("btnExplorer_1Tree_" + oBrowseDialog.oMenu.id);
            SetDomDisplayAndInnerHtml("second_tree_" + oBrowseDialog.oMenu.id, "none");
            const pUrl2 = document.getElementById("Url2_" + oBrowseDialog.oMenu.id);
            oDTP2.fRowClick = function (oTableBranch) {
                ExploreTableRowClick(oTableBranch, oBDP, pUrl2);
            };
            if (pUrl2 && "value" in pUrl2) {
                pUrl2.fKeyDown = (e) => ExplorerUrlEnter(e, pUrl2, oBDP, oDTP2);
            }
        }
        const pNewUrl = document.getElementById("UrlForChange_" + oBrowseDialog.oMenu.id);
        const domSaveBtn = document.getElementById("Btn_Select_" + oBrowseDialog.oMenu.id);
        if (pNewUrl && "value" in pNewUrl) {
            pNewUrl.fKeyDown = (e) => ExplorerUrlEnter(e, pNewUrl, oBDP, oDTP);
        }
        oDTP.fRowClick = function (oTableBranch) {
            ExploreTableRowClick(oTableBranch, oBDP, pNewUrl, domSaveBtn);
        };
        oBrowseDialog.promise.then(() => {
            if (oBDP.domUrl) {
                oBDP.domUrl.value = obj.sUrlForChange;
                oBDP.domUrl.dispatchEvent(new Event('input'));
            }
        }).catch(() => { }).finally(() => {
            DisconnectAllFs();
            pGettingFsHandleAbort = null;
        });
    }
    else {
        jsFloatMenu["BrowseDialog"].title = oBDP.ind ? GetLocaleText("Str_SetRightSide") : GetLocaleText("Str_SetLeftSide");
        pGettingFsHandleAbort = {};
        const oBrowseDialog = CreateFloatMenu(jsFloatMenu["BrowseDialog"], { width: "98%", height: -98 }, obj, { minWidth: "400px", bCurrJobName: true });
        const domSaveBtn = document.getElementById("Btn_Select_" + oBrowseDialog.oMenu.id);
        oResume.pResume = document.getElementById("resume_" + oBrowseDialog.oMenu.id);
        const pNewUrl = document.getElementById("UrlForChange_" + oBrowseDialog.oMenu.id);
        if (pNewUrl && "value" in pNewUrl) {
            pNewUrl.fKeyDown = (e) => ExplorerUrlEnter(e, pNewUrl, oBDP, oDTP);
        }
        oDTP.fRowClick = function (oTableBranch) {
            const sNewUrl = SetNewJobUrl(oTableBranch, pNewUrl, oBDP.ind, oBDP.sUrl2, oResume.pResume, domSaveBtn);
            if (sNewUrl) {
                obj.sUrlForChange = sNewUrl;
            }
        };
        if (domSaveBtn) {
            domSaveBtn.disabled = false;
        }
        oBrowseDialog.promise.then((oData) => {
            if (oData.data.sUrlForChange != GetPathForShow(sUrlForChange)) {
                if (!sUrlForChange.trim() || sUrlForChange == "&nbsp;") {
                    JobOptionsForChangeRequest();
                }
                else {
                    let qsn = GetLocaleText("Browse_SureAboutChange1") + "<p><b>" + GetLocaleText("Str_CurrentFolder") + ":</b><br/>"
                        + GetPathForShow(sUrlForChange) + "<p><b>" + GetLocaleText("Explorer_OpNewFolder") + ":</b><br/>" + GetPathForShow(oData.data.sUrlForChange)
                        + "<p>" + GetLocaleText("Browse_SureAboutChange") + "<p><b>" + GetLocaleText("Qsn_WhatWouldYouLikeToDo") + "</b>";
                    HtmlConfirm(qsn, oBDP.ind ? "Str_ChangeRightSyncFolder" : "Str_ChangeLeftSyncFolder", eMyConfDefBtn.ok, { ok: "Btn_SaveChange" }).then(() => {
                        JobOptionsForChangeRequest();
                    }).catch(() => { });
                }
            }
        }).catch(() => { }).finally(() => {
            DisconnectAllFs();
            pGettingFsHandleAbort = null;
        });
    }
    if (oBDP.oIFDD) {
        let nEndOfNameFs = oBDP.oIFDD.conn.sUrlA.indexOf("://");
        if (nEndOfNameFs > 0) {
            let sFsUrl = oBDP.oIFDD.conn.sUrlA.substring(0, nEndOfNameFs + 3);
            let oTargetRow = oDTP.aDeploedTable.find(item => GetFieldValWithDrillUp(item._branch_, "sFs") == sFsUrl);
            if (oTargetRow) {
                ListAccForExplorerRequest(oBDP.oIFDD, { Branch: oTargetRow._branch_, DTP: oDTP, domErr: oResume.pResume });
            }
            else {
                const oFs = aFileSystems.find(it => it.plain_url == sFsUrl);
                if (oFs) {
                    bShowHiddenFs = true;
                    const oNewFs = oDTP.root.fAddData(oFs, {
                        sPathFieldName: "plain_url",
                        oFunc: {
                            fOpenFolder: function (oBranch, oDTPx) {
                                ListAccForExplorerRequest(null, { Branch: oBranch, DTP: oDTPx, domErr: oResume.pResume });
                            },
                            fRightBtn: function (e, nCurrRow, oDTPx) {
                                TableRowClick(oDTPx, oDTPx.aDeploedTable[nCurrRow]._branch_);
                                CreateDropMenuItems(jsBrowseDialogFsMenu, e.clientX, e.clientY, e.clientX, e.target, false, { "Branch": oDTPx.aDeploedTable[nCurrRow]._branch_, "DTP": oDTPx });
                            }
                        },
                        fDataProcessor: SetFsBranch
                    });
                    bShowHiddenFs = false;
                    oDTP.ShowTable();
                    ListAccForExplorerRequest(oBDP.oIFDD, { Branch: oNewFs, DTP: oDTP, domErr: oResume.pResume });
                }
            }
        }
    }
}
function BrowseDialogForGSE(aFileSystems, oBDP) {
    oBDP.sUrl1 = oBDP.sUrl1 || "";
    oBDP.sUrl2 = oBDP.sUrl2 || "";
    const oResume = { pResume: null };
    const oDTP = CreateBrowserTree(aFileSystems, oBDP, oResume);
    const oDTP2 = CreateBrowserTree(aFileSystems, oBDP, oResume);
    const obj = { oDTP, oDTP2, sUrlForChange: GetPathForShow(oBDP.sUrl1), sUrl2: "" };
    const oBrowseDialog = CreateFloatMenu(jsFloatMenu["ExploreDialog"], { width: "100%", height: -100 }, obj, { bNoTitle: true, bNoborder: true, bNoResize: true });
    DeactivateElById("btnExplorer_1Tree_" + oBrowseDialog.oMenu.id);
    SetDomDisplayAndInnerHtml("second_tree_" + oBrowseDialog.oMenu.id, "none");
    const pUrl2 = document.getElementById("Url2_" + oBrowseDialog.oMenu.id);
    oDTP2.fRowClick = function (oTableBranch) {
        ExploreTableRowClick(oTableBranch, oBDP, pUrl2);
    };
    if (pUrl2 && "value" in pUrl2) {
        pUrl2.fKeyDown = (e) => ExplorerUrlEnter(e, pUrl2, oBDP, oDTP2);
    }
    const pUrl1 = document.getElementById("UrlForChange_" + oBrowseDialog.oMenu.id);
    oDTP.fRowClick = function (oTableBranch) {
        ExploreTableRowClick(oTableBranch, oBDP, pUrl1);
    };
    if (pUrl1 && "value" in pUrl1) {
        pUrl1.fKeyDown = (e) => ExplorerUrlEnter(e, pUrl1, oBDP, oDTP);
        if (pUrl1.value) {
            ExplorerUrlProc(pUrl1.value, oBDP, oDTP);
        }
    }
}
function ExplorerUrlProc(sNewUrl, oBDP, oDTP) {
    return __awaiter(this, void 0, void 0, function* () {
        let sPath = NormalizePath(sNewUrl);
        if (!sPath)
            return;
        const url = ParseUrl(sPath);
        if (url.protocol == "file://") {
            sPath = "file:///" + url.pathname;
        }
        let oNewConn = null;
        if (oBDP.oIFDD && oBDP.oIFDD.conn) {
            oNewConn = CopyObject(oBDP.oIFDD.conn);
        }
        else {
            oNewConn = new TConn;
        }
        url.user += "@";
        oNewConn.sUrlA = sPath.replace(url.user, "");
        const oFS = oDTP.root.fFindEl(url.protocol);
        if (oFS) {
            if (url.protocol == "file://") {
                const aPath = url.pathname.split("\/");
                LocalFsSharesRequest(oFS.fGetData(), oFS, oDTP, aPath);
            }
            else {
                ListAccForExplorerRequest({ "conn": oNewConn, key: oBDP.sKey || "", user: url.user }, { Branch: oFS, DTP: oDTP });
            }
        }
        else {
            try {
                const aFs = (yield AsyncUnicSendRecivePostApiWithRetry("ListFileSystems", { url: url.protocol })).file_systems;
                if (!aFs || aFs.length < 1) {
                    throw null;
                }
                aFs[0].properties.hide_in_fs_list = "0";
                oDTP.root.fAddDataArr(aFs, {
                    sPathFieldName: "plain_url",
                    oFunc: {
                        fOpenFolder: function (oBranch, oDTPx) {
                            ListAccForExplorerRequest(null, { Branch: oBranch, DTP: oDTPx, domErr: null });
                        },
                        fRightBtn: function (e, nCurrRow, oDTPx) {
                            TableRowClick(oDTPx, oDTPx.aDeploedTable[nCurrRow]._branch_);
                            CreateDropMenuItems(jsBrowseDialogFsMenu, e.clientX, e.clientY, e.clientX, e.target, false, { "Branch": oDTPx.aDeploedTable[nCurrRow]._branch_, "DTP": oDTPx });
                        }
                    },
                    bNoSelectWithShiftOrCtrl: true,
                    fDataProcessor: SetFsBranch
                });
                oDTP.ShowTable();
                const oFS1 = oDTP.root.fFindEl(url.protocol);
                if (!oFS1) {
                    throw null;
                }
                ListAccForExplorerRequest({ "conn": oNewConn, key: oBDP.sKey || "", user: url.user }, { Branch: oFS1, DTP: oDTP });
            }
            catch (_a) {
                ErrorMsgShow(GetLocaleText("Err_FileSystemSearchingError"), GetLocaleText("Err_FileSystemDidntFind", [url.protocol], { bBold: true }), "msgbox");
            }
        }
    });
}
function ExplorerUrlEnter(e, pNewUrl, oBDP, oDTP) {
    if (e.code == "Enter") {
        e.preventDefault();
        ExplorerUrlProc(pNewUrl.value, oBDP, oDTP);
    }
}
function SetFolderOptFromJobDetails(xArgs) {
    CreateBrowsDialogWindows(xArgs.nInd, xArgs.oJobInList.left_url, xArgs.oJobInList.right_url, xArgs.oJobInList.oSideCoords);
}
function ShowExplorer(xArgs) {
    return __awaiter(this, void 0, void 0, function* () {
        const sUrl2 = xArgs.nInd ? xArgs.oJobInList.left_url : xArgs.oJobInList.right_url;
        try {
            const jsData = yield AsyncUnicSendRecivePostApiWithRetry("ListFileSystems");
            const oBDP = {
                oIFDD: { conn: xArgs.oJobInList.oSideCoords[xArgs.nInd].conn, key: xArgs.oJobInList.oSideCoords[xArgs.nInd].sAcctKeyA },
                ind: xArgs.nInd, sUrl2, bExplore: true
            };
            BrowseDialogForSideUrlChange(jsData.file_systems, oBDP);
        }
        catch (oErr) {
            if (oErr && oErr.message) {
                ErrorMsgShow("ListFileSystems:", oErr.message, "msgbox");
            }
        }
    });
}
function GetAndShowOptionsFromJobDetails(xArgs) {
    GetAndShowJobOptions(xArgs.nInd ? 'Title_JobRightSide' : 'Title_JobLeftSide');
}
function CopyPathToClipboard(xArgs) {
    navigator.clipboard.writeText(xArgs.nInd ? xArgs.oJobInList.right_url : xArgs.oJobInList.left_url);
}
function SwitchExplorerTo1Tree(oMenu) {
    ActivateElById("btnExplorer_2Tree_" + oMenu.id);
    DeactivateElById("btnExplorer_1Tree_" + oMenu.id);
    SetDomDisplayAndInnerHtml("second_tree_" + oMenu.id, "none");
    const donFirstTree = SetDomDisplayAndInnerHtml("first_tree_" + oMenu.id, null, { text: null, delClass: ["stretch_x", "thick_right_border"] });
    if (donFirstTree) {
        donFirstTree.style.flex = "1 1 100%";
    }
    SetStretchEl();
}
function SwitchExplorerTo2Tree(oMenu) {
    DeactivateElById("btnExplorer_2Tree_" + oMenu.id);
    ActivateElById("btnExplorer_1Tree_" + oMenu.id);
    SetDomDisplayAndInnerHtml("first_tree_" + oMenu.id, null, { text: null, class: ["stretch_x", "thick_right_border"] });
    SetDomDisplayAndInnerHtml("second_tree_" + oMenu.id, "");
    AllUserResize();
    SetStretchEl();
}
const CHK_ENC_FILE_MAX_SIZE = 0x400000;
const CHK_ENC_FILE_ARR_LEN = 2;
const CHK_ENC_NAME_ARR_LEN = 6;
const CHK_ENC_MAX_REQ_NUM = 20;
const CHK_ENC_MAX_PAGE_NUM = 100;
const CHK_ENC_PREFER_FOLDER = "_gsdata_";
const CHK_ENC_PREFER_NAME1 = "_gsdata_/_file_state_v4._gs";
const CHK_ENC_PREFER_NAME2 = "_gsdata_/_recycled_db._gs";
const GS_CANNOT_DECRYPT_NAME_PREFIX = "#cannot-decrypt-name#";
function BtnEncryptTest(oFO, oMenu, bSetUBM) {
    return __awaiter(this, void 0, void 0, function* () {
        if (oFO.nCompressType == 0 || oFO.nCompressType == 2 && oFO.nCipherType == 0) {
            return;
        }
        if (!oFO.sRawPasswd) {
            HtmlErrBox(GetLocaleText("Err_RequirePassword"), "Password error");
            return;
        }
        else if (oFO.sRawPasswd !== oFO.sRepPasswd && !bSetUBM) {
            HtmlErrBox(GetLocaleText("Err_NotMatchPassword"), "Password error");
            return;
        }
        else if (oFO.sRawPasswd.length < FOLDER_OPTIONS_PSWD_MIN_LEN) {
            HtmlErrBox(GetLocaleText("Err_ShortPassword", ["" + FOLDER_OPTIONS_PSWD_MIN_LEN]), "Password error");
            return;
        }
        let oTmpBM;
        if (bSetUBM) {
            oTmpBM = new TFolderCoords;
            oTmpBM.opts = new TOpts;
            oTmpBM.conn = CopyObject(oMenu.jsMenuPart.meta.conn);
            oTmpBM.conn.sUrlA += oMenu.jsMenuPart.meta.sServerDirA;
            oTmpBM.sServerDirA = oMenu.jsMenuPart.meta.sServerDirA;
            oTmpBM.sAcctKeyA = oMenu.jsMenuPart.meta.sAcctKeyA;
        }
        else {
            oTmpBM = CopyObject(oMenu.jsMenuPart.meta.oFC);
        }
        SetSameObjFields(oFO, oTmpBM.opts);
        oTmpBM.opts.bEncryptBodies = oTmpBM.opts.nCompressType === 1;
        oTmpBM.opts.bEncryptPaths = oTmpBM.opts.nCompressType === 1 || oTmpBM.opts.nCompressType === 2 && oTmpBM.opts.bEncryptPaths;
        if (oTmpBM.opts.nCompressType === 1) {
            oTmpBM.opts.nCompressType = 0;
            oTmpBM.opts.nCipherType = 0;
        }
        const oWaitingMenu = CreateWaitingBox("Info_EncTest");
        try {
            oTmpBM.opts.sEncryptionPasswdEncMasterA = yield EncryptStringWithKey(oFO.sRawPasswd, oWebGuSettings.key, oWebGuSettings.iv);
            const oConnectFsResult = yield ConnectFsRequestPromise(oTmpBM);
            const aErrMsg = [];
            const aPathArr = [CHK_ENC_PREFER_NAME1, CHK_ENC_PREFER_NAME2];
            for (const sFile of aPathArr) {
                try {
                    yield OpenFile(oConnectFsResult.filesys_handle, sFile);
                }
                catch (oErr) {
                    if (oErr && oErr.error && oErr.error.data && oErr.error.data.error_str == "local_err" && oErr.error.message) {
                        aErrMsg.push(sFile + ": " + oErr.error.message);
                    }
                }
                yield CloseFileRequest(oConnectFsResult.filesys_handle, true);
            }
            const oListDirResult = yield ListDirRequestPromise(oConnectFsResult.filesys_handle, "", "", CHK_ENC_MAX_PAGE_NUM);
            if (oListDirResult.items.length == 0) {
                CloseFloatMenu(oWaitingMenu);
                HtmlMsgbox(GetLocaleText("Msg_Encr_Test_Empty"), oTmpBM.sServerDirA, { bNoCurrJobName: true, icon: "properties" });
            }
            else {
                const aEncNames = [];
                yield EncryptTest(oTmpBM.sServerDirA, oConnectFsResult.filesys_handle, 0, oListDirResult, "", aErrMsg, aEncNames, [], [], oWaitingMenu);
                if (!oWaitingMenu || oWaitingMenu.bSelfDeleted) {
                    throw null;
                }
                CloseFloatMenu(oWaitingMenu);
                if (aErrMsg.length > 3) {
                    HtmlErrBox(aErrMsg.join("<br>"), GetLocaleText("Err_FailDecrFileName"), { bNoCurrJobName: true });
                }
                else {
                    if (aEncNames.length > 5) {
                        aEncNames[5] = "...";
                    }
                    HtmlMsgbox(GetLocaleText("Msg_Encr_Test_List_Encrypted") + "<br>" + aEncNames.join("<br>"), oTmpBM.sServerDirA, { bNoCurrJobName: true, icon: "properties" });
                }
            }
        }
        catch (oErr) {
            CloseFloatMenu(oWaitingMenu);
            if (oErr && oErr.error && oErr.error.message) {
                HtmlErrBox(oErr.error.message, GetLocaleText("Err_FailDecrFileName"), { bNoCurrJobName: true });
            }
        }
    });
}
function EncryptTest(sFolderPath, sFsHandle, nReqNum, oData, sPath, aErrMsg, aEncNames, aPathsForEncBodys, aFolders, oWaitingMenu) {
    return __awaiter(this, void 0, void 0, function* () {
        const aFData = oData.items;
        for (const oItem of aFData) {
            if (!oWaitingMenu || oWaitingMenu.bSelfDeleted)
                return;
            const sfPathAndName = sPath ? sPath.substring(1) + "\/" + oItem.sNameA : oItem.sNameA;
            if (oItem.sNameA.startsWith(GS_CANNOT_DECRYPT_NAME_PREFIX)) {
                if (oItem.bIsFolder) {
                    aEncNames.push(sfPathAndName + "\/");
                }
                else {
                    aEncNames.push(sfPathAndName);
                }
                continue;
            }
            if (oItem.bIsFile) {
                const nSize = Number(oItem.size);
                if (nSize < CHK_ENC_FILE_MAX_SIZE) {
                    if (aPathsForEncBodys.length < CHK_ENC_FILE_ARR_LEN) {
                        aPathsForEncBodys.push(sfPathAndName);
                    }
                }
                if (aEncNames.length < CHK_ENC_NAME_ARR_LEN) {
                    aEncNames.push(sfPathAndName);
                }
            }
            else if (oItem.bIsFolder) {
                aEncNames.push(sfPathAndName + "\/");
                if (oItem.sNameA.endsWith(CHK_ENC_PREFER_FOLDER)) {
                    aFolders.splice(0, 0, sPath + "\/" + oItem.sNameA);
                }
                else {
                    aFolders.push(sPath + "\/" + oItem.sNameA);
                }
            }
            if (aPathsForEncBodys.length >= CHK_ENC_FILE_ARR_LEN && aEncNames.length >= CHK_ENC_NAME_ARR_LEN)
                break;
        }
        if (nReqNum >= CHK_ENC_MAX_REQ_NUM
            || aPathsForEncBodys.length >= CHK_ENC_FILE_ARR_LEN && aEncNames.length >= CHK_ENC_NAME_ARR_LEN
            || !oData.next_page_token && aFolders.length == 0) {
            for (const sFile of aPathsForEncBodys) {
                if (!oWaitingMenu || oWaitingMenu.bSelfDeleted)
                    return;
                try {
                    yield OpenFile(sFsHandle, sFile);
                }
                catch (oErr) {
                    if (oErr && oErr.error && oErr.error.data && oErr.error.data.error_str == "local_err" && oErr.error.message) {
                        aErrMsg.push(sFile + ": " + oErr.error.message);
                    }
                }
                yield CloseFileRequest(sFsHandle);
            }
            return;
        }
        let nextPageTok = "";
        let sTmpPath = sPath;
        if (oData.next_page_token) {
            nextPageTok = oData.next_page_token;
        }
        else {
            if (aFolders[0] == "/_gsdata_") {
                if (aFolders.length == 1) {
                    return;
                }
                aFolders.splice(0, 1);
            }
            sTmpPath = aFolders[0];
            aFolders.splice(0, 1);
        }
        try {
            const oListDirResult = yield ListDirRequestPromise(sFsHandle, sTmpPath, nextPageTok, CHK_ENC_MAX_PAGE_NUM);
            yield EncryptTest(sFolderPath, sFsHandle, nReqNum + 1, oListDirResult, sTmpPath, aErrMsg, aEncNames, aPathsForEncBodys, aFolders, oWaitingMenu);
        }
        catch (oErr) {
            if (oErr && oErr.error && oErr.error.message) {
                aErrMsg.push(oErr.error.message + " in folder " + sTmpPath);
            }
        }
    });
}
function OpenFile(sFsHandle, sPath) {
    return __awaiter(this, void 0, void 0, function* () {
        if (!sFsHandle || !sPath)
            return;
        if (sPath.substring(0, 1) != '/') {
            sPath = '/' + sPath;
        }
        try {
            const oOpenData = yield OpenFileRequest(sFsHandle, sPath);
            const ui8Out = new Uint8Array(0);
            let nPrefSize = Number(oOpenData.preferred_buf_size);
            if (isNaN(nPrefSize) || nPrefSize == 0) {
                nPrefSize = 0x400000;
            }
            const ui8Resp = yield DownloadFile(sFsHandle, nPrefSize, ui8Out);
            if (sPath.endsWith(CHK_ENC_PREFER_NAME1) || sPath.endsWith(CHK_ENC_PREFER_NAME2)) {
                const slicedArr = Array.from(ui8Resp.slice(0, 3));
                if (slicedArr[0] == 0x1f && slicedArr[1] == 0x8b && slicedArr[2] == 0x08) {
                    return;
                }
                else {
                    const err = { "error": { "code": -32603, "message": GetLocaleText("Err_BadGzipHeader"), "data": { "error_num": 6, "error_str": "local_err" } } };
                    throw err;
                }
            }
            else {
                return;
            }
        }
        catch (err) {
            throw err;
        }
    });
}
function DownloadFile(sFsHandle, nSize, ui8In, pb) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const fileData = yield DowloadFleBufRequest(sFsHandle, nSize);
            if (fileData.buf_size) {
                if (pb) {
                    if (pb.DidDownloadStop()) {
                        throw "canceled by user";
                    }
                    pb.SetPB(fileData.buf_size);
                }
                const ui8New = new Uint8Array(decodeBase64(fileData.buf));
                const ui8Out = new Uint8Array(ui8In.length + ui8New.length);
                ui8Out.set(ui8In, 0);
                ui8Out.set(ui8New, ui8In.length);
                return yield DownloadFile(sFsHandle, nSize, ui8Out, pb);
            }
            else {
                CloseFileRequest(sFsHandle);
                return ui8In;
            }
        }
        catch (err) {
            throw err;
        }
    });
}
function ExplorerDeleteFile(xAddArgs) {
    return __awaiter(this, void 0, void 0, function* () {
        if (!xAddArgs || !xAddArgs.Branch || !xAddArgs.DTP)
            return;
        const oData = xAddArgs.Branch.fGetData();
        let sFsHandle = "";
        let pMenu = null;
        try {
            sFsHandle = yield oData.fGetFsHandle(xAddArgs.Branch, xAddArgs.Branch, {});
            const nSel = xAddArgs.DTP.fGetSelTabLen();
            let nSelRow = xAddArgs.DTP.fGetSelRowNum(0) - 1;
            if (nSelRow < 0) {
                nSelRow = 0;
            }
            if (nSel > 1) {
                const aFiles = [];
                const aFileNames = [];
                const aIndex = [];
                let bIsFolders = false;
                for (let i = 0; i < nSel; i++) {
                    const oData1 = xAddArgs.DTP.fGetSelRow(i)._branch_.fGetData();
                    if (oData1.bIsFile) {
                        aFileNames.push(oData1.sName);
                        let sfPathAndName = oData1.fGetPathAndName(xAddArgs.DTP.fGetSelRow(i)._branch_);
                        aFiles.push(sfPathAndName);
                        aIndex.unshift(i);
                    }
                    else {
                        bIsFolders = true;
                    }
                }
                let sIsFolders = "";
                if (bIsFolders) {
                    sIsFolders = "*The function for deleting FOLDERS has not yet been implemented.";
                }
                if (aFiles.length == 0) {
                    HtmlErrBox("*There are no files for deletion.<br>The function for deleting FOLDERS has not yet been implemented.", "Delete File");
                    return;
                }
                const jsAbout = { title: GetLocaleText("Str_AskDeleteItem1", ["" + aFiles.length]), bottom_box: [
                        { title: "Btn_Delete", nofinal: true, id: "BtnDelete" },
                        { title: "Btn_Cancel", "close": true, default: true },
                    ], cont: [
                        { "title": "", cont: [
                                { type: "place", id: "file_list", maxH: "98%", class: "file_list" },
                                { type: "text", title: sIsFolders, id: "wait_box" },
                            ] }
                    ] };
                const oConfirm = CreateFloatMenu(jsAbout, { width: "600px", height: -50 }, null);
                const domFileList = document.getElementById("file_list_" + oConfirm.oMenu.id);
                domFileList.innerHTML = aFileNames.join("<br>");
                pMenu = oConfirm.oMenu;
                try {
                    yield oConfirm.promise;
                }
                catch (_a) {
                    CloseFloatMenu(oConfirm.oMenu);
                    return;
                }
                const domBtnDelete = document.getElementById("BtnDelete_" + oConfirm.oMenu.id);
                domBtnDelete.disabled = true;
                const aErrors = [];
                for (const path of aFiles) {
                    const sFirst = aFileNames[0];
                    aFileNames.splice(0, 1);
                    domFileList.innerHTML = "<span class='not_conn_cell'>" + sFirst + "</span><br>" + aFileNames.join("<br>");
                    if (!oConfirm.oMenu || oConfirm.oMenu.bSelfDeleted) {
                        throw null;
                    }
                    try {
                        yield AsyncUnicSendRecivePostApiWithRetry("DeleteFile", { "filesys_handle": sFsHandle, "path": path });
                    }
                    catch (oErr) {
                        if (oErr && oErr.error && oErr.error.message) {
                            aErrors.push(path + ": " + oErr.error.message);
                        }
                    }
                    domFileList.innerHTML = aFileNames.join("<br>");
                }
                if (aErrors.length) {
                    const domMenuTitle = document.getElementById(oConfirm.oMenu.id + "_title");
                    domMenuTitle.classList.add("err_in_light_bg");
                    domMenuTitle.innerHTML = "<b>" + GetLocaleText("Err_DeleteFiles") + "</b>";
                    domFileList.classList.add("err_in_light_bg");
                    domFileList.innerHTML = aErrors.join("<br>");
                    if (xAddArgs.Branch.pParent) {
                        RefreshBrowseBranch("", { DTP: xAddArgs.DTP, Branch: xAddArgs.Branch.pParent });
                    }
                    return;
                }
                for (const i of aIndex) {
                    xAddArgs.DTP.fGetSelRow(i)._branch_.fDeleteSelf();
                }
                CloseFloatMenu(oConfirm.oMenu);
            }
            else {
                if (!oData.bIsFile) {
                    HtmlErrBox("*There are no files for deletion.<br>The function for deleting FOLDERS has not yet been implemented.", "Delete File");
                    return;
                }
                let sfPathAndName = oData.fGetPathAndName(xAddArgs.Branch);
                try {
                    yield AsyncHtmlConfirm(GetLocaleText("Str_AskDeleteFile", [sfPathAndName.startsWith("\/") ? sfPathAndName.slice(1) : sfPathAndName]), "Delete file", eMyConfDefBtn.cancel);
                }
                catch (_b) {
                    return;
                }
                yield AsyncUnicSendRecivePostApiWithRetry("DeleteFile", { "filesys_handle": sFsHandle, "path": sfPathAndName });
                xAddArgs.Branch.fDeleteSelf();
            }
            xAddArgs.DTP.fSelTabClean();
            xAddArgs.DTP.fSelTabPush(nSelRow);
            xAddArgs.DTP.ShowTable();
        }
        catch (oErr) {
            CloseFloatMenu(pMenu);
            if (oErr && oErr.error && oErr.error.message) {
                HtmlErrBox(oErr.error.message, "Delete file", { bNoCurrJobName: true });
            }
            if (xAddArgs.Branch.pParent) {
                RefreshBrowseBranch("", { DTP: xAddArgs.DTP, Branch: xAddArgs.Branch.pParent });
            }
        }
    });
}
function DowloadFileForSavingToDisk(xAddArgs) {
    return __awaiter(this, void 0, void 0, function* () {
        if (!xAddArgs || !xAddArgs.Branch)
            return;
        const oData = xAddArgs.Branch.fGetData();
        let sFsHandle = "";
        try {
            sFsHandle = yield oData.fGetFsHandle(xAddArgs.Branch, xAddArgs.Branch, pGettingFsHandleAbort);
            let sfPathAndName = oData.fGetPathAndName(xAddArgs.Branch);
            const oOpenData = yield OpenFileRequest(sFsHandle, sfPathAndName);
            let nSize = Number(oOpenData.info.size);
            const oSize = ConvertBytes(oOpenData.info.size);
            let fm1FileDowload = {
                title: "Str_DowloadFile",
                bottom_box: [],
                cont: [
                    { "title": "", cont: [
                            { type: "row", "h": "10px" },
                            { type: "text", "title": GetLocaleText("Str_DowloadFile") + " " + sfPathAndName },
                            { type: "text", "title": GetLocaleText("sSize") + ": " + oSize.nSpace1 + " " + oSize.unit },
                            { type: "row", cont: [
                                    { type: "progressbar", "id": "file_download_pb" },
                                    { type: "button", img: "stop", command: "{jsFloatMenuDescr.bStopFlag = true;}", class: "img_btn_gor_wo_border" }
                                ] },
                        ] }
                ]
            };
            const oDLControl = { "bStopFlag": false };
            const fm = CreateFloatMenu(fm1FileDowload, { width: "400px", top: "30%" }, oDLControl, { bNoModal: true, bNoCancel: true });
            fm.promise.then(() => { }).catch(() => { });
            const oPB = document.getElementById("file_download_pb_" + fm.oMenu.id);
            let pb = undefined;
            if (oPB) {
                pb = new TProgressBar(oPB.children[0], oPB.children[1], oDLControl, nSize);
            }
            const ui8Out = new Uint8Array(0);
            let nPrefSize = Number(oOpenData.preferred_buf_size);
            if (isNaN(nPrefSize) || nPrefSize == 0) {
                nPrefSize = 0x400000;
            }
            try {
                const ui8Resp = yield DownloadFile(sFsHandle, nPrefSize, ui8Out, pb);
                const blob = new Blob([new Uint8Array(ui8Resp)]);
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                const pos = sfPathAndName.lastIndexOf("/");
                if (pos >= 0) {
                    sfPathAndName = sfPathAndName.substring(pos + 1);
                }
                a.download = sfPathAndName;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                CloseFloatMenu(fm.oMenu);
            }
            catch (err) {
                ErrorMsgShow("file download", err.message, "both", true);
                CloseFileRequest(sFsHandle);
                CloseFloatMenu(fm.oMenu);
            }
            oData.fGetFsHandle(xAddArgs.Branch, null);
        }
        catch (_a) {
            if (sFsHandle) {
                oData.fGetFsHandle(xAddArgs.Branch, null);
            }
        }
    });
}
class TDownloadData {
    constructor() {
        this.oDTP = null;
        this.oBranch = null;
        this.sProblemFiles = "";
        this.nStartTime = -1;
        this.nLastTime = -1;
        this.nFiltSpeed = -1;
    }
    fClear() {
        this.oDTP = null;
        this.oBranch = null;
        this.sProblemFiles = "";
        this.nStartTime = -1;
        this.nLastTime = -1;
        this.nFiltSpeed = -1;
    }
}
const oFileDowloadData = new TDownloadData;
class TDlFoldersInfo {
    constructor(sHandle, fm) {
        this.nFiles = 0;
        this.nFolders = 0;
        this.nSize = 0;
        this.root = { sName: "", cont: [] };
        this.sFsHandle = sHandle;
        this.fm = fm;
    }
    GetFolderStructAndSize(sPathAndName, sub, oBranch) {
        return __awaiter(this, void 0, void 0, function* () {
            try {
                if (oBranch && oBranch.cont && oBranch.cont.length > 0 && !oBranch.oIsWaiting && !oBranch.bError) {
                    for (const it of oBranch.cont) {
                        if (this.fm.oMenu.bSelfDeleted) {
                            throw "canceled by user";
                        }
                        if (it.cont) {
                            this.nFolders++;
                            const oFolder = { sName: it.pathEl, cont: [], oBranch: it };
                            sub.push(oFolder);
                        }
                        else {
                            const oData = it.fGetData();
                            sub.push(oData.sName);
                            this.nFiles++;
                            const nTmp = Number(oData.size);
                            this.nSize += nTmp ? nTmp : 0;
                        }
                    }
                }
                else {
                    const oParams = { "filesys_handle": this.sFsHandle, "path": sPathAndName, "max_items": LIST_DIR_MAX_ITEM };
                    const oListDir = yield AsyncUnicSendRecivePostApiWithRetry("ListDir", oParams, { domMenu: this.fm.oMenu, oMultiPageArrs: { items: [] } });
                    for (const it of oListDir.items) {
                        if (this.fm.oMenu.bSelfDeleted) {
                            throw "canceled by user";
                        }
                        this.fm.oMenu.jsFloatMenuDescr.speedAndRest.innerHTML = sPathAndName + "/" + it.sNameA;
                        if (it.bIsFolder) {
                            this.nFolders++;
                            const oFolder = { sName: it.sNameA, cont: [] };
                            sub.push(oFolder);
                        }
                        else {
                            sub.push(it.sNameA);
                            this.nFiles++;
                            const nTmp = Number(it.size);
                            this.nSize += nTmp ? nTmp : 0;
                        }
                    }
                }
                for (const it of sub) {
                    if (this.fm.oMenu.bSelfDeleted) {
                        throw "canceled by user";
                    }
                    if (typeof it != 'string') {
                        yield this.GetFolderStructAndSize(sPathAndName + "/" + it.sName, it.cont, it.oBranch);
                    }
                }
            }
            catch (catchErr) {
                throw catchErr;
            }
        });
    }
    DownloadFiles(curr, sPath, dirHandle, sFsHandle, sServerPath) {
        return __awaiter(this, void 0, void 0, function* () {
            const oMenu = this.fm.oMenu.jsFloatMenuDescr;
            for (const it of curr.cont) {
                if (this.fm.oMenu.bSelfDeleted) {
                    throw "canceled by user";
                }
                if (typeof it == 'string') {
                    const sIt = it.startsWith("\/") ? it.slice(1) : it;
                    try {
                        yield CopyFileFromGsToDisk(dirHandle, sPath, sIt, oMenu.pb, oMenu.text2, this.fm.oMenu, sFsHandle, sServerPath);
                    }
                    catch (catchErr) {
                        if (catchErr == "canceled by user") {
                            throw "canceled by user";
                        }
                        const sPathAndName = sPath + "/" + sIt;
                        if (catchErr.message) {
                            ErrorMsgShow("Folder download", sPathAndName + " download:" + catchErr.message, "console", true);
                        }
                        else if (catchErr.error && catchErr.error.message) {
                            ErrorMsgShow("Folder download", sPathAndName + " download:" + catchErr.error.message, "console", true);
                        }
                        oFileDowloadData.sProblemFiles += "<br/>" + sPathAndName;
                        continue;
                    }
                }
                else {
                    const sPathAndName = sPath + "/" + it.sName;
                    try {
                        const subDirHandle = yield dirHandle.getDirectoryHandle(it.sName, { create: true });
                        yield this.DownloadFiles(it, sPathAndName, subDirHandle, sFsHandle, sServerPath);
                    }
                    catch (catchErr) {
                        if (catchErr == "canceled by user") {
                            throw "canceled by user";
                        }
                        if (catchErr.message) {
                            ErrorMsgShow("Folder download", sPathAndName + " download:" + catchErr.message, "console", true);
                        }
                        else if (catchErr.error && catchErr.error.message) {
                            ErrorMsgShow("Folder download", sPathAndName + " download:" + catchErr.error.message, "console", true);
                        }
                        oFileDowloadData.sProblemFiles += "<br/>" + sPathAndName;
                        continue;
                    }
                }
            }
        });
    }
}
function StreamDownloadFolderForSavingToDisk() {
    return __awaiter(this, void 0, void 0, function* () {
        if (!oFileDowloadData.oDTP)
            return;
        bStopNewsPolling = true;
        let fm = null;
        try {
            const dirHandle = yield window.showDirectoryPicker({ mode: 'readwrite' });
            fm = GetWaitingBox("Str_DowloadFolder", "", "<span class='waiting_box'></span>");
            const oDLControl = fm.oMenu.jsFloatMenuDescr;
            if (oDLControl.pb_row) {
                oDLControl.pb_row.style.display = "none";
            }
            let oDlFiles = null;
            for (let i = 0; i < oFileDowloadData.oDTP.fGetSelTabLen(); i++) {
                const oBr = oFileDowloadData.oDTP.fGetSelRow(i)._branch_;
                const oData = oBr.fGetData();
                const sFilesysHandle = yield oData.fGetFsHandle(oBr, oBr, {});
                const sPath = oData.fGetPathAndName(oBr);
                if (oData.bIsFile) {
                    if (!oDlFiles) {
                        oDlFiles = new TDlFoldersInfo(sFilesysHandle, fm);
                    }
                    oDlFiles.root.cont.push(sPath);
                    continue;
                }
                else {
                    if (oDLControl.text1) {
                        oDLControl.text1.innerHTML = "Measurement of <b>" + sPath + "</b> folder size";
                    }
                    const oDlFolders = new TDlFoldersInfo(sFilesysHandle, fm);
                    yield oDlFolders.GetFolderStructAndSize(sPath, oDlFolders.root.cont, oBr);
                    const oFolderSize = ConvertBytes("" + oDlFolders.nSize);
                    if (oDLControl.text1) {
                        oDLControl.text1.innerHTML = "Folder <b>" + sPath + "</b> has size <b>" + oFolderSize.nSpace1 + "</b> " + oFolderSize.unit;
                    }
                    if (oDLControl.pb_row) {
                        oDLControl.pb_row.style.display = "";
                    }
                    oDLControl.pb.nSize = oDlFolders.nSize;
                    const subDirHandle = yield dirHandle.getDirectoryHandle(oData.sName, { create: true });
                    oFileDowloadData.nStartTime = GetCurrTime();
                    oFileDowloadData.nLastTime = oFileDowloadData.nStartTime;
                    yield oDlFolders.DownloadFiles(oDlFolders.root, "", subDirHandle, sFilesysHandle, sPath);
                }
                oData.fGetFsHandle(oBr, null);
            }
            if (oDlFiles) {
                if (oDLControl.text1) {
                    oDLControl.text1.innerHTML = "File downloading";
                }
                if (oDLControl.pb_row) {
                    oDLControl.pb_row.style.display = "";
                }
                oFileDowloadData.nStartTime = GetCurrTime();
                oFileDowloadData.nLastTime = oFileDowloadData.nStartTime;
                yield oDlFiles.DownloadFiles(oDlFiles.root, "", dirHandle, oDlFiles.sFsHandle, "");
            }
            if (oFileDowloadData.sProblemFiles) {
                ErrorMsgShow("Folder download", GetLocaleText("Err_ProblemWithDowloadFiles") + oFileDowloadData.sProblemFiles, "msgbox", true);
            }
            oFileDowloadData.fClear();
        }
        catch (catchErr) {
            if (catchErr.name == "AbortError") {
            }
            else if (catchErr.message) {
                ErrorMsgShow("folder download", catchErr.message, "both", true);
            }
            else if (catchErr.error && catchErr.error.message) {
                ErrorMsgShow("folder download", catchErr.error.message, "both", true);
            }
            else {
                if (catchErr == "canceled by user") {
                    ErrorMsgShow("folder download", catchErr, "console", true);
                }
                else {
                    ErrorMsgShow("folder download", JSON.stringify(catchErr), "both", true);
                }
            }
        }
        if (fm) {
            fm.oMenu.fCloseMenu();
        }
        bStopNewsPolling = false;
    });
}
function CopyFileFromGsToDisk(dirHandle, sFilePath, sFileNname, pb, text2, fm, sFilesysHandle, sPath) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const oFileOpenData = yield AsyncUnicSendRecivePostApiWithRetry("OpenDownload", { "filesys_handle": sFilesysHandle, "path": sPath + sFilePath + "/" + sFileNname });
            if (!oFileOpenData)
                return null;
            const fileHandle = yield dirHandle.getFileHandle(GetFileNameOfPath(sFileNname), { create: true });
            const writableStream = yield fileHandle.createWritable();
            let nPrefSize = Number(oFileOpenData.preferred_buf_size);
            if (isNaN(nPrefSize) || !nPrefSize) {
                nPrefSize = 0x400000;
            }
            const oSize = ConvertBytes(oFileOpenData.info.size);
            text2.innerHTML = "<div class='left_3_dots'>" + sFilePath + "/" + sFileNname + "</div><div class='bold_fit_content'><b>" + oSize.nSpace1 + "</b> " + oSize.unit + "</div>";
            const oDLControl = fm.jsFloatMenuDescr;
            for (;;) {
                if (fm.bSelfDeleted) {
                    throw "canceled by user";
                }
                const sBuffContents = yield AsyncUnicSendRecivePostApiWithRetry("DownloadBuf", { "filesys_handle": sFilesysHandle, "size": nPrefSize });
                if (!sBuffContents || sBuffContents.buf_size === 0)
                    break;
                yield writableStream.write(new Blob([new Uint8Array(decodeBase64(sBuffContents.buf))]));
                if (pb) {
                    if (pb.DidDownloadStop()) {
                        throw "canceled by user";
                    }
                    pb.SetPB(sBuffContents.buf_size);
                }
                SetDiwnloadStatistic(oDLControl, pb, sBuffContents.buf_size);
            }
            yield writableStream.close();
            yield AsyncUnicSendRecivePostApiWithRetry("CloseDownload", { "filesys_handle": sFilesysHandle, "commit": true });
        }
        catch (catchErr) {
            throw catchErr;
        }
    });
}
function SetDiwnloadStatistic(oDLControl, pb, nBufSize) {
    const nCurrTime = GetCurrTime();
    if (oFileDowloadData.nStartTime > 0 && nCurrTime > oFileDowloadData.nStartTime && oDLControl.speedAndRest) {
        const nDeltaTime = nCurrTime - oFileDowloadData.nStartTime;
        const nDlAverageSpeed = (pb.nAlready / nDeltaTime) * 1000;
        const nDlCurrSpeed = (nBufSize / (nCurrTime - oFileDowloadData.nLastTime)) * 1000;
        oFileDowloadData.nLastTime = nCurrTime;
        if (oFileDowloadData.nFiltSpeed <= 0) {
            oFileDowloadData.nFiltSpeed = nDlCurrSpeed;
        }
        else {
            oFileDowloadData.nFiltSpeed += (nDlCurrSpeed - oFileDowloadData.nFiltSpeed) / 10;
        }
        if (oFileDowloadData.nFiltSpeed > 0) {
            const oSpeed = ConvertBytes("" + Math.round(nDlAverageSpeed), "" + Math.round(oFileDowloadData.nFiltSpeed));
            oDLControl.speedAndRest.innerHTML = GetLocaleText("Str_DlAverageSpeed") + " <b>" + oSpeed.nSpace1 + "</b> " + oSpeed.unit + "/sec.</br>" +
                GetLocaleText("Str_DlSpeed") + " <b>" + oSpeed.nSpace2 + "</b> " + oSpeed.unit + "/sec.</br>" +
                GetLocaleText("Str_TimeElapsed") + " " + FormatTimeDifference(nDeltaTime, " h ", " m ", " sec. ") + "</br>" +
                FormatTimeDifference((pb.nSize - pb.nAlready) / oFileDowloadData.nFiltSpeed * 1000 + 1, " h ", " m ", " sec ") + GetLocaleText("Str_DlRestTime");
        }
    }
}
function GetWaitingBox(sTitle, sText1, sText2, bNoModal, bNoCancel) {
    let fm1FileDowload = {
        "title": sTitle,
        bottom_box: [],
        cont: [
            { title: "", cont: [
                    { type: "row", "h": "10px" },
                    { type: "text", "title": sText1, id: "text1" },
                    { type: "row", id: "pb_row", cont: [
                            { type: "progressbar", id: "file_download_pb" },
                            { type: "button", img: "stop", command: "{jsFloatMenuDescr.bStopFlag = true;}", class: "img_btn_gor_wo_border" },
                        ] },
                    { type: "text", "title": "", id: "speed_and_rest" },
                    { type: "text", "title": sText2, id: "text2", class: "flex_gor" },
                ] }
        ]
    };
    const oDLControl = { "bStopFlag": false };
    const ret = CreateFloatMenu(fm1FileDowload, { width: "600px", top: "30%" }, oDLControl, { bNoModal, bNoCancel });
    const oPB = document.getElementById("file_download_pb_" + ret.oMenu.id);
    if (oPB) {
        oDLControl.pb = new TProgressBar(oPB.children[0], oPB.children[1], oDLControl);
    }
    oDLControl.text1 = document.getElementById("text1_" + ret.oMenu.id);
    oDLControl.text2 = document.getElementById("text2_" + ret.oMenu.id);
    oDLControl.pb_row = document.getElementById("pb_row_" + ret.oMenu.id);
    oDLControl.speedAndRest = document.getElementById("speed_and_rest_" + ret.oMenu.id);
    ret.promise.then(() => { }).catch(() => { });
    return ret;
}
function StreamDownloadFileForSavingToDisk() {
    return __awaiter(this, void 0, void 0, function* () {
        if (!oFileDowloadData.oDTP || !oFileDowloadData.oBranch)
            return;
        if (oFileDowloadData.oDTP.fGetSelTabLen() > 1) {
            StreamDownloadFolderForSavingToDisk();
            return;
        }
        const oData = oFileDowloadData.oBranch.fGetData();
        const sPath = oData.fGetPathAndName(oFileDowloadData.oBranch);
        let fm = null;
        let sFilesysHandle = "";
        try {
            sFilesysHandle = yield oData.fGetFsHandle(oFileDowloadData.oBranch.pParent, oFileDowloadData.oBranch, {});
            const oFileOpenData = yield AsyncUnicSendRecivePostApiWithRetry("OpenDownload", { "filesys_handle": sFilesysHandle, "path": sPath });
            if (!oFileOpenData)
                return null;
            const fileHandle = yield window.showSaveFilePicker({ suggestedName: oData.sName });
            const writableStream = yield fileHandle.createWritable();
            let nPrefSize = Number(oFileOpenData.preferred_buf_size);
            if (isNaN(nPrefSize) || !nPrefSize) {
                nPrefSize = 0x400000;
            }
            const nSize = +oFileOpenData.info.size;
            const oSize = ConvertBytes(oFileOpenData.info.size);
            fm = GetWaitingBox("Str_DowloadFolder", "<b>" + sPath + "</b> size <b>" + oSize.nSpace1 + "</b> " + oSize.unit, "");
            const oDLControl = fm.oMenu.jsFloatMenuDescr;
            oDLControl.pb.nSize = nSize;
            oFileDowloadData.nStartTime = GetCurrTime();
            for (;;) {
                const sBuffContents = yield AsyncUnicSendRecivePostApiWithRetry("DownloadBuf", { "filesys_handle": sFilesysHandle, "size": nPrefSize });
                if (!sBuffContents || sBuffContents.buf_size === 0)
                    break;
                yield writableStream.write(new Blob([new Uint8Array(decodeBase64(sBuffContents.buf))]));
                if (oDLControl.pb) {
                    if (oDLControl.pb.DidDownloadStop()) {
                        throw "canceled by user";
                    }
                    oDLControl.pb.SetPB(sBuffContents.buf_size);
                    SetDiwnloadStatistic(oDLControl, oDLControl.pb, sBuffContents.buf_size);
                }
            }
            yield writableStream.close();
            console.log("============================================================");
            console.log(`File "${oData.sName}" downloaded successfully.`);
        }
        catch (catchErr) {
            if (catchErr.name == "AbortError") {
            }
            else if (catchErr.message) {
                ErrorMsgShow("file download", catchErr.message, "both", true);
            }
            else if (catchErr.error && catchErr.error.message) {
                ErrorMsgShow("file download", catchErr.error.message, "both", true);
            }
            else {
                if (catchErr == "canceled by user") {
                    ErrorMsgShow("file download", catchErr, "console", true);
                }
                else {
                    ErrorMsgShow("file download", JSON.stringify(catchErr), "both", true);
                }
            }
        }
        try {
            yield AsyncUnicSendRecivePostApiWithRetry("CloseDownload", { "filesys_handle": sFilesysHandle, "commit": true });
        }
        catch (catchErr) {
            throw catchErr;
        }
        oData.fGetFsHandle(oFileDowloadData.oBranch.pParent, null);
        if (fm) {
            CloseFloatMenu(fm.oMenu);
        }
        oFileDowloadData.fClear();
    });
}
function openPopup(url, windowName, width, height) {
    const left = window.screenX + (window.outerWidth - width) / 2;
    const top = window.screenY + (window.outerHeight - height) / 2;
    const windowFeatures = `width=${width},height=${height},left=${left},top=${top},resizable,scrollbars`;
    const popup = window.open(url, windowName, windowFeatures);
    if (!popup) {
        HtmlErrBox(GetLocaleText("Err_PopupAuthPageBlocked"), GetLocaleText("Err_AuthErr"));
        return false;
    }
    return true;
}
function NormalizePath(s) {
    s = s.replaceAll("\\", "\/");
    while (s.startsWith("\/")) {
        s = s.slice(1);
    }
    if (s.toLowerCase() == "file:/" || s.toLowerCase() == "file://" || s.toLowerCase() == "file:///") {
        return "file://";
    }
    if (s.endsWith("://")) {
        return s;
    }
    while (s.endsWith("\/")) {
        s = s.slice(0, -1);
    }
    return s;
}
function DoJobPathsContainsOneAnother(left, right, bLeftInRight) {
    if (!left || !right)
        return false;
    left = NormalizePath(left).toUpperCase();
    right = NormalizePath(right).toUpperCase();
    const aLeft = left.split("\/");
    const aRight = right.split("\/");
    if (bLeftInRight) {
        if (aLeft.length > aRight.length)
            return false;
        for (let i = 0; i < aLeft.length; i++) {
            if (aLeft[i] != aRight[i])
                return false;
        }
    }
    else {
        for (let i = 0; i < aLeft.length && i < aRight.length; i++) {
            if (aLeft[i] != aRight[i])
                return false;
        }
    }
    return true;
}
function SeatchPathInBrowseDialog(x, value, obj, sFieldName) {
    eval("obj." + sFieldName + " = '" + value + "';");
}
class TOAuth2 {
    constructor() {
        this.sSessionHandle = "";
        this.sAuthFormId = "";
    }
    SetSessionHandle(s) {
        this.sSessionHandle = s;
    }
    SetAuthFormId(s) {
        this.sAuthFormId = s;
    }
    CheckOAuthState() {
        if (!this.sSessionHandle || !this.sAuthFormId)
            return;
        if (!document.getElementById(this.sAuthFormId)) {
            this.sSessionHandle = "";
            return;
        }
        GetOAuthStateRequest(this.sSessionHandle);
    }
    SetConnForCreateAccount(oConn) {
        if (!this.sAuthFormId)
            return;
        const oDialog = document.getElementById(this.sAuthFormId);
        if (!oDialog)
            return;
        oConn.bGraphGroupReadPermissions = oDialog.jsFloatMenuDescr.obj.bGraphGroupReadPermissions;
        oConn.bGraphDirectoryReadPerms = oDialog.jsFloatMenuDescr.obj.bGraphDirectoryReadPerms;
        if (oDialog.jsFloatMenuDescr.obj.sTenant) {
            oConn.sGeoLocationA = 'tenant:' + oDialog.jsFloatMenuDescr.obj.sTenant;
        }
        oDialog.jsFloatMenuDescr.obj.conn = oConn;
        const domPlace = document.getElementById("test_results_" + this.sAuthFormId);
        if (domPlace) {
            domPlace.innerHTML = GetLocaleText("Str_Success");
            domPlace.classList.add("oauth_success");
        }
        this.sAuthFormId = "";
    }
    GetDialog() {
        return document.getElementById(this.sAuthFormId);
    }
}
class TProgressBar {
    constructor(ind, num, control, size) {
        this.nSize = -1;
        this.nAlready = 0;
        this.domInd = ind;
        this.domNum = num;
        this.oControl = control;
        if (size) {
            this.nSize = size;
        }
    }
    SetPB(n) {
        this.nAlready += n;
        const percent = (Math.round(this.nAlready * 10000 / this.nSize) / 100) + "%";
        this.domNum.innerHTML = percent;
        this.domInd.style.width = percent;
    }
    DidDownloadStop() {
        return this.oControl.bStopFlag;
    }
}
function SmtpTest(oMenu) {
    return __awaiter(this, void 0, void 0, function* () {
        const aEmptyFilds = [];
        let oWaitingMenu = null;
        try {
            const SmtpPar = oMenu.jsFloatMenuDescr.CProgramOptionsGlobal.m_SmtpServer;
            if (SmtpPar.m_OAuthProvider === 0) {
                if (!SmtpPar.m_sHostA) {
                    aEmptyFilds.push(GetLocaleText("Str_SMTP_Host"));
                }
                if (!SmtpPar.m_sUserIdA) {
                    aEmptyFilds.push(GetLocaleText("Str_SMTP_UserID"));
                }
                if (!oMenu.jsFloatMenuDescr.sPassword) {
                    aEmptyFilds.push(GetLocaleText("Str_SMTP_Passwd"));
                }
                if (!SmtpPar.m_sSenderStrA) {
                    aEmptyFilds.push(GetLocaleText("Str_SMTP_SenderEmail"));
                }
            }
            else {
                if (!SmtpPar.m_sOAuthUserIdA) {
                    aEmptyFilds.push(GetLocaleText("Err_NotOAuthSignIn"));
                }
            }
            if (aEmptyFilds.length > 0) {
                HtmlErrBox(GetLocaleText("Err_ErrSendSMTP") + "- " + aEmptyFilds.join("<br>- "), "SMTP test");
                return;
            }
            SmtpPar.m_bUseOAuth2 = SmtpPar.m_OAuthProvider != 0;
            oWaitingMenu = CreateWaitingBox("Str_TestEmaiIsSending");
            SmtpPar.m_sPasswordEncMasterA = yield EncryptStringWithKey(oMenu.jsFloatMenuDescr.sPassword, oWebGuSettings.key, oWebGuSettings.iv);
            const oUserData = oMenu.jsFloatMenuDescr.JobServerUserInformation;
            yield AsyncUnicSendRecivePostApiWithRetry("SendEMail", {
                settings: SmtpPar,
                subject: "Test e-mail",
                body: "Test Body",
                to: oUserData.email,
                to_name: oUserData.display_name
            });
            if (oWaitingMenu && !oWaitingMenu.bSelfDeleted) {
                CloseFloatMenu(oWaitingMenu);
                HtmlMsgbox(GetLocaleText("Str_EmaiTestSuccess") + oUserData.email, "SMTP test", { bNoCurrJobName: true, icon: "success" });
            }
        }
        catch (oErr) {
            if (oErr && oErr.error && oErr.error.message && oWaitingMenu && !oWaitingMenu.bSelfDeleted) {
                HtmlErrBox(oErr.error.message, "SMTP test", { bNoCurrJobName: true });
            }
            CloseFloatMenu(oWaitingMenu);
        }
    });
}
function SetCompareProgram(oMenu, id) {
    return __awaiter(this, void 0, void 0, function* () {
        const domUrl = document.getElementById(id + "_" + oMenu.id);
        let sUrl = "";
        if (domUrl) {
            sUrl = "file:///" + domUrl.value;
            sUrl = sUrl.replaceAll("\\", "\/");
        }
        try {
            const jsData = yield AsyncUnicSendRecivePostApiWithRetry("ListFileSystems", { url: "file://" });
            const conn = new TConn;
            conn.sUrlA = sUrl;
            const oBDC = { bSetPath: true, oIFDD: { conn }, domUrl: domUrl };
            switch (id) {
                case 'mirror_folder_url':
                    {
                        oBDC.bWOFiles = true;
                        oBDC.fIsThisChoiceGood = IsGoodForMirror;
                        oBDC.sErrHint = "Err_MirrorMustBeFolder";
                        oBDC.sDialogTitile = "Str_MirrorFolder";
                    }
                    break;
                case "log_folder_url":
                    {
                        oBDC.bWOFiles = true;
                        oBDC.fIsThisChoiceGood = IsGoodForMirror;
                        oBDC.sErrHint = "Err_MirrorMustBeFolder";
                        oBDC.sDialogTitile = "Str_LogFolderGlobal";
                    }
                    break;
                default: {
                    oBDC.fIsThisChoiceGood = IsGoodForCompareProgram;
                    oBDC.sErrHint = "Err_CompareProgramCantBeFolder";
                    oBDC.sDialogTitile = "Str_CompareProg";
                }
            }
            BrowseDialogForSideUrlChange(jsData.file_systems, oBDC);
        }
        catch (oErr) {
            if (oErr && oErr.message) {
                ErrorMsgShow("ListFileSystems:", oErr.message, "msgbox");
            }
        }
    });
}
function IsGoodForCompareProgram(obj) {
    try {
        if (obj.bIsFile)
            return true;
    }
    catch (_a) {
        return false;
    }
    return false;
}
function IsGoodForMirror(obj) {
    try {
        if (obj.sName && !obj.bIsFile)
            return true;
    }
    catch (_a) {
        return false;
    }
    return false;
}
function CallRowDropMenu(sFieldName, oDepBr, oDTP, cell) {
    const rect = cell.getBoundingClientRect();
    DeleteAllDropMenu();
    let jsMenu = jsBrowseDialogFsMenu;
    if (oDepBr._level_ === 1) {
        jsMenu = jsBrowseDialogAccMenu;
    }
    else if (oDepBr._level_ > 1) {
        const oData = oDepBr._branch_.fGetData();
        oFileDowloadData.oBranch = oDepBr._branch_;
        oFileDowloadData.oDTP = oDTP;
        if (oData.bIsServer) {
            jsMenu = jsBrowseDialogServerMenu;
        }
        else if (oData.bIsFile) {
            jsMenu = jsBrowseDialogFileMenu;
        }
        else {
            jsMenu = jsBrowseDialogFolderMenu;
        }
    }
    CreateDropMenuItems(jsMenu, rect.left, rect.bottom, rect.right, cell, false, { "Branch": oDepBr._branch_, "DTP": oDTP });
}
