Skip to content

Commit

Permalink
fix(app): Handle Downloads with blob
Browse files Browse the repository at this point in the history
Related to #15
  • Loading branch information
ful1e5 committed Dec 4, 2023
1 parent c446dd2 commit 200d339
Show file tree
Hide file tree
Showing 5 changed files with 70 additions and 46 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [unreleased]

### Improvements:

- Added Download counts for 'PRO' Users
- Background Blur for modal and Navigation bar

### Fixes

- Print username in sponsor card if name is empty
Expand Down
10 changes: 5 additions & 5 deletions api/core/index.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,15 +53,15 @@ def upload_images():

if data.errors:
errors.extend(data.errors)
return jsonify({"status": 400, "id": id, "file": None, "error": errors}), 400
return jsonify({"id": id, "file": None, "error": errors}), 400

name, errs = store_cursors(id, data, logger)
errors.extend(errs)

if errors:
return jsonify({"status": 400, "id": id, "file": None, "error": errors}), 400
return jsonify({"id": id, "file": None, "error": errors}), 400
else:
return jsonify({"status": 200, "id": id, "file": name, "error": None})
return jsonify({"id": id, "file": name, "error": None})


@app.route("/api/core/download", methods=["GET"])
Expand All @@ -75,7 +75,7 @@ def download():

if param.errors:
errors.extend(param.errors)
return jsonify({"status": 400, "id": id, "error": errors}), 400
return jsonify({"id": id, "error": errors}), 400

res: FileResponse
if param.platform == "win":
Expand All @@ -85,6 +85,6 @@ def download():

if res.errors:
errors.extend(res.errors)
return jsonify({"status": 400, "id": id, "error": errors}), 400
return jsonify({"id": id, "error": errors}), 400
else:
return send_file(res.file, as_attachment=True)
64 changes: 30 additions & 34 deletions src/components/DownloadButton/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { LockSVG, ProcessingSVG } from '@components/svgs';
import { Platform, Type } from '@prisma/client';
import { Color, Image, ErrorLogs } from 'bibata/app';
import { AuthToken } from 'bibata/core-api/types';
import { DownloadFile } from 'bibata/core-api/responses';

type Props = {
disabled?: boolean;
Expand Down Expand Up @@ -90,21 +91,26 @@ export const DownloadButton: React.FC<Props> = (props) => {
const upload = await api.uploadImages(formData);
if (upload?.error) {
updateErrorLogs({
text: 'Oops.. Processing Falied! Try Again.',
key: 'upload',
error: upload.error,
text: 'Oops.. Processing Falied! Try Again.'
error: upload.error
});
return upload;
}
}
};

const downloadFile = (url: string) => {
const downloadFile = (file: DownloadFile) => {
const url = window.URL.createObjectURL(new Blob([file.blob]));

const link = document.createElement('a');
link.href = url;
link.setAttribute('download', file.name);

document.body.appendChild(link);
link.click();
link.parentNode?.removeChild(link);

setErrorLogs({ text: '' });
};

Expand All @@ -127,9 +133,9 @@ export const DownloadButton: React.FC<Props> = (props) => {
});
} catch (e) {
updateErrorLogs({
text: 'Unexpected Internal Error.',
key: 'count',
error: e,
text: 'Unexpected Internal Error.'
error: e
});
printError(e);
}
Expand All @@ -146,43 +152,33 @@ export const DownloadButton: React.FC<Props> = (props) => {
const { count, total } = await getDownloadCounts(token);
if ((total && count >= total) || (count === 0 && total === 0)) {
setErrorLogs({ text: 'Download Limit Exceeded.' });
setLock(false);
} else {
const n = `${name}${role === 'PRO' ? '-Pro' : ''}`;

const downloadUrl = api.downloadUrl(platform, n, props.version);

setLoadingText(`Preparing Requests ...`);
const download = await api.downloadable(platform, n, props.version);
const upload = await processImages(api, images, { platform, size });

if (!download?.error) {
downloadFile(downloadUrl);
if (upload?.error) {
printError(upload.error);
await api.refreshSession(token);
} else {
const upload = await processImages(api, images, { platform, size });
setLoadingText(
`Packaging ${platform === 'win' ? 'Win Cursors' : 'XCursors'} ...`
);

if (upload?.error) {
printError(upload.error);
await api.refreshSession(token);
} else {
setLoadingText(
`Packaging ${platform === 'win' ? 'Win Cursors' : 'XCursors'} ...`
);
const file = await api.download(platform, n, props.version);

const download = await api.downloadable(platform, n, props.version);

if (download?.error) {
printError(download.error);

updateErrorLogs({
key: 'download',
error: download.error,
text: 'Oops.. Packaging Failed! Try Again.'
});

await api.refreshSession(token);
} else {
await storeToDB(platform);
downloadFile(downloadUrl);
}
if ('blob' in file) {
await storeToDB(platform);
downloadFile(file);
} else {
printError(file.error);
updateErrorLogs({
text: 'Oops.. Packaging Failed! Try Again.',
key: 'download',
error: file.error || file
});
}
}
}
Expand Down
7 changes: 5 additions & 2 deletions src/types/bibata.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,6 @@ declare module 'bibata/core-api/responses' {
};

type UploadResponse = {
status: number;
id: string;
files: string[];
error: string[];
Expand All @@ -110,8 +109,12 @@ declare module 'bibata/core-api/responses' {
};

type DownloadError = {
status: number;
id: string;
error: string[];
};

type DownloadFile = {
blob: Blob;
name: string;
};
}
30 changes: 25 additions & 5 deletions src/utils/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
AuthError,
DeleteSessionResponse,
DownloadError,
DownloadFile,
GetSessionResponse,
UploadResponse
} from 'bibata/core-api/responses';
Expand Down Expand Up @@ -72,20 +73,39 @@ export class CoreApi {
}
}

public downloadUrl(p: Platform, n: string, v: string) {
private __downloadUrl(p: Platform, n: string, v: string) {
return `${this.url}/download?platform=${p}&name=${n}&v=${v}`;
}

public async downloadable(p: Platform, n: string, v: string) {
const res = await fetch(this.downloadUrl(p, n, v), {
public async download(p: Platform, n: string, v: string) {
const res = await fetch(this.__downloadUrl(p, n, v), {
headers: this.__headers(this.jwt?.token)
});

if (res.status === 200) {
return null;
} else {
try {
const blob = await res.blob();
const name = res.headers
.get('Content-Disposition')
.split('filename=')[1];
return { blob, name } as DownloadFile;
} catch (e) {
return {
id: this.jwt?.id,
error: [
'Unhandle Exception Occur while downloading cursor package.',
JSON.stringify(e)
]
} as DownloadError;
}
} else if (res.status === 400) {
const data = await res.json();
return data as DownloadError;
} else {
return {
id: this.jwt?.id,
error: ['Internal Error Occur while downloading cursor package.']
} as DownloadError;
}
}
}

0 comments on commit 200d339

Please sign in to comment.