Skip to content

Commit

Permalink
feat: adicionado suporte ao r2
Browse files Browse the repository at this point in the history
  • Loading branch information
HugoSilvaF committed May 14, 2024
1 parent d4ee9fe commit 02806af
Show file tree
Hide file tree
Showing 6 changed files with 14,008 additions and 9,446 deletions.
41 changes: 33 additions & 8 deletions apps/game/server/lib/http-service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import fetch, { FormData } from 'node-fetch';
import { config } from '@npwd/config/server';
import { Player } from '../players/player.class';
import { PutObjectCommand, S3Client } from '@aws-sdk/client-s3';
import { uuidv4 } from '../../utils/fivem';

export async function tweetDiscordPost(url: string, body: string): Promise<any> {
return new Promise((resolve, reject) =>
Expand All @@ -11,16 +13,39 @@ export async function tweetDiscordPost(url: string, body: string): Promise<any>
['Content-Type']: 'application/json',
},
})
.then(async (res) => {
const response: any = await res.json();
resolve(response);
})
.catch((err) => {
reject(err);
})
.then(async (res) => {
const response: any = await res.json();
resolve(response);
})
.catch((err) => {
reject(err);
}),
);
}

export async function r2PhotoUpload(body: string | FormData, token: string): Promise<any> {
return new Promise(async (resolve, reject) => {
const client = new S3Client({
region: "auto",
endpoint: config.images.r2.endpoint,
credentials: {
accessKeyId: config.images.r2.credentials.accessKeyId,
secretAccessKey: config.images.r2.credentials.secretAccessKey
}
});
const key = `${uuidv4()}.${config.images.imageEncoding}`;
const command = new PutObjectCommand({
Bucket: config.images.r2.bucketName,
Key: key,
Body: body,
ContentType: "image/" + config.images.imageEncoding
});
const response = await client.send(command);
resolve(`${config.images.url}${key}`);
});
}


export async function apiPhotoUpload(body: string | FormData, token: string): Promise<any> {
return new Promise((resolve, reject) =>
fetch(config.images.url, {
Expand Down Expand Up @@ -74,4 +99,4 @@ export async function webhookPhotoUpload(
reject(err);
}),
);
}
}
25 changes: 24 additions & 1 deletion apps/game/server/photo/photo.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { config } from '@npwd/config/server';
import { v4 as uuidv4 } from 'uuid';
import { FormData, fileFromSync } from 'node-fetch';
import * as fs from 'fs';
import { apiPhotoUpload, webhookPhotoUpload } from '../lib/http-service';
import { apiPhotoUpload, r2PhotoUpload, webhookPhotoUpload } from '../lib/http-service';

const exp = global.exports;
const path = GetResourcePath('npwd') + '/uploads';
Expand Down Expand Up @@ -51,6 +51,7 @@ class _PhotoService {

const filePath = `${path}/screenshot-${uuidv4()}.${config.images.imageEncoding}`;

// use this in r2
const _data = Buffer.from(data.replace(`data:${type};base64`, ''), 'base64');
fs.writeFileSync(filePath, _data);

Expand Down Expand Up @@ -86,6 +87,28 @@ class _PhotoService {
}

let returnData;

if (config.images.type == 'r2') {
await r2PhotoUpload(_data, this.TOKEN)
.then(async (result) => {
returnData = result;
})
.catch((err) => {
photoLogger.error(
`Failed to upload photo, status code: ${err.statusCode}: ${err.errorText}`,
{
source: reqObj.source,
},
);
return resp({ status: 'error', errorMsg: 'GENERIC_DB_ERROR' });
});

fs.rmSync(filePath);
const identifier = PlayerService.getIdentifier(reqObj.source);
const photo = await this.photoDB.uploadPhoto(identifier, returnData);
return resp({ status: 'ok', data: photo });
}

await apiPhotoUpload(body, this.TOKEN)
.then((result) => {
returnData = result;
Expand Down
9 changes: 8 additions & 1 deletion config.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,14 @@
"authorizationHeader": "Authorization",
"authorizationPrefix": "",
"useAuthorization": true,
"returnedDataIndexes": ["url"]
"returnedDataIndexes": ["url"],
"r2": {
"bucketName": "",
"endpoint" : "",
"credentials": {
"accessKeyId": "",
"secretAccessKey": ""
}
},
"imageSafety": {
"filterUnsafeImageUrls": true,
Expand Down
8 changes: 6 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,14 @@
"@octokit/core": "^3.6.0",
"esbuild": "^0.15.15",
"husky": "^7.0.4",
"lodash": "https://github.com/lodash/lodash.git#npm",
"prettier": "^2.8.3",
"pretty-quick": "^3.1.3",
"rollup": "^2.77.2",
"rollup-plugin-dts": "^4.2.2",
"rollup-plugin-esbuild": "^4.10.2",
"turbo": "^1.11.3",
"lodash": "https://github.com/lodash/lodash.git#npm"
"wrangler": "^3.55.0"
},
"scripts": {
"preinstall": "npx only-allow pnpm",
Expand All @@ -44,5 +45,8 @@
"pre-commit": "npx run format:staged"
}
},
"dependencies": {}
"dependencies": {
"@aws-sdk/client-s3": "^3.574.0",
"aws-sdk": "^2.1618.0"
}
}
Loading

0 comments on commit 02806af

Please sign in to comment.