feat: migrate to vue 3 (#2689)

---------

Co-authored-by: Joep <jcbuhre@gmail.com>
Co-authored-by: Omar Hussein <omarmohammad1951@gmail.com>
Co-authored-by: Oleg Lobanov <oleg@lobanov.me>
This commit is contained in:
kloon15
2024-04-01 17:18:22 +02:00
committed by GitHub
parent 0e3b35b30e
commit 5100e587d7
164 changed files with 12202 additions and 8047 deletions

View File

@@ -1,15 +1,22 @@
import { removePrefix } from "./utils";
import { baseURL } from "@/utils/constants";
import store from "@/store";
import { useAuthStore } from "@/stores/auth";
const ssl = window.location.protocol === "https:";
const protocol = ssl ? "wss:" : "ws:";
export default function command(url, command, onmessage, onclose) {
url = removePrefix(url);
url = `${protocol}//${window.location.host}${baseURL}/api/command${url}?auth=${store.state.jwt}`;
export default function command(
url: string,
command: string,
onmessage: WebSocket["onmessage"],
onclose: WebSocket["onclose"]
) {
const authStore = useAuthStore();
let conn = new window.WebSocket(url);
url = removePrefix(url);
url = `${protocol}//${window.location.host}${baseURL}/api/command${url}?auth=${authStore.jwt}`;
const conn = new window.WebSocket(url);
conn.onopen = () => conn.send(command);
conn.onmessage = onmessage;
conn.onclose = onclose;

View File

@@ -1,19 +1,20 @@
import { createURL, fetchURL, removePrefix } from "./utils";
import { baseURL } from "@/utils/constants";
import store from "@/store";
import { useAuthStore } from "@/stores/auth";
import { upload as postTus, useTus } from "./tus";
export async function fetch(url) {
export async function fetch(url: string) {
url = removePrefix(url);
const res = await fetchURL(`/api/resources${url}`, {});
let data = await res.json();
const data = (await res.json()) as Resource;
data.url = `/files${url}`;
if (data.isDir) {
if (!data.url.endsWith("/")) data.url += "/";
data.items = data.items.map((item, index) => {
// Perhaps change the any
data.items = data.items.map((item: any, index: any) => {
item.index = index;
item.url = `${data.url}${encodeURIComponent(item.name)}`;
@@ -28,10 +29,12 @@ export async function fetch(url) {
return data;
}
async function resourceAction(url, method, content) {
async function resourceAction(url: string, method: ApiMethod, content?: any) {
url = removePrefix(url);
let opts = { method };
const opts: ApiOpts = {
method,
};
if (content) {
opts.body = content;
@@ -42,15 +45,15 @@ async function resourceAction(url, method, content) {
return res;
}
export async function remove(url) {
export async function remove(url: string) {
return resourceAction(url, "DELETE");
}
export async function put(url, content = "") {
export async function put(url: string, content = "") {
return resourceAction(url, "PUT", content);
}
export function download(format, ...files) {
export function download(format: any, ...files: string[]) {
let url = `${baseURL}/api/raw`;
if (files.length === 1) {
@@ -58,7 +61,7 @@ export function download(format, ...files) {
} else {
let arg = "";
for (let file of files) {
for (const file of files) {
arg += removePrefix(file) + ",";
}
@@ -71,14 +74,20 @@ export function download(format, ...files) {
url += `algo=${format}&`;
}
if (store.state.jwt) {
url += `auth=${store.state.jwt}&`;
const authStore = useAuthStore();
if (authStore.jwt) {
url += `auth=${authStore.jwt}&`;
}
window.open(url);
}
export async function post(url, content = "", overwrite = false, onupload) {
export async function post(
url: string,
content: ApiContent = "",
overwrite = false,
onupload: any = () => {}
) {
// Use the pre-existing API if:
const useResourcesApi =
// a folder is being created
@@ -93,10 +102,15 @@ export async function post(url, content = "", overwrite = false, onupload) {
: postTus(url, content, overwrite, onupload);
}
async function postResources(url, content = "", overwrite = false, onupload) {
async function postResources(
url: string,
content: ApiContent = "",
overwrite = false,
onupload: any
) {
url = removePrefix(url);
let bufferContent;
let bufferContent: ArrayBuffer;
if (
content instanceof Blob &&
!["http:", "https:"].includes(window.location.protocol)
@@ -104,14 +118,15 @@ async function postResources(url, content = "", overwrite = false, onupload) {
bufferContent = await new Response(content).arrayBuffer();
}
const authStore = useAuthStore();
return new Promise((resolve, reject) => {
let request = new XMLHttpRequest();
const request = new XMLHttpRequest();
request.open(
"POST",
`${baseURL}/api/resources${url}?override=${overwrite}`,
true
);
request.setRequestHeader("X-Auth", store.state.jwt);
request.setRequestHeader("X-Auth", authStore.jwt);
if (typeof onupload === "function") {
request.upload.onprogress = onupload;
@@ -135,12 +150,17 @@ async function postResources(url, content = "", overwrite = false, onupload) {
});
}
function moveCopy(items, copy = false, overwrite = false, rename = false) {
let promises = [];
function moveCopy(
items: any[],
copy = false,
overwrite = false,
rename = false
) {
const promises = [];
for (let item of items) {
for (const item of items) {
const from = item.from;
const to = encodeURIComponent(removePrefix(item.to));
const to = encodeURIComponent(removePrefix(item.to ?? ""));
const url = `${from}?action=${
copy ? "copy" : "rename"
}&destination=${to}&override=${overwrite}&rename=${rename}`;
@@ -150,20 +170,20 @@ function moveCopy(items, copy = false, overwrite = false, rename = false) {
return Promise.all(promises);
}
export function move(items, overwrite = false, rename = false) {
export function move(items: any[], overwrite = false, rename = false) {
return moveCopy(items, false, overwrite, rename);
}
export function copy(items, overwrite = false, rename = false) {
export function copy(items: any[], overwrite = false, rename = false) {
return moveCopy(items, true, overwrite, rename);
}
export async function checksum(url, algo) {
export async function checksum(url: string, algo: ChecksumAlg) {
const data = await resourceAction(`${url}?checksum=${algo}`, "GET");
return (await data.json()).checksums[algo];
}
export function getDownloadURL(file, inline) {
export function getDownloadURL(file: ResourceItem, inline: any) {
const params = {
...(inline && { inline: "true" }),
};
@@ -171,7 +191,7 @@ export function getDownloadURL(file, inline) {
return createURL("api/raw" + file.path, params);
}
export function getPreviewURL(file, size) {
export function getPreviewURL(file: ResourceItem, size: string) {
const params = {
inline: "true",
key: Date.parse(file.modified),
@@ -180,20 +200,15 @@ export function getPreviewURL(file, size) {
return createURL("api/preview/" + size + file.path, params);
}
export function getSubtitlesURL(file) {
export function getSubtitlesURL(file: ResourceItem) {
const params = {
inline: "true",
};
const subtitles = [];
for (const sub of file.subtitles) {
subtitles.push(createURL("api/raw" + sub, params));
}
return subtitles;
return file.subtitles?.map((d) => createURL("api/subtitle" + d, params));
}
export async function usage(url) {
export async function usage(url: string) {
url = removePrefix(url);
const res = await fetchURL(`/api/usage${url}`, {});

View File

@@ -1,7 +1,7 @@
import { fetchURL, removePrefix, createURL } from "./utils";
import { baseURL } from "@/utils/constants";
export async function fetch(url, password = "") {
export async function fetch(url: string, password: string = "") {
url = removePrefix(url);
const res = await fetchURL(
@@ -12,12 +12,12 @@ export async function fetch(url, password = "") {
false
);
let data = await res.json();
const data = (await res.json()) as Resource;
data.url = `/share${url}`;
if (data.isDir) {
if (!data.url.endsWith("/")) data.url += "/";
data.items = data.items.map((item, index) => {
data.items = data.items.map((item: any, index: any) => {
item.index = index;
item.url = `${data.url}${encodeURIComponent(item.name)}`;
@@ -32,7 +32,12 @@ export async function fetch(url, password = "") {
return data;
}
export function download(format, hash, token, ...files) {
export function download(
format: DownloadFormat,
hash: string,
token: string,
...files: string[]
) {
let url = `${baseURL}/api/public/dl/${hash}`;
if (files.length === 1) {
@@ -40,7 +45,7 @@ export function download(format, hash, token, ...files) {
} else {
let arg = "";
for (let file of files) {
for (const file of files) {
arg += encodeURIComponent(file) + ",";
}
@@ -60,11 +65,11 @@ export function download(format, hash, token, ...files) {
window.open(url);
}
export function getDownloadURL(share, inline = false) {
export function getDownloadURL(res: Resource, inline = false) {
const params = {
...(inline && { inline: "true" }),
...(share.token && { token: share.token }),
...(res.token && { token: res.token }),
};
return createURL("api/public/dl/" + share.hash + share.path, params, false);
return createURL("api/public/dl/" + res.hash + res.path, params, false);
}

View File

@@ -1,7 +1,7 @@
import { fetchURL, removePrefix } from "./utils";
import url from "../utils/url";
export default async function search(base, query) {
export default async function search(base: string, query: string) {
base = removePrefix(base);
query = encodeURIComponent(query);
@@ -9,11 +9,11 @@ export default async function search(base, query) {
base += "/";
}
let res = await fetchURL(`/api/search${base}?query=${query}`, {});
const res = await fetchURL(`/api/search${base}?query=${query}`, {});
let data = await res.json();
data = data.map((item) => {
data = data.map((item: UploadItem) => {
item.url = `/files${base}` + url.encodePath(item.path);
if (item.dir) {

View File

@@ -1,10 +1,10 @@
import { fetchURL, fetchJSON } from "./utils";
export function get() {
return fetchJSON(`/api/settings`, {});
return fetchJSON<ISettings>(`/api/settings`, {});
}
export async function update(settings) {
export async function update(settings: ISettings) {
await fetchURL(`/api/settings`, {
method: "PUT",
body: JSON.stringify(settings),

View File

@@ -1,21 +1,26 @@
import { fetchURL, fetchJSON, removePrefix, createURL } from "./utils";
export async function list() {
return fetchJSON("/api/shares");
return fetchJSON<Share[]>("/api/shares");
}
export async function get(url) {
export async function get(url: string) {
url = removePrefix(url);
return fetchJSON(`/api/share${url}`);
return fetchJSON<Share>(`/api/share${url}`);
}
export async function remove(hash) {
export async function remove(hash: string) {
await fetchURL(`/api/share/${hash}`, {
method: "DELETE",
});
}
export async function create(url, password = "", expires = "", unit = "hours") {
export async function create(
url: string,
password = "",
expires = "",
unit = "hours"
) {
url = removePrefix(url);
url = `/api/share${url}`;
if (expires !== "") {
@@ -23,7 +28,11 @@ export async function create(url, password = "", expires = "", unit = "hours") {
}
let body = "{}";
if (password != "" || expires !== "" || unit !== "hours") {
body = JSON.stringify({ password: password, expires: expires, unit: unit });
body = JSON.stringify({
password: password,
expires: expires.toString(), // backend expects string not number
unit: unit,
});
}
return fetchJSON(url, {
method: "POST",
@@ -31,6 +40,6 @@ export async function create(url, password = "", expires = "", unit = "hours") {
});
}
export function getShareURL(share) {
export function getShareURL(share: Share) {
return createURL("share/" + share.hash, {}, false);
}

View File

@@ -1,6 +1,7 @@
import * as tus from "tus-js-client";
import { baseURL, tusEndpoint, tusSettings } from "@/utils/constants";
import store from "@/store";
import { useAuthStore } from "@/stores/auth";
import { useUploadStore } from "@/stores/upload";
import { removePrefix } from "@/api/utils";
import { fetchURL } from "./utils";
@@ -11,13 +12,13 @@ const ALPHA = 0.2;
const ONE_MINUS_ALPHA = 1 - ALPHA;
const RECENT_SPEEDS_LIMIT = 5;
const MB_DIVISOR = 1024 * 1024;
const CURRENT_UPLOAD_LIST = {};
const CURRENT_UPLOAD_LIST: CurrentUploadList = {};
export async function upload(
filePath,
content = "",
filePath: string,
content: ApiContent = "",
overwrite = false,
onupload
onupload: any
) {
if (!tusSettings) {
// Shouldn't happen as we check for tus support before calling this function
@@ -25,29 +26,35 @@ export async function upload(
}
filePath = removePrefix(filePath);
let resourcePath = `${tusEndpoint}${filePath}?override=${overwrite}`;
const resourcePath = `${tusEndpoint}${filePath}?override=${overwrite}`;
await createUpload(resourcePath);
return new Promise((resolve, reject) => {
let upload = new tus.Upload(content, {
const authStore = useAuthStore();
// Exit early because of typescript, tus content can't be a string
if (content === "") {
return false;
}
return new Promise<void | string>((resolve, reject) => {
const upload = new tus.Upload(content, {
uploadUrl: `${baseURL}${resourcePath}`,
chunkSize: tusSettings.chunkSize,
retryDelays: computeRetryDelays(tusSettings),
parallelUploads: 1,
storeFingerprintForResuming: false,
headers: {
"X-Auth": store.state.jwt,
"X-Auth": authStore.jwt,
},
onError: function (error) {
if (CURRENT_UPLOAD_LIST[filePath].interval) {
clearInterval(CURRENT_UPLOAD_LIST[filePath].interval);
}
delete CURRENT_UPLOAD_LIST[filePath];
reject("Upload failed: " + error);
reject(new Error(`Upload failed: ${error.message}`));
},
onProgress: function (bytesUploaded) {
let fileData = CURRENT_UPLOAD_LIST[filePath];
const fileData = CURRENT_UPLOAD_LIST[filePath];
fileData.currentBytesUploaded = bytesUploaded;
if (!fileData.hasStarted) {
@@ -79,14 +86,14 @@ export async function upload(
lastProgressTimestamp: null,
sumOfRecentSpeeds: 0,
hasStarted: false,
interval: null,
interval: undefined,
};
upload.start();
});
}
async function createUpload(resourcePath) {
let headResp = await fetchURL(resourcePath, {
async function createUpload(resourcePath: string) {
const headResp = await fetchURL(resourcePath, {
method: "POST",
});
if (headResp.status !== 201) {
@@ -96,10 +103,10 @@ async function createUpload(resourcePath) {
}
}
function computeRetryDelays(tusSettings) {
function computeRetryDelays(tusSettings: TusSettings): number[] | undefined {
if (!tusSettings.retryCount || tusSettings.retryCount < 1) {
// Disable retries altogether
return null;
return undefined;
}
// The tus client expects our retries as an array with computed backoffs
// E.g.: [0, 3000, 5000, 10000, 20000]
@@ -115,7 +122,7 @@ function computeRetryDelays(tusSettings) {
return retryDelays;
}
export async function useTus(content) {
export async function useTus(content: ApiContent) {
return isTusSupported() && content instanceof Blob;
}
@@ -123,25 +130,34 @@ function isTusSupported() {
return tus.isSupported === true;
}
function computeETA(state) {
function computeETA(state: ETAState, speed?: number) {
if (state.speedMbyte === 0) {
return Infinity;
}
const totalSize = state.sizes.reduce((acc, size) => acc + size, 0);
const totalSize = state.sizes.reduce(
(acc: number, size: number) => acc + size,
0
);
const uploadedSize = state.progress.reduce(
(acc, progress) => acc + progress,
(acc: number, progress: Progress) => {
if (typeof progress === "number") {
return acc + progress;
}
return acc;
},
0
);
const remainingSize = totalSize - uploadedSize;
const speedBytesPerSecond = state.speedMbyte * 1024 * 1024;
const speedBytesPerSecond = (speed ?? state.speedMbyte) * 1024 * 1024;
return remainingSize / speedBytesPerSecond;
}
function computeGlobalSpeedAndETA() {
const uploadStore = useUploadStore();
let totalSpeed = 0;
let totalCount = 0;
for (let filePath in CURRENT_UPLOAD_LIST) {
for (const filePath in CURRENT_UPLOAD_LIST) {
totalSpeed += CURRENT_UPLOAD_LIST[filePath].currentAverageSpeed;
totalCount++;
}
@@ -149,41 +165,43 @@ function computeGlobalSpeedAndETA() {
if (totalCount === 0) return { speed: 0, eta: Infinity };
const averageSpeed = totalSpeed / totalCount;
const averageETA = computeETA(store.state.upload, averageSpeed);
const averageETA = computeETA(uploadStore, averageSpeed);
return { speed: averageSpeed, eta: averageETA };
}
function calcProgress(filePath) {
let fileData = CURRENT_UPLOAD_LIST[filePath];
function calcProgress(filePath: string) {
const uploadStore = useUploadStore();
const fileData = CURRENT_UPLOAD_LIST[filePath];
let elapsedTime = (Date.now() - fileData.lastProgressTimestamp) / 1000;
let bytesSinceLastUpdate =
const elapsedTime =
(Date.now() - (fileData.lastProgressTimestamp ?? 0)) / 1000;
const bytesSinceLastUpdate =
fileData.currentBytesUploaded - fileData.initialBytesUploaded;
let currentSpeed = bytesSinceLastUpdate / MB_DIVISOR / elapsedTime;
const currentSpeed = bytesSinceLastUpdate / MB_DIVISOR / elapsedTime;
if (fileData.recentSpeeds.length >= RECENT_SPEEDS_LIMIT) {
fileData.sumOfRecentSpeeds -= fileData.recentSpeeds.shift();
fileData.sumOfRecentSpeeds -= fileData.recentSpeeds.shift() ?? 0;
}
fileData.recentSpeeds.push(currentSpeed);
fileData.sumOfRecentSpeeds += currentSpeed;
let avgRecentSpeed =
const avgRecentSpeed =
fileData.sumOfRecentSpeeds / fileData.recentSpeeds.length;
fileData.currentAverageSpeed =
ALPHA * avgRecentSpeed + ONE_MINUS_ALPHA * fileData.currentAverageSpeed;
const { speed, eta } = computeGlobalSpeedAndETA();
store.commit("setUploadSpeed", speed);
store.commit("setETA", eta);
uploadStore.setUploadSpeed(speed);
uploadStore.setETA(eta);
fileData.initialBytesUploaded = fileData.currentBytesUploaded;
fileData.lastProgressTimestamp = Date.now();
}
export function abortAllUploads() {
for (let filePath in CURRENT_UPLOAD_LIST) {
for (const filePath in CURRENT_UPLOAD_LIST) {
if (CURRENT_UPLOAD_LIST[filePath].interval) {
clearInterval(CURRENT_UPLOAD_LIST[filePath].interval);
}

View File

@@ -1,14 +1,14 @@
import { fetchURL, fetchJSON } from "./utils";
import { fetchURL, fetchJSON, StatusError } from "./utils";
export async function getAll() {
return fetchJSON(`/api/users`, {});
return fetchJSON<IUser[]>(`/api/users`, {});
}
export async function get(id) {
return fetchJSON(`/api/users/${id}`, {});
export async function get(id: number) {
return fetchJSON<IUser>(`/api/users/${id}`, {});
}
export async function create(user) {
export async function create(user: IUser) {
const res = await fetchURL(`/api/users`, {
method: "POST",
body: JSON.stringify({
@@ -21,9 +21,11 @@ export async function create(user) {
if (res.status === 201) {
return res.headers.get("Location");
}
throw new StatusError(await res.text(), res.status);
}
export async function update(user, which = ["all"]) {
export async function update(user: IUser, which = ["all"]) {
await fetchURL(`/api/users/${user.id}`, {
method: "PUT",
body: JSON.stringify({
@@ -34,7 +36,7 @@ export async function update(user, which = ["all"]) {
});
}
export async function remove(id) {
export async function remove(id: number) {
await fetchURL(`/api/users/${id}`, {
method: "DELETE",
});

View File

@@ -1,80 +0,0 @@
import store from "@/store";
import { renew, logout } from "@/utils/auth";
import { baseURL } from "@/utils/constants";
import { encodePath } from "@/utils/url";
export async function fetchURL(url, opts, auth = true) {
opts = opts || {};
opts.headers = opts.headers || {};
let { headers, ...rest } = opts;
let res;
try {
res = await fetch(`${baseURL}${url}`, {
headers: {
"X-Auth": store.state.jwt,
...headers,
},
...rest,
});
} catch {
const error = new Error("000 No connection");
error.status = 0;
throw error;
}
if (auth && res.headers.get("X-Renew-Token") === "true") {
await renew(store.state.jwt);
}
if (res.status < 200 || res.status > 299) {
const error = new Error(await res.text());
error.status = res.status;
if (auth && res.status == 401) {
logout();
}
throw error;
}
return res;
}
export async function fetchJSON(url, opts) {
const res = await fetchURL(url, opts);
if (res.status === 200) {
return res.json();
} else {
throw new Error(res.status);
}
}
export function removePrefix(url) {
url = url.split("/").splice(2).join("/");
if (url === "") url = "/";
if (url[0] !== "/") url = "/" + url;
return url;
}
export function createURL(endpoint, params = {}, auth = true) {
let prefix = baseURL;
if (!prefix.endsWith("/")) {
prefix = prefix + "/";
}
const url = new URL(prefix + encodePath(endpoint), origin);
const searchParams = {
...(auth && { auth: store.state.jwt }),
...params,
};
for (const key in searchParams) {
url.searchParams.set(key, searchParams[key]);
}
return url.toString();
}

98
frontend/src/api/utils.ts Normal file
View File

@@ -0,0 +1,98 @@
import { useAuthStore } from "@/stores/auth";
import { renew, logout } from "@/utils/auth";
import { baseURL } from "@/utils/constants";
import { encodePath } from "@/utils/url";
export class StatusError extends Error {
constructor(
message: any,
public status?: number
) {
super(message);
this.name = "StatusError";
}
}
export async function fetchURL(
url: string,
opts: ApiOpts,
auth = true
): Promise<Response> {
const authStore = useAuthStore();
opts = opts || {};
opts.headers = opts.headers || {};
const { headers, ...rest } = opts;
let res;
try {
res = await fetch(`${baseURL}${url}`, {
headers: {
"X-Auth": authStore.jwt,
...headers,
},
...rest,
});
} catch {
throw new StatusError("000 No connection", 0);
}
if (auth && res.headers.get("X-Renew-Token") === "true") {
await renew(authStore.jwt);
}
if (res.status < 200 || res.status > 299) {
const body = await res.text();
const error = new StatusError(
body || `${res.status} ${res.statusText}`,
res.status
);
if (auth && res.status == 401) {
logout();
}
throw error;
}
return res;
}
export async function fetchJSON<T>(url: string, opts?: any): Promise<T> {
const res = await fetchURL(url, opts);
if (res.status === 200) {
return res.json() as Promise<T>;
}
throw new StatusError(`${res.status} ${res.statusText}`, res.status);
}
export function removePrefix(url: string): string {
url = url.split("/").splice(2).join("/");
if (url === "") url = "/";
if (url[0] !== "/") url = "/" + url;
return url;
}
export function createURL(endpoint: string, params = {}, auth = true): string {
const authStore = useAuthStore();
let prefix = baseURL;
if (!prefix.endsWith("/")) {
prefix = prefix + "/";
}
const url = new URL(prefix + encodePath(endpoint), origin);
const searchParams: SearchParams = {
...(auth && { auth: authStore.jwt }),
...params,
};
for (const key in searchParams) {
url.searchParams.set(key, searchParams[key]);
}
return url.toString();
}