"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.basicWeb = basicWeb;
exports.detectBasicAgent = detectBasicAgent;
const auth_1 = require("./auth");
const cross_const_1 = require("./cross-const");
const config_1 = require("./config");
const vfs_1 = require("./vfs");
const misc_1 = require("./misc");
const lodash_1 = __importDefault(require("lodash"));
const adminApis_1 = require("./adminApis");
const customHtml_1 = require("./customHtml");
const autoBasic = (0, config_1.defineConfig)('auto_basic', true, v => lodash_1.default.isString(v) ? new RegExp(v, 'i') : null);
function basicWeb(ctx, node) {
    const { get } = ctx.query;
    if (get === 'login') {
        if ((0, auth_1.getCurrentUsername)(ctx))
            ctx.redirect(ctx.get('referer'));
        else {
            ctx.set('WWW-Authenticate', cross_const_1.BASIC_AUTHENTICATE_HEADER);
            ctx.status = cross_const_1.HTTP_UNAUTHORIZED;
        }
        return true;
    }
    if (get === 'logout') {
        ctx.body = `<script>location = ${JSON.stringify(ctx.get('referer'))}</script>`;
        (0, auth_1.setLoggedIn)(ctx, false);
        ctx.status = cross_const_1.HTTP_UNAUTHORIZED; // not effective on firefox52, but the redirection is
        return true;
    }
    const forced = get === 'basic';
    const goBasic = forced || detectBasicAgent(ctx) && get !== 'nobasic';
    if (!goBasic)
        return;
    ctx.type = 'html';
    const force = forced ? '?get=basic' : '';
    const walker = (0, vfs_1.walkNode)(node, { ctx, depth: 0 });
    const stream = (0, misc_1.asyncGeneratorToReadable)((0, misc_1.filterMapGenerator)(walker, async (el) => {
        const isFolder = (0, vfs_1.nodeIsFolder)(el);
        const name = (0, vfs_1.getNodeName)(el) + (isFolder ? '/' : '');
        return `<li>${a((0, misc_1.pathEncode)(name) + (isFolder && !await (0, vfs_1.getDefaultFile)(el, ctx) ? force : ''), name)}\n`;
    }));
    ctx.body = stream;
    stream.push(`<meta name="viewport" content="width=device-width" />`);
    stream.push(`<style>body { font-size: 16pt; }</style>`);
    stream.push(`<title>${adminApis_1.title.get()}</title><body>`);
    stream.push((0, customHtml_1.getSection)('basicHeader'));
    const u = (0, auth_1.getCurrentUsername)(ctx);
    const links = u ? { [`//LOGOUT%00:@${ctx.host}/?get=logout`]: `Logout (${u})` } : { '/?get=login': "Login" };
    stream.push(lodash_1.default.map(links, (v, k) => a(k, v)).join(' ') + '\n<ul>\n');
    if (ctx.state.originalPath.length > 1)
        stream.push('<li>' + a('..' + force, '..') + '\n');
    stream.on('ending', () => stream.push('</ul>\n' + (0, customHtml_1.getSection)('basicFooter')));
    return true;
    function a(href, label) {
        return `<a href='${href}'>${label}</a>`;
    }
}
function detectBasicAgent(ctx) {
    const ua = ctx.get('user-agent');
    return autoBasic.get() && /^$|Mozilla\/4|WebKit\/([234]\d\d|5[012]\d|53[0123456])[. ]|Trident|Lynx|curl|Firefox\/(\d|[1234]\d)\./.test(ua)
        || autoBasic.compiled()?.test(ua);
}
