web/website/node/organisation-socials.mjs

29 lines
1.7 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

export const ORGANISATION_SOCIALS_SCHEMA = `CREATE TABLE IF NOT EXISTS organisation_socials (
organisation_kind VARCHAR(16) NOT NULL, organisation_id CHAR(36) NOT NULL,
website VARCHAR(500) NOT NULL, discord_id VARCHAR(20) NOT NULL, discord_public INT NOT NULL,
updated_at BIGINT NOT NULL, PRIMARY KEY(organisation_kind,organisation_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`;
const discordId = /^\d{17,20}$/;
const officialGuild = '1567229433033531462';
export function validateOrganisationSocials(input) {
let website = typeof input.website === 'string' ? input.website.trim() : '';
const discord = typeof input.discordId === 'string' ? input.discordId.trim() : '';
if (website) {
let url;try{url=new URL(website);}catch{throw Error('Enter a public HTTPS website address.');}
if (url.href.length > 500 || url.protocol !== 'https:' || url.username || url.password) throw Error('Enter a public HTTPS website address.');
website=url.href;
}
if (discord && (!discordId.test(discord) || discord === officialGuild)) throw Error('Enter your organisation’s Discord server ID.');
if (typeof input.discordPublic !== 'boolean' || (input.discordPublic && !discord)) throw Error('Enter a Discord server ID before showing its widget.');
return {website, discordId:discord, discordPublic:input.discordPublic};
}
export async function readPublicSocials(db,kind,id) {
try {
const row=await db.prepare('SELECT website,discord_id,discord_public FROM organisation_socials WHERE organisation_kind=? AND organisation_id=?').bind(kind,id).first();
if (!row) return null;
return {website:row.website,discordId:Number(row.discord_public) === 1 && discordId.test(row.discord_id) && row.discord_id!==officialGuild ? row.discord_id : ''};
} catch {return null;}
}