布鲁诺 普雷托
布鲁诺 普雷托
Explore posts from servers
CDCloudflare Developers
Created by 布鲁诺 普雷托 on 11/8/2024 in #pages-help
Serving Static Files - Hono
So I am trying to convert a previous project of mine from express to Hono (IDK if its the best option or not.. I'd like some feedback/advice). I always start by deploying static stuff to check if everything is according to plan, however I don't seem to be able and serve my static 404 page. From what I gather I have to add to the toml file the following:
assets = { directory = "src/public", binding = "ASSETS", html_handling = "force-trailing-slash", not_found_handling = "404-page" }
assets = { directory = "src/public", binding = "ASSETS", html_handling = "force-trailing-slash", not_found_handling = "404-page" }
Am I suppose to add something else in my index.ts file ? I saw Hono has the following possibility
app.notFound((c) => {
return c.text('Oops not found.', 404)
})
app.notFound((c) => {
return c.text('Oops not found.', 404)
})
I can serve the file if I past it plain in the index.ts file, however for code/folder structure purposes I prefer not to do so... I'd really appreciate some help in this manner. Cheers :cheers:
1 replies
CDCloudflare Developers
Created by 布鲁诺 普雷托 on 7/20/2024 in #workers-help
R2 via workers returnind undefined for list, get, delete and put requests
I have everythin in 'modules' to organize the code better index.js pageHandler.js corsHandler.js I created a bucket so that the static and dynamic html files can be fetched When I call the pageHandler from index I send the request, env and ctx as parameters,however it seems to not pass the object at all
import {corsOptions} from "./corsHandler";

const handlePages=async (request, env, ctx, trigger='404') => {
switch (true) {
case "200": {
return new Response(JSON.stringify({res: "Hi"}), {status: 200})
}
default :
return await handle404Pages(request, env, ctx)
}
}


const returnPage=async (htmlResponse, request, status=200) => {
switch (request.method) {
case 'GET':
return new Response(htmlResponse, {
status: status,
headers: {
'Content-Type': 'text/html'
}
});
default:
const responseData={
"status": "Not Found"
}
const jsonResponse=JSON.stringify(responseData)
// Return JSON response with appropriate CORS headers
return new Response(jsonResponse, corsOptions(request), 404);

}
}

const getPageR2=async (env, page) => {
return await env.STORE.get(`src/html/${page}.html`)
}

async function handle404Pages(request, env, ctx) {

const ContactMeObject=JSON.stringify(env.CONTACTME);
console.log(ContactMeObject)
const object=await getPageR2(env, "404")
if (object === null) {
return new Response('Object Not Found', {status: 404});
}
console.log(JSON.stringify(object))
const htmlContent=object
.replace('{{URL}}', ContactMeObject['WHERE'])
.replace('{{CONTACT}}', ContactMeObject[ContactMeObject['WHERE']]);
return await returnPage(htmlContent, request, 404)
}


export {handlePages}
import {corsOptions} from "./corsHandler";

const handlePages=async (request, env, ctx, trigger='404') => {
switch (true) {
case "200": {
return new Response(JSON.stringify({res: "Hi"}), {status: 200})
}
default :
return await handle404Pages(request, env, ctx)
}
}


const returnPage=async (htmlResponse, request, status=200) => {
switch (request.method) {
case 'GET':
return new Response(htmlResponse, {
status: status,
headers: {
'Content-Type': 'text/html'
}
});
default:
const responseData={
"status": "Not Found"
}
const jsonResponse=JSON.stringify(responseData)
// Return JSON response with appropriate CORS headers
return new Response(jsonResponse, corsOptions(request), 404);

}
}

const getPageR2=async (env, page) => {
return await env.STORE.get(`src/html/${page}.html`)
}

async function handle404Pages(request, env, ctx) {

const ContactMeObject=JSON.stringify(env.CONTACTME);
console.log(ContactMeObject)
const object=await getPageR2(env, "404")
if (object === null) {
return new Response('Object Not Found', {status: 404});
}
console.log(JSON.stringify(object))
const htmlContent=object
.replace('{{URL}}', ContactMeObject['WHERE'])
.replace('{{CONTACT}}', ContactMeObject[ContactMeObject['WHERE']]);
return await returnPage(htmlContent, request, 404)
}


export {handlePages}
3 replies
CDCloudflare Developers
Created by 布鲁诺 普雷托 on 7/14/2024 in #workers-help
CORS Missing Allow Origin
I am havin problems with the Cors, the code I'm about to send here worked before, out of the blue it stopped working, is anyone able to help out?
if (request.method === 'OPTIONS') {
// Handle CORS preflight req
return new Response(JSON.stringify({cors:'allowed'}), corsOptions(request.headers.get('Origin')));
}

function corsOptions(origin, status = 0) {
return {
status: status ? 404:200,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': origin,
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Allow-Credentials': "true",
'Access-Control-Expose-Headers': 'Set-Cookie',
'Same-Site': 'Strict'
}
};
}
if (request.method === 'OPTIONS') {
// Handle CORS preflight req
return new Response(JSON.stringify({cors:'allowed'}), corsOptions(request.headers.get('Origin')));
}

function corsOptions(origin, status = 0) {
return {
status: status ? 404:200,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': origin,
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Allow-Credentials': "true",
'Access-Control-Expose-Headers': 'Set-Cookie',
'Same-Site': 'Strict'
}
};
}
1 replies
CDCloudflare Developers
Created by 布鲁诺 普雷托 on 7/10/2024 in #workers-help
Error: D1_ERROR: near "MERGE": syntax error at offset 3
MERGE INTO pt_player_tribe AS target
USING (SELECT ?1 AS player_id, ?2 AS tribe_id, ?3 AS world) AS source
ON (target.player_id = source.player_id AND target.world = source.world)
WHEN MATCHED AND target.tribe_id <> source.tribe_id THEN
UPDATE SET tribe_id = source.tribe_id
WHEN NOT MATCHED THEN
INSERT (player_id, world, tribe_id)
VALUES (source.player_id, source.world, source.tribe_id)
MERGE INTO pt_player_tribe AS target
USING (SELECT ?1 AS player_id, ?2 AS tribe_id, ?3 AS world) AS source
ON (target.player_id = source.player_id AND target.world = source.world)
WHEN MATCHED AND target.tribe_id <> source.tribe_id THEN
UPDATE SET tribe_id = source.tribe_id
WHEN NOT MATCHED THEN
INSERT (player_id, world, tribe_id)
VALUES (source.player_id, source.world, source.tribe_id)
2 replies
CDCloudflare Developers
Created by 布鲁诺 普雷托 on 7/10/2024 in #workers-help
✘ [ERROR] Error: The 'mode' field on 'RequestInitializerDict' is not implemented.
✘ [ERROR] Error: The 'mode' field on 'RequestInitializerDict' is not implemented.
4 replies
CDCloudflare Developers
Created by 布鲁诺 普雷托 on 4/11/2024 in #general-help
Cloudflare calls
Can someone help me out with this?
4 replies
CDCloudflare Developers
Created by 布鲁诺 普雷托 on 3/2/2024 in #workers-help
Serve js files or json responses
I wanna do something like this with cloudflare workers:
const express = require('express');
const fs = require('fs');
const path = require('path')
const bodyParser = require('body-parser');
const helmet = require('helmet');
const cors = require('cors'); // Add this line
const basicAuth = require('express-basic-auth');
const bcrypt = require('bcrypt');
const app = express();
const port = 3005;
const config = require('./config.json');
const mysql = require("mysql");


//Some DB connection, probably mongo


app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'"],
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", "data:"],
connectSrc: ["'self'"],
fontSrc: ["'self'"],
objectSrc: ["'none'"],
mediaSrc: ["'self'"],
frameSrc: ["'none'"],
},
}, dnsPrefetchControl: false, frameguard: {
action: 'deny'
}, hsts: {
maxAge: 5184000, // 60 days
includeSubDomains: true, preload: true,
}, ieNoOpen: true, noSniff: true, permittedCrossDomainPolicies: {
permittedPolicies: 'none',
}, referrerPolicy: {
policy: 'same-origin',
}, xssFilter: true,
}));

const corsOptions = {
origin: /.*somedomain.*/, credentials: true, exposedHeaders: 'Set-Cookie',
sameSite: 'Strict',
};

// Apply CORS middleware before body parsing
app.use(cors(corsOptions));


// Body parser with increased limits
app.use(bodyParser.json({limit: '1gb'}));
app.use(bodyParser.urlencoded({limit: '1gb', extended: true}));

app.use(express.static(path.join(__dirname, 'public')));
const excludedRoutes = [''];

// Basic authentication middleware
app.use((req, res, next) => {
// Check if the request path matches any of the excluded routes
if (excludedRoutes.includes(req.path)) {
// If the request path matches, skip basic authentication and move to the next middleware
next();
} else {
// If the request path doesn't match, proceed with basic authentication
basicAuth({
users,
challenge: true,
unauthorizedResponse: 'Unauthorized access',
})(req, res, next); // Call the basicAuth middleware
}
});


//part I actually want to implement
app.get('/get-data', (req,res)=>{
res.json('{"somedata":"some other data"}')
})
const express = require('express');
const fs = require('fs');
const path = require('path')
const bodyParser = require('body-parser');
const helmet = require('helmet');
const cors = require('cors'); // Add this line
const basicAuth = require('express-basic-auth');
const bcrypt = require('bcrypt');
const app = express();
const port = 3005;
const config = require('./config.json');
const mysql = require("mysql");


//Some DB connection, probably mongo


app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'"],
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", "data:"],
connectSrc: ["'self'"],
fontSrc: ["'self'"],
objectSrc: ["'none'"],
mediaSrc: ["'self'"],
frameSrc: ["'none'"],
},
}, dnsPrefetchControl: false, frameguard: {
action: 'deny'
}, hsts: {
maxAge: 5184000, // 60 days
includeSubDomains: true, preload: true,
}, ieNoOpen: true, noSniff: true, permittedCrossDomainPolicies: {
permittedPolicies: 'none',
}, referrerPolicy: {
policy: 'same-origin',
}, xssFilter: true,
}));

const corsOptions = {
origin: /.*somedomain.*/, credentials: true, exposedHeaders: 'Set-Cookie',
sameSite: 'Strict',
};

// Apply CORS middleware before body parsing
app.use(cors(corsOptions));


// Body parser with increased limits
app.use(bodyParser.json({limit: '1gb'}));
app.use(bodyParser.urlencoded({limit: '1gb', extended: true}));

app.use(express.static(path.join(__dirname, 'public')));
const excludedRoutes = [''];

// Basic authentication middleware
app.use((req, res, next) => {
// Check if the request path matches any of the excluded routes
if (excludedRoutes.includes(req.path)) {
// If the request path matches, skip basic authentication and move to the next middleware
next();
} else {
// If the request path doesn't match, proceed with basic authentication
basicAuth({
users,
challenge: true,
unauthorizedResponse: 'Unauthorized access',
})(req, res, next); // Call the basicAuth middleware
}
});


//part I actually want to implement
app.get('/get-data', (req,res)=>{
res.json('{"somedata":"some other data"}')
})
How to do this, if possible
5 replies
DIAdiscord.js - Imagine an app
Created by 布鲁诺 普雷托 on 2/3/2024 in #djs-questions
ffmpeg errors
node:events:492
throw er; // Unhandled 'error' event
^

Error: spawn ffmpeg EAGAIN
at ChildProcess._handle.onexit (node:internal/child_process:286:19)
at onErrorNT (node:internal/child_process:484:16)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21)
Emitted 'error' event on ChildProcess instance at:
at ChildProcess._handle.onexit (node:internal/child_process:292:12)
at onErrorNT (node:internal/child_process:484:16)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
errno: -11,
code: 'EAGAIN',
syscall: 'spawn ffmpeg',
path: 'ffmpeg',
spawnargs: [
'-i',
'/home/brunommpreto/Music/CloudMusic/TBT Prod. - Gangsta Gangsta(TBT Remix).mp3',
'-analyzeduration',
'0',
'-loglevel',
'0',
'-acodec',
'libopus',
'-f',
'opus',
'-ar',
'48000',
'-ac',
'2',
'pipe:1'
]
}
node:events:492
throw er; // Unhandled 'error' event
^

Error: spawn ffmpeg EAGAIN
at ChildProcess._handle.onexit (node:internal/child_process:286:19)
at onErrorNT (node:internal/child_process:484:16)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21)
Emitted 'error' event on ChildProcess instance at:
at ChildProcess._handle.onexit (node:internal/child_process:292:12)
at onErrorNT (node:internal/child_process:484:16)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
errno: -11,
code: 'EAGAIN',
syscall: 'spawn ffmpeg',
path: 'ffmpeg',
spawnargs: [
'-i',
'/home/brunommpreto/Music/CloudMusic/TBT Prod. - Gangsta Gangsta(TBT Remix).mp3',
'-analyzeduration',
'0',
'-loglevel',
'0',
'-acodec',
'libopus',
'-f',
'opus',
'-ar',
'48000',
'-ac',
'2',
'pipe:1'
]
}
here is my code, part of it:
try {
// Replace 'path/to/your/local/folder' with the path to your local folder containing audio files
const folderPath='/home/brunommpreto/Music/CloudMusic/';
//If theres already a queue avoid re-reading them
if (!queue.length && !running) {
// Read all files in the folder
const files=fs.readdirSync(folderPath);
let i=0;
for (const file of files) {
if (file.toLowerCase().endsWith('.mp3')) {
const filePath=path.join(folderPath, file.replace(/(['"()])/g, '\\$1'));
const resource=await createAudioResource(filePath, { inputType: StreamType.WebmOpus });
queue.push(resource);
i++;
console.log("Loaded " + i + " of " + files.length)
}
}
queue=queue.sort((a, b) => 0.5 - Math.random())
}

if (!isPlaying) {
await playNextTrack(newState);
running = true
}
} catch (error) {
console.error('Error joining voice channel:', error);
}
try {
// Replace 'path/to/your/local/folder' with the path to your local folder containing audio files
const folderPath='/home/brunommpreto/Music/CloudMusic/';
//If theres already a queue avoid re-reading them
if (!queue.length && !running) {
// Read all files in the folder
const files=fs.readdirSync(folderPath);
let i=0;
for (const file of files) {
if (file.toLowerCase().endsWith('.mp3')) {
const filePath=path.join(folderPath, file.replace(/(['"()])/g, '\\$1'));
const resource=await createAudioResource(filePath, { inputType: StreamType.WebmOpus });
queue.push(resource);
i++;
console.log("Loaded " + i + " of " + files.length)
}
}
queue=queue.sort((a, b) => 0.5 - Math.random())
}

if (!isPlaying) {
await playNextTrack(newState);
running = true
}
} catch (error) {
console.error('Error joining voice channel:', error);
}
14 replies
DIAdiscord.js - Imagine an app
Created by 布鲁诺 普雷托 on 11/18/2023 in #djs-questions
Know which device it it
Is there a way to know in which device the user is? I have a few interactions that work 100% on the computer/web, but on mobile it gets laggy, so i want to have 2 response types, desktop and mobile, so the UI is more pleasant
13 replies
DIAdiscord.js - Imagine an app
Created by 布鲁诺 普雷托 on 6/1/2023 in #djs-questions
Click Button Error
3 replies
DIAdiscord.js - Imagine an app
Created by 布鲁诺 普雷托 on 5/26/2023 in #djs-questions
Button to show modal
7 replies
DIAdiscord.js - Imagine an app
Created by 布鲁诺 普雷托 on 5/22/2023 in #djs-questions
Autocomplete 25 entries limit bypass
How can I bypass the 25 entries limit? I have an array of about 8000 entries sad
'arabacal', 'westcoast', 'SNIFES',
'jomal', '....', 'sharkmaster',
'- Just Try Me o.O', 'JORGED', 'pfialho1',
'speed7', 'Vilarelhos', 'Kroll',
'vaskinadore', 'jbaiao', 'pmrf',
'JOSE GREGORIO', 'joao rangel', 'adelinomartins',
'VelhoVelho', 'fernandes74', 'Cullen Bohannon',
'crackbreak', 'Rui Peres', 'Lucifer125',
'dragonball007', 'zepirikito', 'fabado',
'reisdavid1', 'and282', 'bcchina',
'CarryDaGuarda', 'Costini', 'Pipo Manobra',
'costa67', 'canario28', 'KART46',
'ALLGAR I', 'fafito', 'Nita23',
'bull13', 'xavs', 'Sensei16',
'Dead Pirate', 'roger chelas', 'montemurensse',
'blackkamikase', 'RodrigoBeck', 'carp6969',
'RODRYGORS', 'Jack o Estripador', 'Adesir Braun',
'hiphoptuga', 'agedeão', 'elekid',
'krilinm', 'levezinho', 'Exkimo',
'Luis Dinis', 'dias carlos', 'jaymor',
'JAguiar', 'Lhitow', 'MrErbalist',
'panicoo', 'PLDelta', 'castelo branco',
'Brother Minifix', 'odmilso', 'mjbel',
'SirGuedes', 'sonatas', 'Pintarolas100',
'dragon78', 'kinng', 'VMOM',
'Vandrakens', 'Bullet', 'carolina*',
'valente rui', 'Paulo sobral', 'FUTAIVLOG',
'esteves94', 'tiranio', 'timor',
'passarao123', 'hipol', 'marot',
'Tonho Bruto', 'Selma Nunes', 'james 007',
'saizo', 'Superb Lich', 'lotario',
'SPNA', 'claudinho marques', 'King Tour',
'saraaf', 'MasterFilipe', 'Tiagoacp',
'Aniquilador total',
... 7580 more items
]
'arabacal', 'westcoast', 'SNIFES',
'jomal', '....', 'sharkmaster',
'- Just Try Me o.O', 'JORGED', 'pfialho1',
'speed7', 'Vilarelhos', 'Kroll',
'vaskinadore', 'jbaiao', 'pmrf',
'JOSE GREGORIO', 'joao rangel', 'adelinomartins',
'VelhoVelho', 'fernandes74', 'Cullen Bohannon',
'crackbreak', 'Rui Peres', 'Lucifer125',
'dragonball007', 'zepirikito', 'fabado',
'reisdavid1', 'and282', 'bcchina',
'CarryDaGuarda', 'Costini', 'Pipo Manobra',
'costa67', 'canario28', 'KART46',
'ALLGAR I', 'fafito', 'Nita23',
'bull13', 'xavs', 'Sensei16',
'Dead Pirate', 'roger chelas', 'montemurensse',
'blackkamikase', 'RodrigoBeck', 'carp6969',
'RODRYGORS', 'Jack o Estripador', 'Adesir Braun',
'hiphoptuga', 'agedeão', 'elekid',
'krilinm', 'levezinho', 'Exkimo',
'Luis Dinis', 'dias carlos', 'jaymor',
'JAguiar', 'Lhitow', 'MrErbalist',
'panicoo', 'PLDelta', 'castelo branco',
'Brother Minifix', 'odmilso', 'mjbel',
'SirGuedes', 'sonatas', 'Pintarolas100',
'dragon78', 'kinng', 'VMOM',
'Vandrakens', 'Bullet', 'carolina*',
'valente rui', 'Paulo sobral', 'FUTAIVLOG',
'esteves94', 'tiranio', 'timor',
'passarao123', 'hipol', 'marot',
'Tonho Bruto', 'Selma Nunes', 'james 007',
'saizo', 'Superb Lich', 'lotario',
'SPNA', 'claudinho marques', 'King Tour',
'saraaf', 'MasterFilipe', 'Tiagoacp',
'Aniquilador total',
... 7580 more items
]
11 replies
DIAdiscord.js - Imagine an app
Created by 布鲁诺 普雷托 on 5/22/2023 in #djs-questions
Missing Permissions
13 replies
DIAdiscord.js - Imagine an app
Created by 布鲁诺 普雷托 on 2/1/2023 in #djs-questions
Message Commands and Actions
Hi, I've been for the past 2 hours trying to understand the commands that are prompt using < /test:0>, up till now what I understood is that </test:0> in a message will create some sort of built-in hyperlink and automatically fill the message prompt with /test. And the 0 is the command ID Similar to this there's <@USER_ID> My question is, what else can be done in the </Command:C_id> or what other cool stuff can be done using <> . I can't seem to find any documentation on this.
5 replies
DIAdiscord.js - Imagine an app
Created by 布鲁诺 普雷托 on 11/28/2022 in #djs-questions
Command Interactions Handler
So I have the folder ./commands, where I've got my commands, all is good there, however with button/menu interactions I manage them in the index.js file, I'm wondering if theres a way to handle them externaly in another file
37 replies
DIAdiscord.js - Imagine an app
Created by 布鲁诺 普雷托 on 11/21/2022 in #djs-questions
Create TextChannels
80 replies