"use strict";
/*
API endpoint to copy from a URL on the internet to a project.

This requires the user to be signed in with appropriate access to the project.

If project doesn't have network access, we stop the project, start it with
network access, get the content, then restart the project without network access.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const get_account_1 = __importDefault(require("lib/account/get-account"));
const misc_1 = require("@cocalc/util/misc");
const is_collaborator_1 = __importDefault(require("@cocalc/server/projects/is-collaborator"));
const get_params_1 = __importDefault(require("lib/api/get-params"));
const call_1 = __importDefault(require("@cocalc/server/projects/connection/call"));
const get_proxied_public_path_info_1 = __importDefault(require("lib/share/proxy/get-proxied-public-path-info"));
async function handle(req, res) {
    const params = (0, get_params_1.default)(req);
    const error = checkParams(params);
    if (error) {
        res.json({ error });
        return;
    }
    const { project_id, url, // the supported schema is as in next/lib/share/proxy/get-public-path.ts).
    path, // where to write the contents of the url
     } = params;
    try {
        const account_id = await (0, get_account_1.default)(req);
        if (!account_id) {
            throw Error("must be signed in");
        }
        if (!(0, is_collaborator_1.default)({ account_id, project_id })) {
            throw Error("must be a collaborator on target project");
        }
        const info = await (0, get_proxied_public_path_info_1.default)(url);
        if (info.contents?.content == null) {
            throw Error("copying of directories (e.g., full GitHub repos) is not implemented; copy an individual file instead");
        }
        const i = url.lastIndexOf("/");
        const filename = url.slice(i + 1);
        const mesg = {
            event: "write_text_file_to_project",
            path: path ? path : filename,
            content: info.contents.content,
        };
        const response = await (0, call_1.default)({ project_id, mesg });
        res.json({ response });
    }
    catch (err) {
        res.json({ error: `${err.message}` });
    }
}
exports.default = handle;
function checkParams(obj) {
    if (!obj.url)
        return "url must be specified";
    if (!(0, misc_1.isValidUUID)(obj.project_id))
        return "project_id must be a valid uuid";
}
//# sourceMappingURL=copy-url.js.map