adapter migrate from vercel to node
This commit is contained in:
parent
a825f2a7a0
commit
c7cd229cae
861
package-lock.json
generated
861
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@ -21,7 +21,7 @@
|
||||
"@internationalized/date": "^3.5.5",
|
||||
"@playwright/test": "^1.43.1",
|
||||
"@rollup/plugin-dynamic-import-vars": "^2.1.2",
|
||||
"@sveltejs/adapter-vercel": "^5.3.0",
|
||||
"@sveltejs/adapter-node": "^5.2.3",
|
||||
"@sveltejs/kit": "^2.5.15",
|
||||
"@sveltejs/vite-plugin-svelte": "^3.1.0",
|
||||
"@types/gtag.js": "^0.0.19",
|
||||
|
||||
@ -1,30 +1,38 @@
|
||||
import PocketBase from "pocketbase";
|
||||
import { serializeNonPOJOs } from "$lib/utils";
|
||||
|
||||
const usRegion = new Set(["cle1", "iad1", "pdx1", "sfo1"]);
|
||||
|
||||
export const handle = async ({ event, resolve }) => {
|
||||
// Use optional chaining and nullish coalescing for safer property access
|
||||
const regionHeader =
|
||||
event?.request?.headers?.get("x-vercel-id") ??
|
||||
"fra1::fra1::8t4xg-1700258428633-157d82fdfcc7";
|
||||
|
||||
// Use a more compatible way to get the first element of the split array
|
||||
const userRegion = regionHeader.split("::")[0] || "";
|
||||
const ip =
|
||||
event.request.headers.get("x-forwarded-for") ||
|
||||
event.request.headers.get("remote-address");
|
||||
|
||||
const isUsRegion = usRegion.has(userRegion);
|
||||
let isUS = false;
|
||||
|
||||
if (ip) {
|
||||
const geoResponse = await fetch(`https://ipinfo.io/${ip}/geo`);
|
||||
const geoData = await geoResponse.json();
|
||||
if (geoData.country === "US") {
|
||||
isUS = true;
|
||||
//console.log("yelllo", geoData);
|
||||
}
|
||||
}
|
||||
|
||||
// Use a ternary operator instead of the logical OR for better compatibility
|
||||
const pbURL = isUsRegion
|
||||
const pbURL = isUS
|
||||
? import.meta.env.VITE_USEAST_POCKETBASE_URL
|
||||
: import.meta.env.VITE_EU_POCKETBASE_URL;
|
||||
const apiURL = isUsRegion
|
||||
const apiURL = isUS
|
||||
? import.meta.env.VITE_USEAST_API_URL
|
||||
: import.meta.env.VITE_EU_API_URL;
|
||||
const fastifyURL = isUsRegion
|
||||
const fastifyURL = isUS
|
||||
? import.meta.env.VITE_USEAST_FASTIFY_URL
|
||||
: import.meta.env.VITE_EU_FASTIFY_URL;
|
||||
const wsURL = isUsRegion
|
||||
const wsURL = isUS
|
||||
? import.meta.env.VITE_USEAST_WS_URL
|
||||
: import.meta.env.VITE_EU_WS_URL;
|
||||
|
||||
|
||||
@ -1,397 +1,364 @@
|
||||
import { createPostTextSchema,createPostImageSchema, createPostLinkSchema } from '$lib/schemas';
|
||||
import { validateData } from '$lib/utils';
|
||||
import { error, fail, redirect } from '@sveltejs/kit';
|
||||
import { serialize } from 'object-to-formdata';
|
||||
import { marked } from 'marked';
|
||||
import {
|
||||
createPostTextSchema,
|
||||
createPostImageSchema,
|
||||
createPostLinkSchema,
|
||||
} from "$lib/schemas";
|
||||
import { validateData } from "$lib/utils";
|
||||
import { error, fail, redirect } from "@sveltejs/kit";
|
||||
import { serialize } from "object-to-formdata";
|
||||
import { marked } from "marked";
|
||||
|
||||
import got from 'got';
|
||||
import cheerio from 'cheerio';
|
||||
import BlobUtil from 'blob-util';
|
||||
import sharp from 'sharp';
|
||||
import got from "got";
|
||||
import cheerio from "cheerio";
|
||||
import * as blobUtil from "blob-util"; // Changed import
|
||||
import sharp from "sharp";
|
||||
|
||||
function removeDuplicateClasses(str) {
|
||||
return str.replace(
|
||||
/class="([^"]*)"/,
|
||||
(match, classAttr) =>
|
||||
`class="${[...new Set(classAttr.split(" "))].join(" ")}"`
|
||||
);
|
||||
}
|
||||
|
||||
function addClassesToHtml(htmlString) {
|
||||
// Helper function to add a class to a specific tag
|
||||
function addClassToTag(tag, className) {
|
||||
// Add class if the tag doesn't already have a class attribute
|
||||
const regex = new RegExp(`<${tag}(?![^>]*\\bclass=)([^>]*)>`, "g");
|
||||
htmlString = htmlString.replace(regex, `<${tag} class="${className}"$1>`);
|
||||
|
||||
export const config = {
|
||||
runtime: 'nodejs20.x',
|
||||
};
|
||||
|
||||
|
||||
function removeDuplicateClasses(str) {
|
||||
return str.replace(/class="([^"]*)"/, (match, classAttr) => `class="${[...new Set(classAttr.split(' '))].join(' ')}"`);
|
||||
// Append the new class to tags that already have a class attribute, ensuring no duplicates
|
||||
const regexWithClass = new RegExp(
|
||||
`(<${tag}[^>]*\\bclass=["'][^"']*)(?!.*\\b${className}\\b)([^"']*)["']`,
|
||||
"g"
|
||||
);
|
||||
htmlString = htmlString.replace(regexWithClass, `$1 ${className}$2"`);
|
||||
}
|
||||
|
||||
function addClassesToHtml(htmlString) {
|
||||
// Helper function to add a class to a specific tag
|
||||
function addClassToTag(tag, className) {
|
||||
// Add class if the tag doesn't already have a class attribute
|
||||
const regex = new RegExp(`<${tag}(?![^>]*\\bclass=)([^>]*)>`, 'g');
|
||||
htmlString = htmlString.replace(regex, `<${tag} class="${className}"$1>`);
|
||||
|
||||
// Append the new class to tags that already have a class attribute, ensuring no duplicates
|
||||
const regexWithClass = new RegExp(`(<${tag}[^>]*\\bclass=["'][^"']*)(?!.*\\b${className}\\b)([^"']*)["']`, 'g');
|
||||
htmlString = htmlString.replace(regexWithClass, `$1 ${className}$2"`);
|
||||
}
|
||||
|
||||
// Add classes to headings
|
||||
addClassToTag('h1', 'text-lg');
|
||||
addClassToTag('h2', 'text-lg');
|
||||
addClassToTag('h3', 'text-lg');
|
||||
addClassToTag('h4', 'text-lg');
|
||||
addClassToTag('h5', 'text-lg');
|
||||
addClassToTag('h6', 'text-lg');
|
||||
|
||||
// Add classes to anchor tags
|
||||
addClassToTag('a', 'text-blue-400 hover:text-white underline');
|
||||
|
||||
// Add classes to ordered lists
|
||||
addClassToTag('ol', 'list-decimal ml-10 text-sm');
|
||||
|
||||
// Add classes to unordered lists
|
||||
addClassToTag('ul', 'list-disc ml-10 text-sm -mt-5');
|
||||
|
||||
// Add classes to blockquotes and their paragraphs
|
||||
function addClassToBlockquote() {
|
||||
// Add class to blockquote
|
||||
htmlString = htmlString.replace(
|
||||
/<blockquote/g,
|
||||
'<blockquote class="pl-4 pr-4 rounded-lg bg-[#323232]"'
|
||||
);
|
||||
|
||||
// Add class to p inside blockquote
|
||||
htmlString = htmlString.replace(
|
||||
/<blockquote([^>]*)>\s*<p/g,
|
||||
`<blockquote$1>\n<p class="text-sm font-medium leading-relaxed text-white"`
|
||||
);
|
||||
}
|
||||
|
||||
addClassToBlockquote();
|
||||
|
||||
// Remove duplicate classes after all modifications
|
||||
htmlString = removeDuplicateClasses(htmlString);
|
||||
|
||||
return htmlString;
|
||||
// Add classes to headings
|
||||
addClassToTag("h1", "text-lg");
|
||||
addClassToTag("h2", "text-lg");
|
||||
addClassToTag("h3", "text-lg");
|
||||
addClassToTag("h4", "text-lg");
|
||||
addClassToTag("h5", "text-lg");
|
||||
addClassToTag("h6", "text-lg");
|
||||
|
||||
// Add classes to anchor tags
|
||||
addClassToTag("a", "text-blue-400 hover:text-white underline");
|
||||
|
||||
// Add classes to ordered lists
|
||||
addClassToTag("ol", "list-decimal ml-10 text-sm");
|
||||
|
||||
// Add classes to unordered lists
|
||||
addClassToTag("ul", "list-disc ml-10 text-sm -mt-5");
|
||||
|
||||
// Add classes to blockquotes and their paragraphs
|
||||
function addClassToBlockquote() {
|
||||
// Add class to blockquote
|
||||
htmlString = htmlString.replace(
|
||||
/<blockquote/g,
|
||||
'<blockquote class="pl-4 pr-4 rounded-lg bg-[#323232]"'
|
||||
);
|
||||
|
||||
// Add class to p inside blockquote
|
||||
htmlString = htmlString.replace(
|
||||
/<blockquote([^>]*)>\s*<p/g,
|
||||
`<blockquote$1>\n<p class="text-sm font-medium leading-relaxed text-white"`
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
export const load = async ({ locals}) => {
|
||||
addClassToBlockquote();
|
||||
|
||||
if (!locals.pb.authStore.isValid) {
|
||||
redirect(303, '/login');
|
||||
}
|
||||
// Remove duplicate classes after all modifications
|
||||
htmlString = removeDuplicateClasses(htmlString);
|
||||
|
||||
return htmlString;
|
||||
}
|
||||
|
||||
export const load = async ({ locals }) => {
|
||||
if (!locals.pb.authStore.isValid) {
|
||||
redirect(303, "/login");
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
export const actions = {
|
||||
createPostText: async ({ request, locals }) => {
|
||||
let newPost = "";
|
||||
const body = await request.formData();
|
||||
body.delete("thumbnail");
|
||||
body.append("user", locals?.user?.id);
|
||||
|
||||
createPostText: async ({ request, locals }) => {
|
||||
let { formData, errors } = await validateData(body, createPostTextSchema);
|
||||
|
||||
let newPost = '';
|
||||
const body = await request.formData();
|
||||
body.delete('thumbnail');
|
||||
body.append('user', locals?.user?.id);
|
||||
formData.description = addClassesToHtml(marked(formData?.description));
|
||||
|
||||
let {formData, errors} = await validateData( body, createPostTextSchema);
|
||||
formData.tagTopic = JSON.parse(formData.tagTopic)[0];
|
||||
formData.upvote = 1;
|
||||
|
||||
formData.description = addClassesToHtml(marked(formData?.description))
|
||||
|
||||
if (errors) {
|
||||
return fail(400, {
|
||||
data: formData,
|
||||
errors: errors.fieldErrors,
|
||||
});
|
||||
}
|
||||
|
||||
formData.tagTopic = JSON.parse(formData.tagTopic)[0]
|
||||
formData.upvote = 1
|
||||
|
||||
//Each post gives the user +1 Karma points
|
||||
await locals.pb.collection("users").update(locals.user.id, {
|
||||
"karma+": 1,
|
||||
});
|
||||
|
||||
if(errors)
|
||||
{
|
||||
return fail(400, {
|
||||
data: formData,
|
||||
errors: errors.fieldErrors
|
||||
})
|
||||
}
|
||||
try {
|
||||
newPost = await locals.pb.collection("posts").create(serialize(formData));
|
||||
|
||||
|
||||
// add the tagTopic manually because serialize does not work on arrays
|
||||
await locals?.pb.collection("posts").update(newPost.id, {
|
||||
tagTopic: formData.tagTopic,
|
||||
});
|
||||
|
||||
//Each post gives the user +1 Karma points
|
||||
await locals.pb.collection("users").update(locals.user.id, {
|
||||
"karma+": 1,
|
||||
})
|
||||
//Save it collection alreadyVoted to keep track if user voted or not
|
||||
//FormData for alreadyVoted
|
||||
|
||||
try {
|
||||
let formDataAlreadyVoted = new FormData();
|
||||
formDataAlreadyVoted.append("post", newPost?.id);
|
||||
formDataAlreadyVoted.append("user", newPost?.user);
|
||||
formDataAlreadyVoted.append("type", "upvote");
|
||||
//console.log(formDataAlreadyVoted)
|
||||
await locals.pb.collection("alreadyVoted").create(formDataAlreadyVoted);
|
||||
} catch (err) {
|
||||
console.log("Error: ", err);
|
||||
error(err.status, err.message);
|
||||
}
|
||||
|
||||
newPost = await locals.pb.collection('posts').create(serialize(formData));
|
||||
|
||||
if (newPost?.id?.length !== 0) {
|
||||
redirect(303, "/community/post/" + newPost?.id);
|
||||
} else {
|
||||
redirect(303, "/community");
|
||||
}
|
||||
},
|
||||
|
||||
// add the tagTopic manually because serialize does not work on arrays
|
||||
await locals?.pb.collection("posts").update(newPost.id, {
|
||||
"tagTopic": formData.tagTopic,
|
||||
})
|
||||
createPostImage: async ({ request, locals }) => {
|
||||
let newPost = "";
|
||||
const body = await request.formData();
|
||||
const thumb = body.get("thumbnail");
|
||||
|
||||
//Save it collection alreadyVoted to keep track if user voted or not
|
||||
//FormData for alreadyVoted
|
||||
|
||||
let formDataAlreadyVoted = new FormData();
|
||||
formDataAlreadyVoted.append('post', newPost?.id);
|
||||
formDataAlreadyVoted.append('user', newPost?.user);
|
||||
formDataAlreadyVoted.append('type', 'upvote');
|
||||
//console.log(formDataAlreadyVoted)
|
||||
await locals.pb.collection('alreadyVoted').create(formDataAlreadyVoted);
|
||||
if (thumb?.size === 0) {
|
||||
body.delete("thumbnail");
|
||||
}
|
||||
|
||||
body.append("user", locals?.user?.id);
|
||||
|
||||
|
||||
} catch (err) {
|
||||
console.log('Error: ', err);
|
||||
error(err.status, err.message);
|
||||
}
|
||||
let { formData, errors } = await validateData(body, createPostImageSchema);
|
||||
|
||||
if(newPost?.id?.length !== 0) {
|
||||
redirect(303, '/community/post/'+newPost?.id);
|
||||
} else {
|
||||
redirect(303, '/community');
|
||||
}
|
||||
|
||||
formData.tagTopic = JSON.parse(formData.tagTopic)[0];
|
||||
formData.upvote = 1;
|
||||
|
||||
if (errors) {
|
||||
return fail(400, {
|
||||
data: formData,
|
||||
errors: errors.fieldErrors,
|
||||
});
|
||||
}
|
||||
|
||||
},
|
||||
//Each post gives the user +1 Karma points
|
||||
await locals.pb.collection("users").update(locals?.user?.id, {
|
||||
"karma+": 1,
|
||||
});
|
||||
|
||||
createPostImage: async ({ request, locals }) => {
|
||||
let newPost = '';
|
||||
const body = await request.formData();
|
||||
const thumb = body.get('thumbnail');
|
||||
if (formData.thumbnail.type.includes("image")) {
|
||||
try {
|
||||
const image = formData.thumbnail;
|
||||
const imageBuffer = await image.arrayBuffer();
|
||||
const imageBufferArray = new Uint8Array(imageBuffer);
|
||||
let optimizedImageBuffer;
|
||||
|
||||
if (thumb?.size === 0) {
|
||||
body.delete('thumbnail');
|
||||
}
|
||||
if (image.type === "image/gif") {
|
||||
// Process GIF files differently
|
||||
optimizedImageBuffer = imageBufferArray;
|
||||
} else {
|
||||
// Process other image formats (e.g., JPEG, PNG) using sharp library
|
||||
optimizedImageBuffer = await sharp(imageBufferArray)
|
||||
.resize({
|
||||
width: 800,
|
||||
height: 1000,
|
||||
fit: sharp.fit.inside,
|
||||
withoutEnlargement: true,
|
||||
})
|
||||
.jpeg({ quality: 80 })
|
||||
.toBuffer();
|
||||
}
|
||||
|
||||
body.append('user', locals?.user?.id);
|
||||
formData.thumbnail = new File([optimizedImageBuffer], image.name, {
|
||||
type: image.type,
|
||||
lastModified: image.lastModified,
|
||||
});
|
||||
} catch (err) {
|
||||
console.log("Error:", err);
|
||||
error(err.status, err.message);
|
||||
}
|
||||
}
|
||||
|
||||
let {formData, errors} = await validateData( body, createPostImageSchema);
|
||||
|
||||
formData.tagTopic = JSON.parse(formData.tagTopic)[0]
|
||||
formData.upvote = 1
|
||||
try {
|
||||
newPost = await locals.pb.collection("posts").create(serialize(formData));
|
||||
|
||||
// add the tagTopic manually because serialize does not work on arrays
|
||||
await locals?.pb.collection("posts").update(newPost.id, {
|
||||
tagTopic: formData?.tagTopic,
|
||||
});
|
||||
|
||||
if(errors)
|
||||
{
|
||||
//Save it collection alreadyVoted to keep track if user voted or not
|
||||
//FormData for alreadyVoted
|
||||
|
||||
return fail(400, {
|
||||
data: formData,
|
||||
errors: errors.fieldErrors
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
let formDataAlreadyVoted = new FormData();
|
||||
formDataAlreadyVoted.append("post", newPost.id);
|
||||
formDataAlreadyVoted.append("user", newPost.user);
|
||||
formDataAlreadyVoted.append("type", "upvote");
|
||||
//console.log(formDataAlreadyVoted)
|
||||
await locals.pb.collection("alreadyVoted").create(formDataAlreadyVoted);
|
||||
} catch (err) {
|
||||
console.log("Error: ", err);
|
||||
error(err.status, err.message);
|
||||
}
|
||||
|
||||
//Each post gives the user +1 Karma points
|
||||
await locals.pb.collection("users").update(locals?.user?.id, {
|
||||
"karma+": 1,
|
||||
})
|
||||
if (newPost?.id?.length !== 0) {
|
||||
redirect(303, "/community/post/" + newPost?.id);
|
||||
} else {
|
||||
redirect(303, "/community");
|
||||
}
|
||||
},
|
||||
|
||||
createPostLink: async ({ request, locals }) => {
|
||||
let newPost = "";
|
||||
const body = await request.formData();
|
||||
const url = body.get("link");
|
||||
let image;
|
||||
let description;
|
||||
let imageBlob;
|
||||
|
||||
|
||||
if (formData.thumbnail.type.includes('image')) {
|
||||
try {
|
||||
const image = formData.thumbnail;
|
||||
const imageBuffer = await image.arrayBuffer();
|
||||
const imageBufferArray = new Uint8Array(imageBuffer);
|
||||
let optimizedImageBuffer;
|
||||
|
||||
if (image.type === 'image/gif') {
|
||||
// Process GIF files differently
|
||||
optimizedImageBuffer = imageBufferArray;
|
||||
} else {
|
||||
// Process other image formats (e.g., JPEG, PNG) using sharp library
|
||||
optimizedImageBuffer = await sharp(imageBufferArray)
|
||||
.resize({
|
||||
width: 800,
|
||||
height: 1000,
|
||||
fit: sharp.fit.inside,
|
||||
withoutEnlargement: true,
|
||||
})
|
||||
.jpeg({ quality: 80 })
|
||||
.toBuffer();
|
||||
}
|
||||
|
||||
formData.thumbnail = new File([optimizedImageBuffer], image.name, {
|
||||
type: image.type,
|
||||
lastModified: image.lastModified,
|
||||
});
|
||||
|
||||
try {
|
||||
const response = await got(url, {
|
||||
headers: {
|
||||
"user-agent":
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3",
|
||||
},
|
||||
responseType: "buffer",
|
||||
});
|
||||
|
||||
} catch (err) {
|
||||
console.log('Error:', err);
|
||||
error(err.status, err.message);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
const $ = cheerio.load(response.body);
|
||||
//const title = $('head title').text();
|
||||
description = $('head meta[property="og:description"]').attr("content");
|
||||
image = $('head meta[property="og:image"]').attr("content");
|
||||
|
||||
|
||||
try {
|
||||
|
||||
newPost = await locals.pb.collection('posts').create(serialize(formData));
|
||||
|
||||
|
||||
// add the tagTopic manually because serialize does not work on arrays
|
||||
await locals?.pb.collection("posts").update(newPost.id, {
|
||||
"tagTopic": formData?.tagTopic,
|
||||
})
|
||||
if (!image) {
|
||||
let largestSize = 0;
|
||||
let largestImage = "";
|
||||
$("img").each(async function () {
|
||||
if (
|
||||
$(this).attr("src") &&
|
||||
$(this)
|
||||
.attr("src")
|
||||
.match(/\.(webp|jpg|jpeg|png|gif)$/)
|
||||
) {
|
||||
try {
|
||||
const imageBuffer = await got(image, {
|
||||
headers: {
|
||||
"user-agent":
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3",
|
||||
},
|
||||
responseType: "buffer",
|
||||
}).then((response) => response.body);
|
||||
imageBlob = await blobUtil.createBlob([imageBuffer], {
|
||||
// Changed usage
|
||||
type: "image/jpeg",
|
||||
});
|
||||
} catch (error) {
|
||||
// Handle the error when getting the image
|
||||
console.error("Error getting image:", error);
|
||||
}
|
||||
}
|
||||
});
|
||||
image = largestImage;
|
||||
}
|
||||
|
||||
|
||||
//Save it collection alreadyVoted to keep track if user voted or not
|
||||
//FormData for alreadyVoted
|
||||
|
||||
let formDataAlreadyVoted = new FormData();
|
||||
formDataAlreadyVoted.append('post', newPost.id);
|
||||
formDataAlreadyVoted.append('user', newPost.user);
|
||||
formDataAlreadyVoted.append('type', 'upvote');
|
||||
//console.log(formDataAlreadyVoted)
|
||||
await locals.pb.collection('alreadyVoted').create(formDataAlreadyVoted);
|
||||
|
||||
} catch (err) {
|
||||
console.log('Error: ', err);
|
||||
error(err.status, err.message);
|
||||
}
|
||||
// Download the image and append it to the form data
|
||||
const imageBuffer = await got(image, {
|
||||
headers: {
|
||||
"user-agent":
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3",
|
||||
},
|
||||
responseType: "buffer",
|
||||
}).then((response) => response.body);
|
||||
imageBlob = await blobUtil.createBlob([imageBuffer], {
|
||||
// Changed usage
|
||||
type: "image/jpeg",
|
||||
});
|
||||
} catch (e) {
|
||||
console.log(e);
|
||||
}
|
||||
|
||||
|
||||
if(newPost?.id?.length !== 0) {
|
||||
redirect(303, '/community/post/'+newPost?.id);
|
||||
} else {
|
||||
redirect(303, '/community');
|
||||
}
|
||||
//body.delete('thumbnail')
|
||||
//body.append('thumbnail', imageBlob);
|
||||
|
||||
// Append the title to the form data
|
||||
//body.append('name', title);
|
||||
body.append("user", locals.user.id);
|
||||
body.append("description", description);
|
||||
|
||||
},
|
||||
|
||||
|
||||
createPostLink: async ({ request, locals }) => {
|
||||
let newPost = '';
|
||||
const body = await request.formData();
|
||||
const url = body.get('link')
|
||||
let image;
|
||||
let description;
|
||||
let imageBlob;
|
||||
|
||||
try {
|
||||
const response = await got(url, { headers: {
|
||||
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
|
||||
},
|
||||
responseType: 'buffer' });
|
||||
|
||||
const $ = cheerio.load(response.body);
|
||||
//const title = $('head title').text();
|
||||
description= $('head meta[property="og:description"]').attr('content');
|
||||
image = $('head meta[property="og:image"]').attr('content');
|
||||
|
||||
if (!image) {
|
||||
let largestSize = 0;
|
||||
let largestImage = '';
|
||||
$('img').each(async function() {
|
||||
if ($(this).attr('src') && $(this).attr('src').match(/\.(webp|jpg|jpeg|png|gif)$/)) {
|
||||
try {
|
||||
const imageBuffer = await got($(this).attr('src'), { headers: {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'},responseType: 'buffer' }).then(response => response.body);
|
||||
const imageSize = (await sharp(imageBuffer).metadata()).width * (await sharp(imageBuffer).metadata()).height;
|
||||
if (imageSize > largestSize) {
|
||||
largestSize = imageSize;
|
||||
largestImage = $(this).attr('src');
|
||||
}
|
||||
} catch (error) {
|
||||
// Handle the error when getting the image
|
||||
console.error('Error getting image:', error);
|
||||
}
|
||||
}
|
||||
});
|
||||
image = largestImage;
|
||||
}
|
||||
|
||||
|
||||
// Download the image and append it to the form data
|
||||
const imageBuffer = await got(image, { headers: {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'},responseType: 'buffer' }).then(response => response.body);
|
||||
imageBlob = await BlobUtil.createBlob([imageBuffer], { type: 'image/jpeg' });
|
||||
|
||||
}
|
||||
|
||||
catch(e)
|
||||
{
|
||||
console.log(e)
|
||||
}
|
||||
|
||||
|
||||
//body.delete('thumbnail')
|
||||
//body.append('thumbnail', imageBlob);
|
||||
|
||||
// Append the title to the form data
|
||||
//body.append('name', title);
|
||||
body.append('user', locals.user.id);
|
||||
body.append('description', description);
|
||||
|
||||
|
||||
|
||||
/*
|
||||
/*
|
||||
const thumb = body.get('thumbnail');
|
||||
|
||||
if (thumb.size === 0) {
|
||||
body.delete('thumbnail');
|
||||
}
|
||||
*/
|
||||
|
||||
|
||||
let {formData, errors} = await validateData( body, createPostLinkSchema);
|
||||
let { formData, errors } = await validateData(body, createPostLinkSchema);
|
||||
|
||||
formData.tagTopic = JSON.parse(formData.tagTopic)[0]
|
||||
formData.upvote = 1
|
||||
formData.tagTopic = JSON.parse(formData.tagTopic)[0];
|
||||
formData.upvote = 1;
|
||||
|
||||
if (imageBlob?.length !== 0) {
|
||||
formData.thumbnail = imageBlob;
|
||||
}
|
||||
|
||||
if (imageBlob?.length !== 0) {
|
||||
formData.thumbnail = imageBlob
|
||||
if (errors) {
|
||||
return fail(400, {
|
||||
data: formData,
|
||||
errors: errors.fieldErrors,
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
//Each post gives the user +1 Karma points
|
||||
await locals.pb.collection("users").update(locals?.user?.id, {
|
||||
"karma+": 1,
|
||||
});
|
||||
|
||||
if(errors)
|
||||
{
|
||||
return fail(400, {
|
||||
data: formData,
|
||||
errors: errors.fieldErrors
|
||||
})
|
||||
}
|
||||
try {
|
||||
newPost = await locals.pb.collection("posts").create(serialize(formData));
|
||||
|
||||
// add the tagTopic manually because serialize does not work on arrays
|
||||
await locals.pb.collection("posts").update(newPost.id, {
|
||||
tagTopic: formData.tagTopic,
|
||||
});
|
||||
|
||||
//Each post gives the user +1 Karma points
|
||||
await locals.pb.collection("users").update(locals?.user?.id, {
|
||||
"karma+": 1,
|
||||
})
|
||||
//Save it collection alreadyVoted to keep track if user voted or not
|
||||
//FormData for alreadyVoted
|
||||
|
||||
try {
|
||||
newPost = await locals.pb.collection('posts').create(serialize(formData));
|
||||
|
||||
let formDataAlreadyVoted = new FormData();
|
||||
formDataAlreadyVoted.append("post", newPost.id);
|
||||
formDataAlreadyVoted.append("user", newPost.user);
|
||||
formDataAlreadyVoted.append("type", "upvote");
|
||||
//console.log(formDataAlreadyVoted)
|
||||
await locals.pb.collection("alreadyVoted").create(formDataAlreadyVoted);
|
||||
} catch (err) {
|
||||
console.log("Error: ", err);
|
||||
error(err.status, err.message);
|
||||
}
|
||||
|
||||
// add the tagTopic manually because serialize does not work on arrays
|
||||
await locals.pb.collection("posts").update(newPost.id, {
|
||||
"tagTopic": formData.tagTopic,
|
||||
})
|
||||
|
||||
//Save it collection alreadyVoted to keep track if user voted or not
|
||||
//FormData for alreadyVoted
|
||||
|
||||
let formDataAlreadyVoted = new FormData();
|
||||
formDataAlreadyVoted.append('post', newPost.id);
|
||||
formDataAlreadyVoted.append('user', newPost.user);
|
||||
formDataAlreadyVoted.append('type', 'upvote');
|
||||
//console.log(formDataAlreadyVoted)
|
||||
await locals.pb.collection('alreadyVoted').create(formDataAlreadyVoted);
|
||||
|
||||
} catch (err) {
|
||||
console.log('Error: ', err);
|
||||
error(err.status, err.message);
|
||||
}
|
||||
|
||||
if(newPost?.id?.length !== 0) {
|
||||
redirect(303, '/community/post/'+newPost?.id);
|
||||
} else {
|
||||
redirect(303, '/community');
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
|
||||
};
|
||||
if (newPost?.id?.length !== 0) {
|
||||
redirect(303, "/community/post/" + newPost?.id);
|
||||
} else {
|
||||
redirect(303, "/community");
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
//import adapter from '@sveltejs/adapter-static';
|
||||
import adapter from "@sveltejs/adapter-vercel";
|
||||
import adapter from "@sveltejs/adapter-node";
|
||||
|
||||
import compression from "compression";
|
||||
import { vitePreprocess } from "@sveltejs/vite-plugin-svelte";
|
||||
@ -10,8 +10,6 @@ const config = {
|
||||
adapter: adapter({
|
||||
// Add the compression middleware to the adapter options
|
||||
middleware: (handler) => compression()(handler),
|
||||
runtime: "nodejs20.x",
|
||||
regions: ["fra1"],
|
||||
worker: true, // Add this line if the adapter supports handling worker files
|
||||
}),
|
||||
},
|
||||
|
||||
@ -1,35 +1,37 @@
|
||||
import { sveltekit } from '@sveltejs/kit/vite';
|
||||
import { visualizer } from 'rollup-plugin-visualizer';
|
||||
import { sveltekit } from "@sveltejs/kit/vite";
|
||||
import { visualizer } from "rollup-plugin-visualizer";
|
||||
|
||||
/** @type {import('vite').UserConfig} */
|
||||
const config = {
|
||||
plugins: [
|
||||
sveltekit(),
|
||||
visualizer({ open: true }) // Plugin to visualize the bundle
|
||||
//visualizer({ open: true }) // Plugin to visualize the bundle
|
||||
],
|
||||
server: {
|
||||
cors: true,
|
||||
},
|
||||
build: {
|
||||
target: 'esnext',
|
||||
target: "esnext",
|
||||
minify: true,
|
||||
chunkSizeWarningLimit: 500, // Lower this to ensure chunks are appropriately sized
|
||||
rollupOptions: {
|
||||
output: {
|
||||
manualChunks(id) {
|
||||
if (id.includes('node_modules')) {
|
||||
return id.toString().split('node_modules/')[1].split('/')[0].toString();
|
||||
if (id.includes("node_modules")) {
|
||||
return id
|
||||
.toString()
|
||||
.split("node_modules/")[1]
|
||||
.split("/")[0]
|
||||
.toString();
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
brotliSize: true, // Enable Brotli compression
|
||||
},
|
||||
optimizeDeps: {
|
||||
exclude: [
|
||||
'pocketbase',
|
||||
],
|
||||
}
|
||||
exclude: ["pocketbase"],
|
||||
},
|
||||
};
|
||||
|
||||
export default config;
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user