Use logo as default avatar

This commit is contained in:
Kieran 2023-12-25 18:56:26 +00:00
parent 9837d917b9
commit 097f97edc1
Signed by: Kieran
GPG Key ID: DE71CEB3925BE941
9 changed files with 217 additions and 214 deletions

View File

@ -1,192 +1,192 @@
import {
AdminProfile,
AdminUserListResult,
ApiError,
ApiKey,
LoginSession,
PagedRequest,
PagedResponse,
PaymentOrder,
Profile,
SetPaymentConfigRequest,
SiteInfoResponse,
VoidFileResponse,
AdminProfile,
AdminUserListResult,
ApiError,
ApiKey,
LoginSession,
PagedRequest,
PagedResponse,
PaymentOrder,
Profile,
SetPaymentConfigRequest,
SiteInfoResponse,
VoidFileResponse,
} from "./index";
import {
ProgressHandler,
ProxyChallengeHandler,
StateChangeHandler,
VoidUploader,
ProgressHandler,
ProxyChallengeHandler,
StateChangeHandler,
VoidUploader,
} from "./upload";
import {StreamUploader} from "./stream-uploader";
import {XHRUploader} from "./xhr-uploader";
import { StreamUploader } from "./stream-uploader";
import { XHRUploader } from "./xhr-uploader";
export type AuthHandler = (url: string, method: string) => Promise<string>;
export class VoidApi {
readonly #uri: string;
readonly #auth?: AuthHandler;
readonly #uri: string;
readonly #auth?: AuthHandler;
constructor(uri?: string, auth?: AuthHandler) {
this.#uri = uri ?? "";
this.#auth = auth;
constructor(uri?: string, auth?: AuthHandler) {
this.#uri = uri ?? "";
this.#auth = auth;
}
async #req<T>(method: string, url: string, body?: object): Promise<T> {
const absoluteUrl = `${this.#uri}${url}`;
const headers: HeadersInit = {
Accept: "application/json",
};
if (this.#auth) {
headers["Authorization"] = await this.#auth(absoluteUrl, method);
}
if (body) {
headers["Content-Type"] = "application/json";
}
async #req<T>(method: string, url: string, body?: object): Promise<T> {
const absoluteUrl = `${this.#uri}${url}`;
const headers: HeadersInit = {
Accept: "application/json",
};
if (this.#auth) {
headers["Authorization"] = await this.#auth(absoluteUrl, method);
}
if (body) {
headers["Content-Type"] = "application/json";
}
const res = await fetch(absoluteUrl, {
method,
headers,
mode: "cors",
body: body ? JSON.stringify(body) : undefined,
});
const text = await res.text();
if (res.ok) {
return text ? (JSON.parse(text) as T) : ({} as T);
} else {
throw new ApiError(res.status, text);
}
const res = await fetch(absoluteUrl, {
method,
headers,
mode: "cors",
body: body ? JSON.stringify(body) : undefined,
});
const text = await res.text();
if (res.ok) {
return text ? (JSON.parse(text) as T) : ({} as T);
} else {
throw new ApiError(res.status, text);
}
}
/**
* Get uploader for uploading files
*/
getUploader(
file: File | Blob,
stateChange?: StateChangeHandler,
progress?: ProgressHandler,
proxyChallenge?: ProxyChallengeHandler,
chunkSize?: number,
): VoidUploader {
if (StreamUploader.canUse()) {
return new StreamUploader(
this.#uri,
file,
stateChange,
progress,
proxyChallenge,
this.#auth,
chunkSize,
);
} else {
return new XHRUploader(
this.#uri,
file,
stateChange,
progress,
proxyChallenge,
this.#auth,
chunkSize,
);
}
/**
* Get uploader for uploading files
*/
getUploader(
file: File | Blob,
stateChange?: StateChangeHandler,
progress?: ProgressHandler,
proxyChallenge?: ProxyChallengeHandler,
chunkSize?: number,
): VoidUploader {
if (StreamUploader.canUse()) {
return new StreamUploader(
this.#uri,
file,
stateChange,
progress,
proxyChallenge,
this.#auth,
chunkSize,
);
} else {
return new XHRUploader(
this.#uri,
file,
stateChange,
progress,
proxyChallenge,
this.#auth,
chunkSize,
);
}
}
/**
* General site information
*/
info() {
return this.#req<SiteInfoResponse>("GET", "/info");
}
/**
* General site information
*/
info() {
return this.#req<SiteInfoResponse>("GET", "/info");
}
fileInfo(id: string) {
return this.#req<VoidFileResponse>("GET", `/upload/${id}`);
}
fileInfo(id: string) {
return this.#req<VoidFileResponse>("GET", `/upload/${id}`);
}
setPaymentConfig(id: string, cfg: SetPaymentConfigRequest) {
return this.#req("POST", `/upload/${id}/payment`, cfg);
}
setPaymentConfig(id: string, cfg: SetPaymentConfigRequest) {
return this.#req("POST", `/upload/${id}/payment`, cfg);
}
createOrder(id: string) {
return this.#req<PaymentOrder>("GET", `/upload/${id}/payment`);
}
createOrder(id: string) {
return this.#req<PaymentOrder>("GET", `/upload/${id}/payment`);
}
getOrder(file: string, order: string) {
return this.#req<PaymentOrder>("GET", `/upload/${file}/payment/${order}`);
}
getOrder(file: string, order: string) {
return this.#req<PaymentOrder>("GET", `/upload/${file}/payment/${order}`);
}
login(username: string, password: string, captcha?: string) {
return this.#req<LoginSession>("POST", `/auth/login`, {
username,
password,
captcha,
});
}
login(username: string, password: string, captcha?: string) {
return this.#req<LoginSession>("POST", `/auth/login`, {
username,
password,
captcha,
});
}
register(username: string, password: string, captcha?: string) {
return this.#req<LoginSession>("POST", `/auth/register`, {
username,
password,
captcha,
});
}
register(username: string, password: string, captcha?: string) {
return this.#req<LoginSession>("POST", `/auth/register`, {
username,
password,
captcha,
});
}
getUser(id: string) {
return this.#req<Profile>("GET", `/user/${id}`);
}
getUser(id: string) {
return this.#req<Profile>("GET", `/user/${id}`);
}
updateUser(u: Profile) {
return this.#req<void>("POST", `/user/${u.id}`, u);
}
updateUser(u: Profile) {
return this.#req<void>("POST", `/user/${u.id}`, u);
}
listUserFiles(uid: string, pageReq: PagedRequest) {
return this.#req<PagedResponse<VoidFileResponse>>(
"POST",
`/user/${uid}/files`,
pageReq,
);
}
listUserFiles(uid: string, pageReq: PagedRequest) {
return this.#req<PagedResponse<VoidFileResponse>>(
"POST",
`/user/${uid}/files`,
pageReq,
);
}
submitVerifyCode(uid: string, code: string) {
return this.#req<void>("POST", `/user/${uid}/verify`, {code});
}
submitVerifyCode(uid: string, code: string) {
return this.#req<void>("POST", `/user/${uid}/verify`, { code });
}
sendNewCode(uid: string) {
return this.#req<void>("GET", `/user/${uid}/verify`);
}
sendNewCode(uid: string) {
return this.#req<void>("GET", `/user/${uid}/verify`);
}
updateFileMetadata(id: string, meta: any) {
return this.#req<void>("POST", `/upload/${id}/meta`, meta);
}
updateFileMetadata(id: string, meta: any) {
return this.#req<void>("POST", `/upload/${id}/meta`, meta);
}
listApiKeys() {
return this.#req<Array<ApiKey>>("GET", `/auth/api-key`);
}
listApiKeys() {
return this.#req<Array<ApiKey>>("GET", `/auth/api-key`);
}
createApiKey(req: any) {
return this.#req<ApiKey>("POST", `/auth/api-key`, req);
}
createApiKey(req: any) {
return this.#req<ApiKey>("POST", `/auth/api-key`, req);
}
adminListFiles(pageReq: PagedRequest) {
return this.#req<PagedResponse<VoidFileResponse>>(
"POST",
"/admin/file",
pageReq,
);
}
adminListFiles(pageReq: PagedRequest) {
return this.#req<PagedResponse<VoidFileResponse>>(
"POST",
"/admin/file",
pageReq,
);
}
adminDeleteFile(id: string) {
return this.#req<void>("DELETE", `/admin/file/${id}`);
}
adminDeleteFile(id: string) {
return this.#req<void>("DELETE", `/admin/file/${id}`);
}
adminUserList(pageReq: PagedRequest) {
return this.#req<PagedResponse<AdminUserListResult>>(
"POST",
`/admin/users`,
pageReq,
);
}
adminUserList(pageReq: PagedRequest) {
return this.#req<PagedResponse<AdminUserListResult>>(
"POST",
`/admin/users`,
pageReq,
);
}
adminUpdateUser(u: AdminProfile) {
return this.#req<void>("POST", `/admin/update-user`, u);
}
adminUpdateUser(u: AdminProfile) {
return this.#req<void>("POST", `/admin/update-user`, u);
}
}

View File

@ -1,18 +1,18 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<link rel="icon" href="/logo_32.png"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta name="theme-color" content="#000000"/>
<meta name="description" content="void.cat - free, simple file sharing."/>
<link rel="apple-touch-icon" href="/logo_256.png"/>
<link rel="manifest" href="/manifest.json"/>
<head>
<meta charset="utf-8" />
<link rel="icon" href="/logo_32.png" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta name="description" content="void.cat - free, simple file sharing." />
<link rel="apple-touch-icon" href="/logo_256.png" />
<link rel="manifest" href="/manifest.json" />
<title>void.cat</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script src="./src/index.tsx" type="module"></script>
</body>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script src="./src/index.tsx" type="module"></script>
</body>
</html>

View File

@ -34,7 +34,12 @@ const router = createBrowserRouter([
path: "/u/:id",
loader: async ({ params }: LoaderFunctionArgs) => {
const state = store.getState();
const api = new VoidApi(import.meta.env.VITE_API_HOST, state.login.jwt ? () => Promise.resolve(`Bearer ${state.login.jwt}`) : undefined);
const api = new VoidApi(
import.meta.env.VITE_API_HOST,
state.login.jwt
? () => Promise.resolve(`Bearer ${state.login.jwt}`)
: undefined,
);
if (params.id) {
try {
return await api.getUser(params.id);

View File

@ -3,8 +3,6 @@ import { CSSProperties } from "react";
import { Link } from "react-router-dom";
import { Profile } from "@void-cat/api";
import { DefaultAvatar } from "@/Const";
const DefaultSize = 64;
interface InlineProfileProps {
@ -24,8 +22,8 @@ export function InlineProfile({ profile, options }: InlineProfileProps) {
...options,
};
let avatarUrl = profile.avatar ?? DefaultAvatar;
if (!avatarUrl.startsWith("http")) {
let avatarUrl = profile.avatar ?? "/logo_256.jpg";
if (profile.avatar && !avatarUrl.startsWith("http")) {
avatarUrl = `/d/${avatarUrl}`;
}
let avatarStyles = {

View File

@ -1,5 +1,3 @@
export const DefaultAvatar = "https://i.imgur.com/8A5Fu65.jpeg";
/**
* @constant {number} - Size of 1 kiB
*/

View File

@ -5,5 +5,8 @@ import { RootState } from "@/Store";
export default function useApi() {
const auth = useSelector((s: RootState) => s.login.jwt);
return new VoidApi(import.meta.env.VITE_API_HOST, auth ? () => Promise.resolve(`Bearer ${auth}`) : undefined);
return new VoidApi(
import.meta.env.VITE_API_HOST,
auth ? () => Promise.resolve(`Bearer ${auth}`) : undefined,
);
}

View File

@ -248,7 +248,9 @@ export function FilePreview() {
useEffect(() => {
if (info) {
const fileLink = info.metadata?.url ?? `${import.meta.env.VITE_API_HOST ?? ""}/d/${info.id}`;
const fileLink =
info.metadata?.url ??
`${import.meta.env.VITE_API_HOST ?? ""}/d/${info.id}`;
setFileSize(info.metadata?.size ?? 0);
const order = window.localStorage.getItem(`payment-${info.id}`);

View File

@ -7,7 +7,6 @@ import { Profile } from "@void-cat/api";
import useApi from "@/Hooks/UseApi";
import { RootState } from "@/Store";
import { DefaultAvatar } from "@/Const";
import { logout, setProfile as setGlobalProfile } from "@/LoginState";
import { FileList } from "@/Components/Shared/FileList";
@ -173,9 +172,8 @@ export function ProfilePage() {
}
if (profile) {
let avatarUrl = profile.avatar ?? DefaultAvatar;
if (!avatarUrl.startsWith("http")) {
// assume void-cat hosted avatar
let avatarUrl = profile.avatar ?? "/logo_256.jpg";
if (profile.avatar && !avatarUrl.startsWith("http")) {
avatarUrl = `/d/${avatarUrl}`;
}
let avatarStyles = {

View File

@ -1,34 +1,33 @@
import react from "@vitejs/plugin-react";
import {visualizer} from "rollup-plugin-visualizer";
import {defineConfig} from "vite";
import {vitePluginVersionMark} from "vite-plugin-version-mark";
import { visualizer } from "rollup-plugin-visualizer";
import { defineConfig } from "vite";
import { vitePluginVersionMark } from "vite-plugin-version-mark";
export default defineConfig({
plugins: [
react(),
visualizer({
open: true,
gzipSize: true,
filename: "build/stats.html",
}),
vitePluginVersionMark({
name: "void_cat",
ifGitSHA: true,
command: "git describe --always --tags",
ifMeta: false,
}),
],
assetsInclude: [],
build: {
outDir: "build"
plugins: [
react(),
visualizer({
open: true,
gzipSize: true,
filename: "build/stats.html",
}),
vitePluginVersionMark({
name: "void_cat",
ifGitSHA: true,
command: "git describe --always --tags",
ifMeta: false,
}),
],
assetsInclude: [],
build: {
outDir: "build",
},
base: "/",
clearScreen: false,
resolve: {
alias: {
"@": "/src",
},
base: "/",
clearScreen: false,
resolve: {
alias: {
"@": "/src",
},
},
define: {}
},
define: {},
});