"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
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());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
var _a, _b;
Object.defineProperty(exports, "__esModule", { value: true });
const remoteMain = __importStar(require("@electron/remote/main"));
const electron_1 = require("electron");
const electron_window_state_1 = __importDefault(require("electron-window-state"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const get_proxy_settings_1 = require("get-proxy-settings");
const minimist_1 = __importDefault(require("minimist"));
const path = __importStar(require("path"));
const url_1 = require("url");
const commons_1 = require("@wireapp/commons");
const webapp_events_1 = require("@wireapp/webapp-events");
const ProxyAuth = __importStar(require("./auth/ProxyAuth"));
const CertificateVerifyProcManager_1 = require("./lib/CertificateVerifyProcManager");
const CoreProtocol_1 = require("./lib/CoreProtocol");
const download_1 = require("./lib/download");
const eventType_1 = require("./lib/eventType");
const LocalAccountDeletion_1 = require("./lib/LocalAccountDeletion");
const openGraph_1 = require("./lib/openGraph");
const showDialog_1 = require("./lib/showDialog");
const locale = __importStar(require("./locale"));
const getLogger_1 = require("./logging/getLogger");
const loggerUtils_1 = require("./logging/loggerUtils");
const developer_1 = require("./menu/developer");
const systemMenu = __importStar(require("./menu/system"));
const TrayHandler_1 = require("./menu/TrayHandler");
const EnvironmentUtil = __importStar(require("./runtime/EnvironmentUtil"));
const lifecycle = __importStar(require("./runtime/lifecycle"));
const OriginValidator_1 = require("./runtime/OriginValidator");
const config_1 = require("./settings/config");
const ConfigurationPersistence_1 = require("./settings/ConfigurationPersistence");
const SettingsType_1 = require("./settings/SettingsType");
const SingleSignOn_1 = require("./sso/SingleSignOn");
const AboutWindow_1 = require("./window/AboutWindow");
const ProxyPromptWindow_1 = require("./window/ProxyPromptWindow");
const WindowManager_1 = require("./window/WindowManager");
const WindowUtil = __importStar(require("./window/WindowUtil"));
remoteMain.initialize();
const APP_PATH = path.join(electron_1.app.getAppPath(), config_1.config.electronDirectory);
const INDEX_HTML = path.join(APP_PATH, 'renderer/index.html');
const LOG_DIR = path.join(electron_1.app.getPath('userData'), 'logs');
const LOG_FILE = path.join(LOG_DIR, 'electron.log');
const PRELOAD_JS = path.join(APP_PATH, 'dist/preload/preload-app.js');
const PRELOAD_RENDERER_JS = path.join(APP_PATH, 'dist/preload/preload-webview.js');
const WRAPPER_CSS = path.join(APP_PATH, 'css/wrapper.css');
const WINDOW_SIZE = {
    DEFAULT_HEIGHT: 768,
    DEFAULT_WIDTH: 1024,
    MIN_HEIGHT: 512,
    MIN_WIDTH: 398,
};
let proxyInfoArg;
const customProtocolHandler = new CoreProtocol_1.CustomProtocolHandler();
const argv = (0, minimist_1.default)(process.argv.slice(1));
const BASE_URL = EnvironmentUtil.web.getWebappUrl(argv[config_1.config.ARGUMENT.ENV]);
const fileBasedProxyConfig = ConfigurationPersistence_1.settings.restore(SettingsType_1.SettingsType.PROXY_SERVER_URL);
const logger = (0, getLogger_1.getLogger)(path.basename(__filename));
const currentLocale = locale.getCurrent();
const startHidden = Boolean(argv[config_1.config.ARGUMENT.STARTUP] || argv[config_1.config.ARGUMENT.HIDDEN]);
if (argv[config_1.config.ARGUMENT.VERSION]) {
    console.info(config_1.config.version);
    electron_1.app.exit();
}
logger.info(`Initializing ${config_1.config.name} v${config_1.config.version} ...`);
if (argv[config_1.config.ARGUMENT.PROXY_SERVER] || fileBasedProxyConfig) {
    try {
        proxyInfoArg = new url_1.URL(argv[config_1.config.ARGUMENT.PROXY_SERVER] || fileBasedProxyConfig);
        if (!argv[config_1.config.ARGUMENT.PROXY_SERVER] && fileBasedProxyConfig) {
            logger.info(`Using proxy server URL from "init.json": ${fileBasedProxyConfig}`);
            electron_1.app.commandLine.appendSwitch('proxy-server', fileBasedProxyConfig);
        }
        if (!/^(https?|socks[45]):$/.test(proxyInfoArg.protocol)) {
            throw new Error('Invalid protocol for the proxy server specified.');
        }
        if (proxyInfoArg.origin === 'null') {
            proxyInfoArg = undefined;
            throw new Error('No protocol for the proxy server specified.');
        }
    }
    catch (error) {
        logger.error(`Could not parse authenticated proxy URL: "${error.message}"`);
    }
}
const iconFileName = `logo.${EnvironmentUtil.platform.IS_WINDOWS ? 'ico' : 'png'}`;
const iconPath = path.join(APP_PATH, 'img', iconFileName);
let tray;
let isFullScreen = false;
let isQuitting = false;
let main;
Object.entries(config_1.config).forEach(([key, value]) => {
    if (typeof value === 'undefined' || (typeof value === 'number' && isNaN(value))) {
        logger.warn(`Configuration key "${key}" not defined.`);
    }
});
electron_1.app.setAppUserModelId(config_1.config.appUserModelId);
electron_1.app.commandLine.appendSwitch('disable-features', 'WebRtcHideLocalIpsWithMdns');
try {
    logger.info('GPUFeatureStatus:', electron_1.app.getGPUFeatureStatus());
    const has2dCanvas = (_b = (_a = electron_1.app.getGPUFeatureStatus()) === null || _a === void 0 ? void 0 : _a['2d_canvas']) === null || _b === void 0 ? void 0 : _b.startsWith('enabled');
    if (!has2dCanvas) {
        logger.warn('2D canvas unavailable, disabling hardware acceleration');
        electron_1.app.disableHardwareAcceleration();
    }
}
catch (error) {
    logger.warn(`Can't read GPUFeatureStatus, disabling hardware acceleration`);
    electron_1.app.disableHardwareAcceleration();
}
const bindIpcEvents = () => {
    electron_1.ipcMain.on(eventType_1.EVENT_TYPE.ACTION.SAVE_PICTURE, (_event, bytes, timestamp) => {
        return (0, download_1.downloadImage)(bytes, timestamp);
    });
    electron_1.ipcMain.on(eventType_1.EVENT_TYPE.ACTION.NOTIFICATION_CLICK, () => WindowManager_1.WindowManager.showPrimaryWindow());
    electron_1.ipcMain.on(eventType_1.EVENT_TYPE.WEBAPP.APP_LOADED, () => WindowManager_1.WindowManager.flushActionsQueue());
    electron_1.ipcMain.on(eventType_1.EVENT_TYPE.UI.BADGE_COUNT, (_event, { count, ignoreFlash }) => {
        tray.showUnreadCount(main, count, ignoreFlash);
    });
    electron_1.ipcMain.on(eventType_1.EVENT_TYPE.ACCOUNT.DELETE_DATA, (_event, id, accountId, partitionId) => __awaiter(void 0, void 0, void 0, function* () {
        yield (0, LocalAccountDeletion_1.deleteAccount)(id, accountId, partitionId);
        main.webContents.send(eventType_1.EVENT_TYPE.ACCOUNT.DATA_DELETED);
    }));
    electron_1.ipcMain.on(eventType_1.EVENT_TYPE.WRAPPER.RELAUNCH, () => lifecycle.relaunch());
    electron_1.ipcMain.on(eventType_1.EVENT_TYPE.ABOUT.SHOW, () => AboutWindow_1.AboutWindow.showWindow());
    electron_1.ipcMain.handle(eventType_1.EVENT_TYPE.ACTION.GET_OG_DATA, (_event, url) => (0, openGraph_1.getOpenGraphDataAsync)(url));
};
const checkConfigV0FullScreen = (mainWindowState) => {
    if (typeof mainWindowState.isMaximized === 'undefined' && isFullScreen === true) {
        main.maximize();
    }
};
const initWindowStateKeeper = () => {
    const loadedWindowBounds = ConfigurationPersistence_1.settings.restore(SettingsType_1.SettingsType.WINDOW_BOUNDS, {
        height: WINDOW_SIZE.DEFAULT_HEIGHT,
        width: WINDOW_SIZE.DEFAULT_WIDTH,
    });
    const showInFullScreen = ConfigurationPersistence_1.settings.restore(SettingsType_1.SettingsType.FULL_SCREEN, 'not-set-in-v0');
    const stateKeeperOptions = {
        defaultHeight: loadedWindowBounds.height,
        defaultWidth: loadedWindowBounds.width,
        path: path.join(electron_1.app.getPath('userData'), 'config'),
    };
    if (showInFullScreen !== 'not-set-in-v0') {
        stateKeeperOptions.fullScreen = showInFullScreen;
        stateKeeperOptions.maximize = showInFullScreen;
        isFullScreen = showInFullScreen;
    }
    return (0, electron_window_state_1.default)(stateKeeperOptions);
};
const showMainWindow = (mainWindowState) => __awaiter(void 0, void 0, void 0, function* () {
    const showMenuBar = ConfigurationPersistence_1.settings.restore(SettingsType_1.SettingsType.SHOW_MENU_BAR, true);
    const options = {
        autoHideMenuBar: !showMenuBar,
        backgroundColor: '#f7f8fa',
        height: mainWindowState.height,
        icon: iconPath,
        minHeight: WINDOW_SIZE.MIN_HEIGHT,
        minWidth: WINDOW_SIZE.MIN_WIDTH,
        show: false,
        title: config_1.config.name,
        titleBarStyle: 'hiddenInset',
        webPreferences: {
            backgroundThrottling: false,
            contextIsolation: false,
            nodeIntegration: false,
            preload: PRELOAD_JS,
            sandbox: false,
            webviewTag: true,
        },
        width: mainWindowState.width,
        x: mainWindowState.x,
        y: mainWindowState.y,
    };
    electron_1.ipcMain.handle(eventType_1.EVENT_TYPE.ACTION.GET_DESKTOP_SOURCES, (event, opts) => electron_1.desktopCapturer.getSources(opts));
    electron_1.ipcMain.handle(eventType_1.EVENT_TYPE.ACTION.ENCRYPT, (event, plaintext) => electron_1.safeStorage.encryptString(plaintext));
    electron_1.ipcMain.handle(eventType_1.EVENT_TYPE.ACTION.DECRYPT, (event, encrypted) => electron_1.safeStorage.decryptString(Buffer.from(encrypted)));
    main = new electron_1.BrowserWindow(options);
    remoteMain.enable(main.webContents);
    main.setMenuBarVisibility(showMenuBar);
    mainWindowState.manage(main);
    (0, CertificateVerifyProcManager_1.attachTo)(main);
    checkConfigV0FullScreen(mainWindowState);
    const webappURL = new url_1.URL(BASE_URL);
    webappURL.searchParams.set('hl', currentLocale);
    if (getLogger_1.ENABLE_LOGGING) {
        webappURL.searchParams.set('enableLogging', '@wireapp/*');
    }
    if (customProtocolHandler.hashLocation) {
        webappURL.hash = customProtocolHandler.hashLocation;
    }
    if (typeof argv[config_1.config.ARGUMENT.DEVTOOLS] !== 'undefined') {
        (0, developer_1.openDevTools)(argv[config_1.config.ARGUMENT.DEVTOOLS]).catch(() => logger.warn(`Could not open DevTools with index "${argv[config_1.config.ARGUMENT.DEVTOOLS]}". Does the account exist?`));
    }
    if (!startHidden) {
        if (!WindowUtil.isInView(main)) {
            main.center();
        }
        WindowManager_1.WindowManager.setPrimaryWindowId(main.id);
        setTimeout(() => main.show(), 800);
    }
    main.webContents.on('will-navigate', event => {
        event.preventDefault();
    });
    main.webContents.setWindowOpenHandler(details => {
        return { action: 'deny' };
    });
    main.on('focus', () => {
        systemMenu.registerGlobalShortcuts();
        main.flashFrame(false);
    });
    main.on('blur', () => systemMenu.unregisterGlobalShortcuts());
    main.on('page-title-updated', () => tray.showUnreadCount(main));
    main.on('close', event => {
        if (!isQuitting) {
            event.preventDefault();
            logger.log('Closing window...');
            if (main.isFullScreen()) {
                logger.log('Fullscreen detected, leaving full screen before hiding...');
                main.once('leave-full-screen', () => main.hide());
                main.setFullScreen(false);
            }
            else {
                main.hide();
            }
            systemMenu.unregisterGlobalShortcuts();
        }
    });
    main.webContents.on('crashed', event => {
        logger.error('WebContents crashed. Will reload the window.');
        logger.error(event);
        try {
            main.reload();
        }
        catch (error) {
            (0, showDialog_1.showErrorDialog)(`Could not reload the window: ${error.message}`);
            logger.error('Could not reload the window:', error);
        }
    });
    electron_1.app.on('child-process-gone', (event, details) => {
        logger.error('child process gone');
        logger.error(event);
        logger.error(details);
    });
    main.webContents.setZoomFactor(1);
    const mainURL = (0, url_1.pathToFileURL)(INDEX_HTML);
    mainURL.searchParams.set('env', encodeURIComponent(webappURL.href));
    mainURL.searchParams.set('focus', String(!startHidden));
    yield main.loadURL(mainURL.href);
    const wrapperCSSContent = yield fs_extra_1.default.readFile(WRAPPER_CSS, 'utf8');
    yield main.webContents.insertCSS(wrapperCSSContent);
});
const handleAppEvents = () => {
    electron_1.app.on('window-all-closed', () => __awaiter(void 0, void 0, void 0, function* () {
        if (!EnvironmentUtil.platform.IS_MAC_OS) {
            yield lifecycle.quit();
        }
    }));
    electron_1.app.on('activate', () => {
        if (main) {
            main.show();
        }
    });
    electron_1.app.on('before-quit', () => {
        isQuitting = true;
    });
    electron_1.app.on('login', (event, webContents, _responseDetails, authInfo, callback) => __awaiter(void 0, void 0, void 0, function* () {
        if (authInfo.isProxy) {
            event.preventDefault();
            const { host, port } = authInfo;
            const systemProxy = yield (0, get_proxy_settings_1.getProxySettings)();
            const systemProxySettings = systemProxy && (systemProxy.http || systemProxy.https);
            if (systemProxySettings) {
                const { credentials: { username, password }, protocol, } = systemProxySettings;
                proxyInfoArg = ProxyAuth.generateProxyURL({ host, port }, { password, protocol, username });
                logger.log('Found system proxy settings, applying settings on the main window...');
                yield applyProxySettings(proxyInfoArg, main.webContents);
                return callback(username, password);
            }
            if (proxyInfoArg) {
                electron_1.ipcMain.once(eventType_1.EVENT_TYPE.PROXY_PROMPT.SUBMITTED, (_event, promptData) => __awaiter(void 0, void 0, void 0, function* () {
                    var _a;
                    logger.log('Proxy info was submitted via prompt');
                    const { username, password } = promptData;
                    const protocol = (_a = proxyInfoArg === null || proxyInfoArg === void 0 ? void 0 : proxyInfoArg.protocol) === null || _a === void 0 ? void 0 : _a.replace(':', '');
                    proxyInfoArg = ProxyAuth.generateProxyURL({ host, port }, Object.assign(Object.assign({}, promptData), { protocol }));
                    logger.log('Proxy prompt was submitted, applying proxy settings on the main window...');
                    yield applyProxySettings(proxyInfoArg, main.webContents);
                    callback(username, password);
                }));
                electron_1.ipcMain.once(eventType_1.EVENT_TYPE.PROXY_PROMPT.CANCELED, () => __awaiter(void 0, void 0, void 0, function* () {
                    logger.log('Proxy prompt was canceled');
                    yield webContents.session.setProxy({});
                    try {
                        main.reload();
                    }
                    catch (error) {
                        (0, showDialog_1.showErrorDialog)(`Could not reload the window: ${error.message}`);
                        logger.error('Could not reload the window:', error);
                    }
                }));
                yield ProxyPromptWindow_1.ProxyPromptWindow.showWindow();
            }
        }
    }));
    electron_1.app.on('ready', () => __awaiter(void 0, void 0, void 0, function* () {
        const mainWindowState = initWindowStateKeeper();
        const appMenu = systemMenu.createMenu(isFullScreen);
        if (EnvironmentUtil.app.IS_DEVELOPMENT) {
            appMenu.append(developer_1.developerMenu);
        }
        electron_1.Menu.setApplicationMenu(appMenu);
        tray = new TrayHandler_1.TrayHandler();
        if (!EnvironmentUtil.platform.IS_MAC_OS) {
            tray.initTray();
        }
        yield showMainWindow(mainWindowState);
    }));
};
const renameFileExtensions = (files, oldExtension, newExtension) => {
    for (const file of files) {
        try {
            const fileStat = fs_extra_1.default.statSync(file);
            if (fileStat.isFile() && file.endsWith(oldExtension)) {
                fs_extra_1.default.renameSync(file, file.replace(oldExtension, newExtension));
            }
        }
        catch (error) {
            logger.error(`Failed to rename log file: "${error.message}"`);
        }
    }
};
const renameWebViewLogFiles = () => {
    try {
        const logFiles = (0, loggerUtils_1.getLogFilenames)(LOG_DIR, true);
        renameFileExtensions(logFiles, '.log', '.old');
    }
    catch (error) {
        logger.log(`Failed to read log directory with error: ${error.message}`);
    }
};
const addLinuxWorkarounds = () => {
    if (EnvironmentUtil.platform.IS_LINUX) {
        if (EnvironmentUtil.linuxDesktop.isUbuntuUnity ||
            EnvironmentUtil.linuxDesktop.isPopOS ||
            EnvironmentUtil.linuxDesktop.isGnomeX11) {
            process.env.XDG_CURRENT_DESKTOP = 'Unity';
        }
    }
};
const handlePortableFlags = () => {
    if (argv[config_1.config.ARGUMENT.USER_DATA_DIR] || argv[config_1.config.ARGUMENT.PORTABLE]) {
        const USER_PATH = argv[config_1.config.ARGUMENT.USER_DATA_DIR]
            ? path.resolve(argv[config_1.config.ARGUMENT.USER_DATA_DIR])
            : path.join(process.env.APPIMAGE || process.execPath, '../Data');
        logger.log(`Saving user data to "${USER_PATH}".`);
        electron_1.app.setPath('userData', USER_PATH);
    }
};
const applyProxySettings = (authenticatedProxyDetails, webContents) => __awaiter(void 0, void 0, void 0, function* () {
    const proxyURL = authenticatedProxyDetails.origin.split('://')[1];
    const proxyProtocol = authenticatedProxyDetails.protocol;
    const isSocksProxy = proxyProtocol === 'socks4:' || proxyProtocol === 'socks5:';
    logger.info(`Setting proxy on the window to URL "${proxyURL}" with protocol "${proxyProtocol}"...`);
    webContents.session.allowNTLMCredentialsForDomains(authenticatedProxyDetails.hostname);
    const proxyRules = isSocksProxy ? `socks=${proxyURL}` : `http=${proxyURL};https=${proxyURL}`;
    yield webContents.session.setProxy({ pacScript: '', proxyBypassRules: '', proxyRules });
});
class ElectronWrapperInit {
    constructor() {
        this.closeSSOWindow = () => {
            var _a;
            if (this.ssoWindow) {
                (_a = this.ssoWindow) === null || _a === void 0 ? void 0 : _a.close();
                this.ssoWindow = null;
            }
        };
        this.focusSSOWindow = () => {
            if (this.ssoWindow) {
                this.ssoWindow.focus();
            }
        };
        this.sendSSOWindowCloseEvent = () => {
            if (this.ssoWindow) {
                main.webContents.send(webapp_events_1.WebAppEvents.LIFECYCLE.SSO_WINDOW_CLOSED);
            }
        };
        this.logger = (0, getLogger_1.getLogger)('ElectronWrapperInit');
        this.ssoWindow = null;
        electron_1.ipcMain.on(webapp_events_1.WebAppEvents.LIFECYCLE.SSO_WINDOW_CLOSE, this.closeSSOWindow);
        electron_1.ipcMain.on(webapp_events_1.WebAppEvents.LIFECYCLE.SSO_WINDOW_FOCUS, this.focusSSOWindow);
    }
    run() {
        return __awaiter(this, void 0, void 0, function* () {
            this.logger.log('webviewProtection init');
            this.webviewProtection();
        });
    }
    webviewProtection() {
        const openLinkInNewWindowHandler = (details) => {
            if (SingleSignOn_1.SingleSignOn.isSingleSignOnLoginWindow(details.frameName)) {
                return {
                    action: 'allow',
                    overrideBrowserWindowOptions: {
                        alwaysOnTop: true,
                        backgroundColor: '#FFFFFF',
                        fullscreen: false,
                        fullscreenable: false,
                        height: 600,
                        maximizable: false,
                        minimizable: false,
                        modal: false,
                        movable: true,
                        parent: main,
                        resizable: false,
                        title: SingleSignOn_1.SingleSignOn.getWindowTitle(details.url),
                        titleBarStyle: 'default',
                        useContentSize: true,
                        webPreferences: {
                            allowRunningInsecureContent: false,
                            backgroundThrottling: false,
                            contextIsolation: true,
                            devTools: false,
                            disableBlinkFeatures: '',
                            experimentalFeatures: false,
                            images: true,
                            javascript: true,
                            nodeIntegration: false,
                            nodeIntegrationInWorker: false,
                            offscreen: false,
                            partition: '',
                            plugins: false,
                            preload: '',
                            sandbox: true,
                            scrollBounce: true,
                            spellcheck: false,
                            textAreasAreResizable: false,
                            webSecurity: true,
                            webgl: false,
                            webviewTag: false,
                        },
                        width: 480,
                    },
                };
            }
            this.logger.log('Opening an external window from a webview.');
            void WindowUtil.openExternal(details.url);
            return { action: 'deny' };
        };
        const openLinkInNewWindow = (win, url, event, frameName, options) => {
            if (SingleSignOn_1.SingleSignOn.isSingleSignOnLoginWindow(frameName)) {
                const singleSignOn = new SingleSignOn_1.SingleSignOn(win, event, url, options).init();
                return new Promise(() => {
                    singleSignOn
                        .then(sso => {
                        this.ssoWindow = sso;
                        this.ssoWindow.onClose = this.sendSSOWindowCloseEvent;
                    })
                        .catch(error => console.info(error));
                });
            }
        };
        const willNavigateInWebview = (event, url, baseUrl) => {
            if (OriginValidator_1.OriginValidator.isMatchingHost(url, baseUrl)) {
                this.logger.log(`Navigating inside <webview>. URL: ${url}`);
            }
            else {
                this.logger.log(`Preventing navigation inside <webview>. URL: ${url}`);
                event.preventDefault();
            }
        };
        const enableSpellChecking = ConfigurationPersistence_1.settings.restore(SettingsType_1.SettingsType.ENABLE_SPELL_CHECKING, true);
        electron_1.app.on('web-contents-created', (webviewEvent, contents) => __awaiter(this, void 0, void 0, function* () {
            remoteMain.enable(contents);
            contents.setWindowOpenHandler(() => {
                return { action: 'deny' };
            });
            switch (contents.getType()) {
                case 'window': {
                    contents.on('will-attach-webview', (_event, webPreferences, params) => {
                        params.autosize = 'false';
                        params.contextIsolation = 'true';
                        params.plugins = 'false';
                        webPreferences.allowRunningInsecureContent = false;
                        webPreferences.contextIsolation = false;
                        webPreferences.experimentalFeatures = false;
                        webPreferences.nodeIntegration = false;
                        webPreferences.preload = PRELOAD_RENDERER_JS;
                        webPreferences.spellcheck = enableSpellChecking;
                        webPreferences.webSecurity = true;
                        webPreferences.sandbox = false;
                    });
                    break;
                }
                case 'webview': {
                    if ((proxyInfoArg === null || proxyInfoArg === void 0 ? void 0 : proxyInfoArg.origin) && contents.session) {
                        this.logger.log('Found proxy settings in arguments, applying settings on the webview...');
                        yield applyProxySettings(proxyInfoArg, contents);
                    }
                    contents.setWindowOpenHandler(openLinkInNewWindowHandler);
                    contents.on('did-create-window', (win, { url, frameName, options }) => __awaiter(this, void 0, void 0, function* () {
                        yield openLinkInNewWindow(win, url, webviewEvent, frameName, options);
                    }));
                    contents.on('will-navigate', (event, url) => {
                        willNavigateInWebview(event, url, contents.getURL());
                    });
                    if (getLogger_1.ENABLE_LOGGING) {
                        const colorCodeRegex = /%c(.+?)%c/gm;
                        const accessTokenRegex = /access_token=[^ &]+/gm;
                        contents.on('console-message', (_event, _level, message) => __awaiter(this, void 0, void 0, function* () {
                            const webViewId = lifecycle.getWebViewId(contents);
                            const accountIndex = contents.id - 2;
                            if (webViewId) {
                                const logFilePath = path.join(LOG_DIR, `${accountIndex}_${webViewId}`, config_1.config.logFileName);
                                try {
                                    yield commons_1.LogFactory.writeMessage(message.replace(colorCodeRegex, '$1').replace(accessTokenRegex, ''), logFilePath);
                                }
                                catch (error) {
                                    logger.error(`Cannot write to log file "${logFilePath}": ${error.message}`, error);
                                }
                            }
                        }));
                    }
                    if (enableSpellChecking) {
                        try {
                            const availableSpellCheckerLanguages = contents.session.availableSpellCheckerLanguages;
                            const foundLanguages = locale.supportedSpellCheckLanguages[currentLocale].filter(language => availableSpellCheckerLanguages.includes(language));
                            contents.session.setSpellCheckerLanguages(foundLanguages);
                        }
                        catch (error) {
                            logger.error(error);
                            contents.session.setSpellCheckerLanguages([]);
                        }
                    }
                    contents.session.setSSLConfig({ minVersion: 'tls1.2' });
                    contents.session.setCertificateVerifyProc(CertificateVerifyProcManager_1.setCertificateVerifyProc);
                    contents.on('before-input-event', (_event, input) => {
                        if (input.type === 'keyUp' && input.key === 'Alt') {
                            const mainBrowserWindow = WindowManager_1.WindowManager.getPrimaryWindow();
                            if (mainBrowserWindow) {
                                const isAutoHide = mainBrowserWindow.isMenuBarAutoHide();
                                const isVisible = mainBrowserWindow.isMenuBarVisible();
                                if (isAutoHide) {
                                    mainBrowserWindow.setMenuBarVisibility(!isVisible);
                                }
                            }
                        }
                    });
                    break;
                }
            }
        }));
    }
}
customProtocolHandler.registerCoreProtocol();
handlePortableFlags();
lifecycle
    .checkSingleInstance()
    .then(() => lifecycle.initSquirrelListener())
    .catch(error => logger.error(error));
if (lifecycle.isFirstInstance) {
    addLinuxWorkarounds();
    bindIpcEvents();
    handleAppEvents();
    renameWebViewLogFiles();
    fs_extra_1.default.ensureFileSync(LOG_FILE);
    new ElectronWrapperInit().run().catch(error => logger.error(error));
}
//# sourceMappingURL=main.js.map