"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.authenticateWithCode = void 0;
exports.newFileApi = newFileApi;
exports.initFileApi = initFileApi;
const file_api_driver_joplinServer_1 = require("./file-api-driver-joplinServer");
const Setting_1 = require("./models/Setting");
const locale_js_1 = require("./locale.js");
const JoplinServerApi_1 = require("./JoplinServerApi");
const file_api_1 = require("./file-api");
const SyncTargetJoplinServer_1 = require("./SyncTargetJoplinServer");
async function newFileApi(id, options) {
    const apiOptions = {
        baseUrl: () => options.path(),
        userContentBaseUrl: () => options.userContentPath(),
        username: () => '',
        password: () => '',
        apiKey: () => Setting_1.default.value('sync.11.apiKey'),
        session: () => ({ id: Setting_1.default.value('sync.11.id'), user_id: Setting_1.default.value('sync.11.userId') }),
        env: Setting_1.default.value('env'),
    };
    const api = new JoplinServerApi_1.default(apiOptions);
    const driver = new file_api_driver_joplinServer_1.default(api);
    const fileApi = new file_api_1.FileApi('', driver);
    fileApi.setSyncTargetId(id);
    await fileApi.initialize();
    return fileApi;
}
async function initFileApi(syncTargetId, logger, options) {
    const fileApi = await newFileApi(syncTargetId, options);
    fileApi.setLogger(logger);
    return fileApi;
}
const authenticateWithCode = async (code) => {
    try {
        const response = await fetch(`${Setting_1.default.value('sync.11.path')}/api/login_with_code/${code}`);
        if (response.status !== 200) {
            return false;
        }
        const token = await response.json();
        Setting_1.default.setValue('sync.11.id', token.id);
        Setting_1.default.setValue('sync.11.userId', token.user_id);
    }
    catch (_e) {
        return false;
    }
    return true;
};
exports.authenticateWithCode = authenticateWithCode;
// A sync target for Joplin Server that uses SAML for authentication.
//
// Based on the regular Joplin Server sync target.
class SyncTargetJoplinServerSAML extends SyncTargetJoplinServer_1.default {
    constructor() {
        super(...arguments);
        this.lastFileApiOptions_ = null;
    }
    static id() {
        return 11;
    }
    static targetName() {
        return 'joplinServerSaml';
    }
    static label() {
        return `${(0, locale_js_1._)('Joplin Server (SAML)')}`;
    }
    async isAuthenticated() {
        if (!Setting_1.default.value('sync.11.id'))
            return false;
        // We check that the file API has been initialized at least once, otherwise the below check
        // will always fail and it will be impossible to login.
        if (this.lastFileApiOptions_) {
            const check = await SyncTargetJoplinServer_1.default.checkConfig(null, null, await this.fileApi());
            return check.ok;
        }
        return true;
    }
    static requiresPassword() {
        return false;
    }
    static async checkConfig(fileApi) {
        try {
            // Simulate a login request
            const result = await fetch(`${fileApi.path()}/api/saml`);
            if (result.status === 200) { // The server successfully responded, SAML is enabled
                return {
                    ok: true,
                    errorMessage: '',
                };
            }
            else { // SAML is disabled or an error occurred
                const text = await result.text();
                let message = text; // Use the textual body as the default message
                // Check if we got an error message
                if (result.headers.get('Content-Type').includes('application/json')) {
                    try {
                        const json = JSON.parse(text);
                        if (json.error) {
                            message = json.error;
                        }
                    }
                    catch (_e) { } // eslint-disable-line no-empty -- Keep the plain text response as the error message, ignore the parsing exception
                }
                return {
                    ok: false,
                    errorMessage: `Could not connect to server: Error ${result.status}: ${message}`,
                };
            }
        }
        catch (e) {
            return {
                ok: false,
                errorMessage: e.message,
            };
        }
    }
    async initFileApi() {
        this.lastFileApiOptions_ = {
            path: () => Setting_1.default.value('sync.11.path'),
            userContentPath: () => Setting_1.default.value('sync.11.userContentPath'),
            username: () => '',
            password: () => '',
            apiKey: () => Setting_1.default.value('sync.11.apiKey'),
        };
        return initFileApi(SyncTargetJoplinServerSAML.id(), this.logger(), this.lastFileApiOptions_);
    }
}
exports.default = SyncTargetJoplinServerSAML;
//# sourceMappingURL=SyncTargetJoplinServerSAML.js.map