OSSecureFileWrapper/src/index.ts

223 lines
5.8 KiB
TypeScript

import Observable from "./observable";
import Lock from "./lock";
export interface IFileVersion {
version: string;
time: Date;
preview: string;
deleted: boolean;
}
export interface IFile {
_id: string;
type: string;
name: string;
folder: string;
deleted: boolean;
active: IFileVersion;
versions: IFileVersion[];
user: string;
application: string;
}
export interface IHistory {
file: IFile;
history: IFileVersion[];
}
export class NoConnection extends Error {
type: string;
constructor() {
super("No connection");
this.type = "noconnection"
}
}
export class Unauthorized extends Error {
type: string;
constructor() {
super("Not authorized");
this.type = "unauthorized"
}
}
export class NoPermission extends Error {
type: string;
constructor() {
super("No permission");
this.type = "nopermission"
}
}
export class NotFound extends Error {
type: string;
constructor() {
super("Not found");
this.type = "notfound"
}
}
export class BadRequest extends Error {
type: string;
constructor() {
super("Bad request");
this.type = "badrequest"
}
}
import * as fetch from "isomorphic-fetch";
function statusParser(res: Response) {
if (res.status !== 200) {
switch (res.status) {
case 400:
throw new BadRequest();
case 404:
throw new NotFound();
case 403:
throw new NoPermission();
case 401:
throw new Unauthorized();
default:
throw new Error(res.statusText);
}
}
}
export default class SecureFileWrapper {
private _jwtObservableServer: Observable<(jwt: string) => void> = new Observable();
jwtObservable = this._jwtObservableServer.getPublicApi();
jwt: string;
auth_lock = new Lock();
constructor(private server: string) {
if (this.server.endsWith("/")) {
this.server += "api/v1";
} else {
this.server += "/api/v1";
}
}
public async getJWT() {
if (!this.auth_lock.locked) {
let lock = await this.auth_lock.getLock();
this._jwtObservableServer.send((jwt: string) => {
this.jwt = jwt;
lock.release();
});
}
await this.auth_lock.getLock().then(lock => lock.release())
}
public async makeRequest(endpoint: string, method: "POST" | "GET" | "PUT" | "DELETE", query: any, body?: ArrayBuffer | ArrayBufferView, second = false) {
if (!this.jwt || this.jwt === undefined) {
await this.getJWT();
}
query.jwt = this.jwt;
let query_str = "?";
let first = true;
for (let key in query) {
if (!first) query_str += "&";
query_str += encodeURIComponent(key) + "=" + encodeURIComponent(query[key]);
first = false;
}
var headers = {
"pragme": "no-cache",
"cache-control": "no-cache"
};
let body_n;
if (body) {
headers["Content-Type"] = "application/octet-stream"
body_n = Buffer ? Buffer.from(body instanceof ArrayBuffer ? body : body.buffer) : body;
}
try {
let res = await fetch(this.server + endpoint + query_str, { method, body: body_n, headers });
if (res.status === 401 && !second) {
await this.getJWT();
return this.makeRequest(endpoint, method, query, body, true);
} else {
statusParser(res);
return res;
}
} catch (err) {
if (err instanceof TypeError || err.errno === "ECONNREFUSED")
throw new NoConnection();
throw err;
}
}
// async test(jwt): Promise<{ user: string, test: true }> {
// let res = await this.makeRequest("/test", "GET", {}, undefined, this.jwt_enabled);
// statusParser(res);
// return await res.json();
// }
async list(folder?: string): Promise<IFile[]> {
let query: any = {}
if (folder) query.folder = folder;
let res = await this.makeRequest("/files", "GET", query);
let d = await res.json();
return d.files;
}
async create(name: string, data: ArrayBuffer | ArrayBufferView, type: "text" | "binary", folder?: string, preview?: string): Promise<IFile> {
let params: any = { type: type, name: name };
if (preview) {
params.preview = preview;
}
if (folder) {
params.folder = folder;
}
let res = await this.makeRequest("/files", "POST", params, data);
return (await res.json()).file;
}
async get(id: string, version?: string): Promise<ArrayBuffer> {
let res: Response;
if (typeof version === "string") {
res = await this.makeRequest(`/files/${id}/history/${version}`, "GET", {});
} else {
res = await this.makeRequest("/files/" + id, "GET", {});
}
if (res.arrayBuffer) {
return res.arrayBuffer()
} else {
let blob: Buffer = await (<any>res).buffer()
// console.log(blob.length);
return Uint8Array.from(blob).buffer;
}
}
async update(id: string, data: ArrayBuffer | ArrayBufferView, preview?: string): Promise<IFile> {
let put: any = {};
if (preview) put.preview = preview;
let res = await this.makeRequest("/files/" + id, "PUT", put, data);
let json = await res.json()
return json.file;
}
async delete(id: string): Promise<boolean> {
let res = await this.makeRequest("/files/" + id, "DELETE", {});
return res.json();
}
async history(id: string): Promise<IHistory> {
let res = await this.makeRequest(`/files/${id}/history`, "GET", {});
statusParser(res);
return res.json();
}
async restore(id: string, version: string) {
await this.makeRequest(`/files/${id}/history/${version}/restore`, "PUT", {});
}
}