"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const rsa = require("node-rsa"); const node_fetch_1 = require("node-fetch"); class SecureFile { constructor(server, username, private_key) { this.Server = server; this.Username = username; this.PrivateKey = private_key; } async getCode() { let code_res = await node_fetch_1.default(this.Server + "/code?username=" + this.Username); //ToDo check status Codes let code = (await code_res.json()).code; let r = new rsa(this.PrivateKey, "pkcs1-pem"); return { code: code, signature: r.sign(code).toString("base64") }; } async makeRequest(endpoint, method, query, body) { let code = await this.getCode(); query.code = code.code; query.signature = code.signature; let query_str = "?"; let first = true; for (let key in query) { if (!first) query_str += "&"; query_str += encodeURIComponent(key) + "=" + encodeURIComponent(query[key]); first = false; } return await node_fetch_1.default(this.Server + endpoint + query_str, { method: method, body: body }); } async list(folder) { if (!folder) folder = "root"; let res = await this.makeRequest("/files", "GET", { folder: folder }, undefined); statusParser(res); return await res.json(); } async create(name, data, type, folder, preview) { let res = await this.makeRequest("/files", "POST", { type: type, name: name, preview: preview, folder: folder }, data); statusParser(res); return res.json(); } async get(id, version) { let res; if (typeof version === "string") { res = await this.makeRequest(`/files/${id}/history/${version}`, "GET", {}, undefined); } else { res = await this.makeRequest("/files/" + id, "GET", {}, undefined); } statusParser(res); return res.buffer(); } async update(id, data, preview) { let put = {}; if (preview) put.preview = preview; let res = await this.makeRequest("/files/" + id, "PUT", put, data); statusParser(res); return res.json(); } async delete(id) { let res = await this.makeRequest("/files/" + id, "DELETE", {}, undefined); statusParser(res); return res.json(); } async history(id) { let res = await this.makeRequest(`/files/${id}/history`, "GET", {}, undefined); statusParser(res); return res.json(); } } exports.default = SecureFile; class Unauthorized extends Error { constructor() { super("Not authorized"); } } exports.Unauthorized = Unauthorized; class NotFound extends Error { constructor() { super("Not found"); } } exports.NotFound = NotFound; class BadRequest extends Error { constructor() { super("Bad request"); } } exports.BadRequest = BadRequest; function statusParser(res) { if (res.status !== 200) { switch (res.status) { case 400: throw new BadRequest(); case 404: throw new NotFound(); case 403: throw new Unauthorized(); default: throw new Error(res.statusText); } } }