commit 10a31d068ed86d3a3c1485bb0888d41f274297a1 Author: Nikita Karamov Date: Tue Sep 3 19:19:27 2024 +0200 WIP diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5b4bdef --- /dev/null +++ b/.gitignore @@ -0,0 +1,11 @@ +# dotenv environment variable files +.env +.env.development.local +.env.test.local +.env.production.local +.env.local + +# Fresh build directory +_fresh/ +# npm dependencies +node_modules/ diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 0000000..09cf720 --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,5 @@ +{ + "recommendations": [ + "denoland.vscode-deno" + ] +} diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..a5f0701 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,17 @@ +{ + "deno.enable": true, + "deno.lint": true, + "editor.defaultFormatter": "denoland.vscode-deno", + "[typescriptreact]": { + "editor.defaultFormatter": "denoland.vscode-deno" + }, + "[typescript]": { + "editor.defaultFormatter": "denoland.vscode-deno" + }, + "[javascriptreact]": { + "editor.defaultFormatter": "denoland.vscode-deno" + }, + "[javascript]": { + "editor.defaultFormatter": "denoland.vscode-deno" + } +} diff --git a/README.md b/README.md new file mode 100644 index 0000000..ec0e33e --- /dev/null +++ b/README.md @@ -0,0 +1,16 @@ +# Fresh project + +Your new Fresh project is ready to go. You can follow the Fresh "Getting +Started" guide here: https://fresh.deno.dev/docs/getting-started + +### Usage + +Make sure to install Deno: https://deno.land/manual/getting_started/installation + +Then start the project: + +``` +deno task start +``` + +This will watch the project directory and restart as necessary. diff --git a/components/Button.tsx b/components/Button.tsx new file mode 100644 index 0000000..f1b80a0 --- /dev/null +++ b/components/Button.tsx @@ -0,0 +1,12 @@ +import { JSX } from "preact"; +import { IS_BROWSER } from "$fresh/runtime.ts"; + +export function Button(props: JSX.HTMLAttributes) { + return ( + +

{props.count}

+ + + ); +} diff --git a/lib/instance.ts b/lib/instance.ts new file mode 100644 index 0000000..5a23c7e --- /dev/null +++ b/lib/instance.ts @@ -0,0 +1,60 @@ +/*! + * This file is part of Share₂Fedi + * https://github.com/kytta/share2fedi + * + * SPDX-FileCopyrightText: © 2023 Nikita Karamov + * SPDX-License-Identifier: AGPL-3.0-only + */ + +import { supportedProjects } from "$lib/project.ts"; + +interface Instance { + domain: string; + score: number; + active_users_monthly: number; + total_users: number; +} + +const getInstancesForProject = async ( + project: keyof typeof supportedProjects, +): Promise => { + let instances: Instance[]; + try { + const response = await fetch("https://api.fediverse.observer/", { + headers: { + Accept: "*/*", + "Accept-Language": "en;q=1.0", + "Content-Type": "application/json", + }, + body: JSON.stringify({ + query: + `{nodes(status:"UP",softwarename:"${project}"){domain score active_users_monthly total_users}}`, + }), + method: "POST", + }); + const json = await response.json(); + instances = json.data.nodes; + } catch (error) { + console.error(`Could not fetch instances for "${project}"`, error); + return []; + } + + return instances.filter( + (instance) => + instance.score > 90 && + // sanity check for some spammy-looking instances + instance.total_users >= instance.active_users_monthly, + ); +}; + +export const getPopularInstanceDomains = async (): Promise => { + const instancesPerProject = await Promise.all( + Object.keys(supportedProjects).map((project) => + getInstancesForProject(project) + ), + ); + const instances = instancesPerProject.flat(); + instances.sort((a, b) => b.active_users_monthly - a.active_users_monthly); + + return instances.slice(0, 200).map((instance) => instance.domain); +}; diff --git a/lib/nodeinfo.ts b/lib/nodeinfo.ts new file mode 100644 index 0000000..de0ec43 --- /dev/null +++ b/lib/nodeinfo.ts @@ -0,0 +1,61 @@ +/*! + * This file is part of Share₂Fedi + * https://github.com/kytta/share2fedi + * + * SPDX-FileCopyrightText: © 2023 Nikita Karamov + * SPDX-License-Identifier: AGPL-3.0-only + */ + +import { normalizeURL } from "$lib/url.ts"; + +interface NodeInfoList { + links: { + rel: string; + href: string; + }[]; +} + +interface NodeInfo { + software: { + name: string; + version: string; + [key: string]: unknown; + }; + [key: string]: unknown; +} + +export const getSoftwareName = async ( + domain: string, +): Promise => { + const nodeInfoListUrl = new URL( + "/.well-known/nodeinfo", + normalizeURL(domain), + ); + + let nodeInfoList: NodeInfoList; + try { + const nodeInfoListResponse = await fetch(nodeInfoListUrl); + nodeInfoList = await nodeInfoListResponse.json(); + } catch (error) { + console.error("Could not fetch '.well-known/nodeinfo':", error); + return undefined; + } + + for (const link of nodeInfoList.links) { + if ( + /^http:\/\/nodeinfo\.diaspora\.software\/ns\/schema\/(1\.0|1\.1|2\.0|2\.1)/ + .test( + link.rel, + ) + ) { + const nodeInfoResponse = await fetch(link.href); + const nodeInfo = (await nodeInfoResponse.json()) as NodeInfo; + + return nodeInfo.software.name; + } + } + + // not found + console.warn("No NodeInfo found for domain:", domain); + return undefined; +}; diff --git a/lib/project.ts b/lib/project.ts new file mode 100644 index 0000000..6307bea --- /dev/null +++ b/lib/project.ts @@ -0,0 +1,64 @@ +/*! + * This file is part of Share₂Fedi + * https://github.com/kytta/share2fedi + * + * SPDX-FileCopyrightText: © 2023 Nikita Karamov + * SPDX-License-Identifier: AGPL-3.0-only + */ + +export interface ProjectPublishConfig { + endpoint: string; + params: { + text: string; + }; +} + +const mastodonConfig: ProjectPublishConfig = { + endpoint: "share", + params: { + text: "text", + }, +}; + +const misskeyConfig: ProjectPublishConfig = { + endpoint: "share", + params: { + text: "text", + }, +}; + +/** + * Mapping of the supported fediverse projects. + * + * The keys of this mapping can be used as keys for the fediverse.observer API, + * icon names, etc. + */ +export const supportedProjects: Record = { + calckey: misskeyConfig, + fedibird: mastodonConfig, + firefish: misskeyConfig, + foundkey: misskeyConfig, + friendica: { + endpoint: "compose", + params: { + text: "body", + }, + }, + glitchcafe: mastodonConfig, + gnusocial: { + endpoint: "notice/new", + params: { + text: "status_textarea", + }, + }, + hometown: mastodonConfig, + hubzilla: { + endpoint: "rpost", + params: { + text: "body", + }, + }, + mastodon: mastodonConfig, + meisskey: misskeyConfig, + misskey: misskeyConfig, +}; diff --git a/lib/response.ts b/lib/response.ts new file mode 100644 index 0000000..6da9537 --- /dev/null +++ b/lib/response.ts @@ -0,0 +1,30 @@ +/*! + * This file is part of Share₂Fedi + * https://github.com/kytta/share2fedi + * + * SPDX-FileCopyrightText: © 2023 Nikita Karamov + * SPDX-License-Identifier: AGPL-3.0-only + */ + +export const json = ( + body: unknown, + status: number = 200, + headers: Record = {}, +) => { + return new Response(JSON.stringify(body), { + headers: { + "Content-Type": "application/json", + ...headers, + }, + status, + }); +}; + +export const error = (message: string, status: number = 400) => { + return json( + { + error: message, + }, + status, + ); +}; diff --git a/lib/url.ts b/lib/url.ts new file mode 100644 index 0000000..224648b --- /dev/null +++ b/lib/url.ts @@ -0,0 +1,35 @@ +/*! + * This file is part of Share₂Fedi + * https://github.com/kytta/share2fedi + * + * SPDX-FileCopyrightText: © 2023 Nikita Karamov + * SPDX-License-Identifier: AGPL-3.0-only + */ + +/** + * Adds missing "https://" and ending slash to the URL + * + * @param url URL to normalize + * @return normalized URL + */ +export const normalizeURL = (url: string): string => { + if (!(url.startsWith("https://") || url.startsWith("http://"))) { + url = "https://" + url; + } + if (!url.endsWith("/")) { + url += "/"; + } + return url; +}; + +export const getUrlDomain = (url: string | URL): string => { + if (typeof url === "string") { + url = url.trim(); + + if (!/^https?:\/\//.test(url)) { + url = `https://${url}`; + } + } + + return new URL(url).host; +}; diff --git a/main.ts b/main.ts new file mode 100644 index 0000000..404bfb0 --- /dev/null +++ b/main.ts @@ -0,0 +1,13 @@ +/// +/// +/// +/// +/// + +import "@std/dotenv/load"; + +import { start } from "$fresh/server.ts"; +import manifest from "./fresh.gen.ts"; +import config from "./fresh.config.ts"; + +await start(manifest, config); diff --git a/routes/_404.tsx b/routes/_404.tsx new file mode 100644 index 0000000..c63ae2e --- /dev/null +++ b/routes/_404.tsx @@ -0,0 +1,27 @@ +import { Head } from "$fresh/runtime.ts"; + +export default function Error404() { + return ( + <> + + 404 - Page not found + +
+
+ the Fresh logo: a sliced lemon dripping with juice +

404 - Page not found

+

+ The page you were looking for doesn't exist. +

+ Go back home +
+
+ + ); +} diff --git a/routes/_app.tsx b/routes/_app.tsx new file mode 100644 index 0000000..36b1ea2 --- /dev/null +++ b/routes/_app.tsx @@ -0,0 +1,22 @@ +import { type PageProps } from "$fresh/server.ts"; + +export default function App({ Component, state }: PageProps) { + return ( + + + + Share₂Fedi + + + + + + + + ); +} diff --git a/routes/_middleware.ts b/routes/_middleware.ts new file mode 100644 index 0000000..9188288 --- /dev/null +++ b/routes/_middleware.ts @@ -0,0 +1,35 @@ +import { FreshContext } from "$fresh/server.ts"; +import { defaultLanguage, languages } from "$i18n/translations.ts"; + +interface State { + languages: string[]; + prerenderLanguage: string; +} +const chooseLanguage = (localeTags: string[]): string => { + for (const tag of localeTags) { + const locale = new Intl.Locale(tag); + const minimized = locale.minimize(); + + for (const candidate of [locale.baseName, minimized.baseName]) { + if (candidate in languages) { + return candidate; + } + } + } + + return defaultLanguage; +}; + +export function handler( + req: Request, + ctx: FreshContext, +) { + const acceptLanguages = req.headers.get("Accept-Language") + ?.split(",") + .filter(Boolean) + .map((tag) => tag.split(";")[0].trim()) + .filter((tag) => tag !== "*") ?? []; + ctx.state.prerenderLanguage = chooseLanguage(acceptLanguages); + + return ctx.next(); +} diff --git a/routes/api/detect/[domain].ts b/routes/api/detect/[domain].ts new file mode 100644 index 0000000..74695b2 --- /dev/null +++ b/routes/api/detect/[domain].ts @@ -0,0 +1,37 @@ +import type { FreshContext, Handlers } from "$fresh/server.ts"; +import { getSoftwareName } from "$lib/nodeinfo.ts"; +import { type ProjectPublishConfig, supportedProjects } from "$lib/project.ts"; +import { error, json } from "$lib/response.ts"; + +type Detection = { + domain: string; + project: keyof typeof supportedProjects; +} & ProjectPublishConfig; + +export const handler: Handlers = { + async GET(_req: Request, ctx: FreshContext): Promise { + const domain = ctx.params.domain; + + const softwareName = await getSoftwareName(domain); + if (softwareName === undefined) { + return error("Could not detect Fediverse project."); + } + if (!(softwareName in supportedProjects)) { + return error(`Fediverse project "${softwareName}" is not supported yet.`); + } + + const publishConfig = + supportedProjects[softwareName] as ProjectPublishConfig; + return json( + { + domain, + project: softwareName, + ...publishConfig, + }, + 200, + { + "Cache-Control": "public, s-maxage=86400, max-age=604800", + }, + ); + }, +}; diff --git a/routes/api/instances.ts b/routes/api/instances.ts new file mode 100644 index 0000000..850eac4 --- /dev/null +++ b/routes/api/instances.ts @@ -0,0 +1,15 @@ +import type { FreshContext, Handlers } from "$fresh/server.ts"; +import { getPopularInstanceDomains } from "$lib/instance.ts"; +import { json } from "$lib/response.ts"; + +export const handler: Handlers = { + async GET(_req: Request, _ctx: FreshContext): Promise { + const popularInstanceDomains = await getPopularInstanceDomains(); + + return json(popularInstanceDomains, 200, { + "Cache-Control": popularInstanceDomains.length > 0 + ? "public, s-maxage=86400, max-age=604800" + : "public, s-maxage=60, max-age=3600", + }); + }, +}; diff --git a/routes/greet/[name].tsx b/routes/greet/[name].tsx new file mode 100644 index 0000000..9c06827 --- /dev/null +++ b/routes/greet/[name].tsx @@ -0,0 +1,5 @@ +import { PageProps } from "$fresh/server.ts"; + +export default function Greet(props: PageProps) { + return
Hello {props.params.name}
; +} diff --git a/routes/index.tsx b/routes/index.tsx new file mode 100644 index 0000000..27ba339 --- /dev/null +++ b/routes/index.tsx @@ -0,0 +1,71 @@ +import type { FreshContext, Handlers } from "$fresh/server.ts"; +import { useSignal } from "@preact/signals"; +import Counter from "../islands/Counter.tsx"; +import { type ProjectPublishConfig, supportedProjects } from "$lib/project.ts"; +import { getUrlDomain } from "$lib/url.ts"; +import { seeOther } from "@http/response/see-other"; + +type Detection = { + domain: string; + project: keyof typeof supportedProjects; +} & ProjectPublishConfig; + +import { z } from "zod"; + +const postSchema = z.object({ + text: z.string({ + required_error: "Please enter post text.", + }), + instance: z.string({ + required_error: "Please enter instance domain.", + }), +}); + +type POST = z.infer; + +export const handler: Handlers = { + async POST(req: Request, ctx: FreshContext): Promise { + const formData = await req.formData(); + const form = postSchema.safeParse(formData); + + if (!form.success) { + const errors = form.error?.format(); + return await ctx.render({ errors }); + } + + const instance = getUrlDomain(form.data.instance); + const detectResponse = await fetch( + new URL(`/api/detect/${instance}`, ctx.url), + ); + const { domain, endpoint, params } = await detectResponse.json(); + const publishUrl = new URL(endpoint, `https://${domain}/`); + publishUrl.search = new URLSearchParams([ + [params.text, form.data.text], + ]).toString(); + + return seeOther(publishUrl); + }, +}; + +export default function Home() { + const count = useSignal(3); + return ( +
+
+ the Fresh logo: a sliced lemon dripping with juice +

Welcome to Fresh

+

+ Try updating this message in the + ./routes/index.tsx file, and refresh. +

+ +
+
+ ); +} diff --git a/static/favicon.ico b/static/favicon.ico new file mode 100644 index 0000000..1cfaaa2 Binary files /dev/null and b/static/favicon.ico differ diff --git a/static/logo.svg b/static/logo.svg new file mode 100644 index 0000000..ef2fbe4 --- /dev/null +++ b/static/logo.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/static/styles.css b/static/styles.css new file mode 100644 index 0000000..e94132d --- /dev/null +++ b/static/styles.css @@ -0,0 +1,129 @@ + +*, +*::before, +*::after { + box-sizing: border-box; +} +* { + margin: 0; +} +button { + color: inherit; +} +button, [role="button"] { + cursor: pointer; +} +code { + font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, + "Liberation Mono", "Courier New", monospace; + font-size: 1em; +} +img, +svg { + display: block; +} +img, +video { + max-width: 100%; + height: auto; +} + +html { + line-height: 1.5; + -webkit-text-size-adjust: 100%; + font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, + "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, + "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; +} +.transition-colors { + transition-property: background-color, border-color, color, fill, stroke; + transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); + transition-duration: 150ms; +} +.my-6 { + margin-bottom: 1.5rem; + margin-top: 1.5rem; +} +.text-4xl { + font-size: 2.25rem; + line-height: 2.5rem; +} +.mx-2 { + margin-left: 0.5rem; + margin-right: 0.5rem; +} +.my-4 { + margin-bottom: 1rem; + margin-top: 1rem; +} +.mx-auto { + margin-left: auto; + margin-right: auto; +} +.px-4 { + padding-left: 1rem; + padding-right: 1rem; +} +.py-8 { + padding-bottom: 2rem; + padding-top: 2rem; +} +.bg-\[\#86efac\] { + background-color: #86efac; +} +.text-3xl { + font-size: 1.875rem; + line-height: 2.25rem; +} +.py-6 { + padding-bottom: 1.5rem; + padding-top: 1.5rem; +} +.px-2 { + padding-left: 0.5rem; + padding-right: 0.5rem; +} +.py-1 { + padding-bottom: 0.25rem; + padding-top: 0.25rem; +} +.border-gray-500 { + border-color: #6b7280; +} +.bg-white { + background-color: #fff; +} +.flex { + display: flex; +} +.gap-8 { + grid-gap: 2rem; + gap: 2rem; +} +.font-bold { + font-weight: 700; +} +.max-w-screen-md { + max-width: 768px; +} +.flex-col { + flex-direction: column; +} +.items-center { + align-items: center; +} +.justify-center { + justify-content: center; +} +.border-2 { + border-width: 2px; +} +.rounded { + border-radius: 0.25rem; +} +.hover\:bg-gray-200:hover { + background-color: #e5e7eb; +} +.tabular-nums { + font-variant-numeric: tabular-nums; +}