Skip to content

Commit

Permalink
Update cdn handling
Browse files Browse the repository at this point in the history
  • Loading branch information
SupertigerDev committed Oct 11, 2024
1 parent 68d3d80 commit 020eff8
Show file tree
Hide file tree
Showing 3 changed files with 95 additions and 45 deletions.
22 changes: 14 additions & 8 deletions src/chat-api/services/Request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,9 @@ export async function request<T>(opts: RequestOpts): Promise<T> {
...(!(opts.body instanceof FormData)
? { "Content-Type": "application/json" }
: undefined),
Authorization: opts.useToken ? opts.token || token : "",
...(opts.useToken || opts.token
? { Authorization: opts.token || token }
: {}),
},
}).catch((err) => {
throw { message: "Could not connect to server. " + err.message };
Expand Down Expand Up @@ -121,8 +123,9 @@ export function xhrRequest<T>(
});
}


export const createProgressHandler = (onProgress?: (percent: number, speed?: string) => void) => {
export const createProgressHandler = (
onProgress?: (percent: number, speed?: string) => void
) => {
let startTime = 0;
let uploadedSize = 0;
return (e: ProgressEvent) => {
Expand All @@ -137,19 +140,22 @@ export const createProgressHandler = (onProgress?: (percent: number, speed?: str
const uploadSpeedMBps = uploadSpeedKBps / 1024; // Megabytes per second

// Choose the appropriate unit based on the speed
let unit = ' KB/s';
let unit = " KB/s";
if (uploadSpeedMBps >= 1) {
unit = ' MB/s';
unit = " MB/s";
}
let speed: string | undefined = uploadSpeedMBps >= 1 ? uploadSpeedMBps.toFixed(2) + unit : uploadSpeedKBps.toFixed(0) + unit;
let speed: string | undefined =
uploadSpeedMBps >= 1
? uploadSpeedMBps.toFixed(2) + unit
: uploadSpeedKBps.toFixed(0) + unit;

if (uploadSpeedMBps == Infinity) {
speed = "0 KB/s"
speed = "0 KB/s";
}

if (e.lengthComputable) {
const percentComplete = (e.loaded / e.total) * 100;
onProgress?.(Math.round(percentComplete), speed);
}
};
}
};
106 changes: 71 additions & 35 deletions src/chat-api/services/nerimityCDNService.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import env from "@/common/env";
import { xhrRequest } from "./Request";

import { request, xhrRequest } from "./Request";

interface NerimityCDNRequestOpts {
url: string;
Expand All @@ -9,56 +8,93 @@ interface NerimityCDNRequestOpts {
onUploadProgress?: (progress: number) => void;
}



export function uploadBanner(groupId: string, opts: Omit<NerimityCDNRequestOpts, "url">) {
return nerimityCDNRequest({
...opts,
url: `${env.NERIMITY_CDN}banners/${groupId}`,
})
export async function uploadBanner(
groupId: string,
opts: Omit<NerimityCDNRequestOpts, "url">
) {
return nerimityCDNUploadRequest({ ...opts, image: true }).then((res) => {
return nerimityCDNRequest({
...opts,
url: `${env.NERIMITY_CDN}banners/${groupId}/${res.fileId}`,
});
});
}
export function uploadAvatar(groupId: string, opts: Omit<NerimityCDNRequestOpts, "url"> & { points?: number[] }) {
return nerimityCDNRequest({
...opts,
query: {
points: opts.points ? JSON.stringify(opts.points) : undefined,
},
url: `${env.NERIMITY_CDN}avatars/${groupId}`,
})
export async function uploadAvatar(
groupId: string,
opts: Omit<NerimityCDNRequestOpts, "url"> & { points?: number[] }
) {
return nerimityCDNUploadRequest({ ...opts, image: true }).then((res) => {
return nerimityCDNRequest({
...opts,
query: {
points: opts.points ? JSON.stringify(opts.points) : undefined,
},
url: `${env.NERIMITY_CDN}avatars/${groupId}/${res.fileId}`,
});
});
}


export function uploadEmoji(opts: Omit<NerimityCDNRequestOpts, "url">) {
return nerimityCDNRequest({
...opts,
url: `${env.NERIMITY_CDN}emojis`,
})
export async function uploadEmoji(opts: Omit<NerimityCDNRequestOpts, "url">) {
return nerimityCDNUploadRequest({ ...opts, image: true }).then((res) => {
return nerimityCDNRequest({
...opts,
url: `${env.NERIMITY_CDN}emojis/${res.fileId}`,
});
});
}

export function uploadAttachment(groupId: string, opts: Omit<NerimityCDNRequestOpts, "url">) {
return nerimityCDNRequest({
...opts,
url: `${env.NERIMITY_CDN}attachments/${groupId}`,
})
export async function uploadAttachment(
groupId: string,
opts: Omit<NerimityCDNRequestOpts, "url">
) {
return nerimityCDNUploadRequest({ ...opts }).then((res) => {
return nerimityCDNRequest({
...opts,
url: `${env.NERIMITY_CDN}attachments/${groupId}/${res.fileId}`,
});
});
}

function nerimityCDNRequest(opts: NerimityCDNRequestOpts) {
const url = new URL(opts.url);
function nerimityCDNUploadRequest(opts: {
image?: boolean;
file: File;
onUploadProgress?: (percent: number, speed?: string) => void;
}) {
const url = new URL(`${env.NERIMITY_CDN}upload`);

if (opts.query) {
url.search = new URLSearchParams(JSON.parse(JSON.stringify(opts.query))).toString();
if (opts.image) {
url.search = new URLSearchParams({ image: "true" }).toString();
}

const formData = new FormData();
formData.append("attachment", opts.file);
formData.append("f", opts.file);

return xhrRequest<{ fileId: string }>(
{
method: "POST",
url: url.href,
body: formData,
useToken: false
useToken: false,
},
opts.onUploadProgress
);
}
}

function nerimityCDNRequest(opts: NerimityCDNRequestOpts) {
const url = new URL(opts.url);

if (opts.query) {
url.search = new URLSearchParams(
JSON.parse(JSON.stringify(opts.query))
).toString();
}

const formData = new FormData();
formData.append("attachment", opts.file);

return request<{ fileId: string }>({
method: "POST",
url: url.href,
useToken: false,
});
}
12 changes: 10 additions & 2 deletions src/components/settings/AccountSettings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -171,15 +171,23 @@ export function EditAccountPage(props: {
const res = await uploadAvatar(props.bot?.id || account.user()?.id!, {
file: avatar,
points: avatarPoints!,
}).catch((err) => {
setError(err.message);
});
avatarId = res.fileId;
if (res) {
avatarId = res.fileId;
}
}

if (banner) {
const res = await uploadBanner(props.bot?.id || account.user()?.id!, {
file: banner,
}).catch((err) => {
setError(err.message);
});
bannerId = res.fileId;
if (res) {
bannerId = res.fileId;
}
}

await updateUser({ ...values, bannerId, avatarId }, props.botToken)
Expand Down

0 comments on commit 020eff8

Please sign in to comment.