"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GeoIP = void 0;
const tslib_1 = require("tslib");
const fs_extra_1 = require("fs-extra");
const maxmind_1 = tslib_1.__importDefault(require("maxmind"));
const path_1 = require("path");
const config_1 = require("../initializers/config");
const logger_1 = require("./logger");
const requests_1 = require("./requests");
const lTags = (0, logger_1.loggerTagsFactory)('geo-ip');
const mmbdFilename = 'dbip-country-lite-latest.mmdb';
const mmdbPath = (0, path_1.join)(config_1.CONFIG.STORAGE.BIN_DIR, mmbdFilename);
class GeoIP {
    constructor() {
    }
    safeCountryISOLookup(ip) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            if (config_1.CONFIG.GEO_IP.ENABLED === false)
                return null;
            yield this.initReaderIfNeeded();
            try {
                const result = this.reader.get(ip);
                if (!result)
                    return null;
                return result.country.iso_code;
            }
            catch (err) {
                logger_1.logger.error('Cannot get country from IP.', { err });
                return null;
            }
        });
    }
    updateDatabase() {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            if (config_1.CONFIG.GEO_IP.ENABLED === false)
                return;
            const url = config_1.CONFIG.GEO_IP.COUNTRY.DATABASE_URL;
            logger_1.logger.info('Updating GeoIP database from %s.', url, lTags());
            const gotOptions = { context: { bodyKBLimit: 200000 }, responseType: 'buffer' };
            try {
                const gotResult = yield (0, requests_1.peertubeGot)(url, gotOptions);
                if (!(0, requests_1.isBinaryResponse)(gotResult)) {
                    throw new Error('Not a binary response');
                }
                yield (0, fs_extra_1.writeFile)(mmdbPath, gotResult.body);
                this.reader = undefined;
                logger_1.logger.info('GeoIP database updated %s.', mmdbPath, lTags());
            }
            catch (err) {
                logger_1.logger.error('Cannot update GeoIP database from %s.', url, Object.assign({ err }, lTags()));
            }
        });
    }
    initReaderIfNeeded() {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            if (!this.reader) {
                if (!(yield (0, fs_extra_1.pathExists)(mmdbPath))) {
                    yield this.updateDatabase();
                }
                this.reader = yield maxmind_1.default.open(mmdbPath);
            }
        });
    }
    static get Instance() {
        return this.instance || (this.instance = new this());
    }
}
exports.GeoIP = GeoIP;
//# sourceMappingURL=geo-ip.js.map