"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    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) : new P(function (resolve) { resolve(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 };
};
Object.defineProperty(exports, "__esModule", { value: true });
const axios_1 = __importDefault(require("axios"));
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const typedi_1 = require("typedi");
const services_1 = require("../../services");
let UtilsController = class UtilsController {
    regist(router) {
        // 下载证书
        router.get('/utils/rootCA.crt', ctx => {
            ctx.set('Content-disposition', 'attachment;filename=zproxy.crt');
            const filePath = path_1.default.join(this.appInfoService.getProxyDataDir(), 'certificate/root/zproxy.crt.pem');
            ctx.body = fs_1.default.createReadStream(filePath, { encoding: 'utf-8' });
        });
        router.get('/pac', (ctx) => __awaiter(this, void 0, void 0, function* () {
            const ip = this.appInfoService.getPcIp();
            const port = this.appInfoService.getHttpProxyPort();
            const matchScripts = [];
            const userIDs = Object.keys(this.ruleService.rules);
            for (const userID of userIDs) {
                const userRuleFilesMap = this.ruleService.rules[userID];
                const userRuleFiles = Object.keys(userRuleFilesMap).map(k => userRuleFilesMap[k]);
                for (const ruleFile of userRuleFiles) {
                    for (const rule of ruleFile.content) {
                        matchScripts.push(`if (url.indexOf("${rule.match}") > -1) { return zProxy; }`);
                        matchScripts.push(`try {
                if ((new RegExp("${rule.match}")).test(url)) { return zProxy; }
              } catch(e){}`);
                    }
                }
                const hostFileList = this.hostService.getHostFileList(userID);
                for (const hostFile of hostFileList) {
                    const hf = this.hostService.getHostFile(userID, hostFile.name);
                    if (!hf) {
                        continue;
                    }
                    const hostFileContent = hf.content;
                    const hosts = Object.keys(hostFileContent);
                    for (const host of hosts) {
                        matchScripts.push(`if ( host == "${host}" ) { return zProxy; }`);
                        if (host.startsWith('*')) {
                            matchScripts.push(`if ( host.indexOf("${host.substr(1, host.length)}") > -1 ) { return zProxy; } `);
                        }
                    }
                }
            }
            const pac = `\n\
                        var direct = 'DIRECT;';\n\
                        var zProxy = 'PROXY ${ip}:${port}';\n\
                        function FindProxyForURL(url, host) {\n\
                            ${matchScripts.join('\n')}
                            return direct;\n\
                       }`;
            ctx.set('Content-Type', 'application/x-javascript-config');
            ctx.body = pac;
        }));
        router.get('/utils/download', (ctx) => __awaiter(this, void 0, void 0, function* () {
            axios_1.default.get(ctx.query.url);
        }));
    }
};
__decorate([
    typedi_1.Inject(),
    __metadata("design:type", services_1.AppInfoService)
], UtilsController.prototype, "appInfoService", void 0);
__decorate([
    typedi_1.Inject(),
    __metadata("design:type", services_1.HostService)
], UtilsController.prototype, "hostService", void 0);
__decorate([
    typedi_1.Inject(),
    __metadata("design:type", services_1.RuleService)
], UtilsController.prototype, "ruleService", void 0);
UtilsController = __decorate([
    typedi_1.Service()
], UtilsController);
exports.UtilsController = UtilsController;
//# sourceMappingURL=utils.js.map