Compare commits

...

17 Commits

Author SHA1 Message Date
Max Richter
7dda2dd60d feat: add kmenu icon for mobile 2025-11-12 16:12:57 +01:00
Max Richter
7ad08daf80 fix: make recipe crawling work 2025-11-12 15:41:30 +01:00
Max Richter
92126882b6 feat: correctly size search result items 2025-11-12 13:35:39 +01:00
Max Richter
655fc648e6 feat: fallback to unsplash cover when article contains no image 2025-11-09 23:52:53 +01:00
Max Richter
6c6b69a46a fix: make search work 2025-11-07 18:58:23 +01:00
Max Richter
97c5b7f93c fix: better position covers 2025-11-07 18:26:31 +01:00
Max Richter
bf3483019c fix: make unseen search work 2025-11-07 18:18:39 +01:00
Max Richter
5502c17c28 fix: correctly display noise gradient 2025-11-07 17:54:56 +01:00
Max Richter
581f1c1926 fix: make search usable again 2025-11-05 00:42:53 +01:00
Max Richter
7664abe089 fix: actually write image 2025-11-04 16:04:51 +01:00
Max Richter
bed7d1a11b feat: better log article creations 2025-11-04 13:57:32 +01:00
Max Richter
56a104c8b9 feat: use better names for md files 2025-11-04 13:26:49 +01:00
Max Richter
3103ed19fb fix: correctly fetch marka pi in background 2025-11-04 12:58:26 +01:00
Max Richter
fea9b69d4d feat: cache marka api responses 2025-11-04 12:09:17 +01:00
Max Richter
bb4e895770 fix: display correct name for series 2025-11-03 01:06:27 +01:00
Max Richter
28e9de4dc8 fix: make sure to only decode thumbhash once 2025-11-03 00:57:44 +01:00
Max Richter
ebb897dca4 fix: correctly embed styles.css 2025-11-03 00:46:49 +01:00
69 changed files with 1113 additions and 475 deletions

View File

@@ -10,5 +10,5 @@ export const Emoji = (props: { class?: string; name: string }) => {
/> />
) )
: <span>{props.name}</span> : <span>{props.name}</span>
: <></>; : null;
}; };

View File

@@ -47,6 +47,11 @@ const Image = (
"/api/images", "/api/images",
); );
const hasDimensions = typeof props.width === "number" &&
typeof props.height === "number";
const sizes = hasDimensions ? "" : responsiveAttributes.sizes;
const srcset = hasDimensions ? "" : responsiveAttributes.srcset;
return ( return (
<span <span
style={{ style={{
@@ -62,8 +67,8 @@ const Image = (
loading="lazy" loading="lazy"
alt={props.alt} alt={props.alt}
style={props.style} style={props.style}
srcset={responsiveAttributes.srcset} sizes={sizes}
sizes={responsiveAttributes.sizes} srcset={srcset}
src={`/api/images?image=${asset(props.src)}${ src={`/api/images?image=${asset(props.src)}${
props.width ? `&width=${props.width}` : "" props.width ? `&width=${props.width}` : ""
}${props.height ? `&height=${props.height}` : ""}`} }${props.height ? `&height=${props.height}` : ""}`}

View File

@@ -26,7 +26,7 @@ function generateJsonLd(resource: GenericResource): string {
if (resource.content?.datePublished) { if (resource.content?.datePublished) {
try { try {
baseSchema.datePublished = formatDate( baseSchema.datePublished = formatDate(
new Date(resource.content.datePublished), resource.content.datePublished,
); );
} catch (_) { } catch (_) {
// Ignore invalid date // Ignore invalid date

View File

@@ -1,5 +1,5 @@
import { IconStar, IconStarFilled } from "@components/icons.tsx"; import { IconStar, IconStarFilled } from "@components/icons.tsx";
import { useSignal } from "@preact/signals"; import { Signal, useSignal } from "@preact/signals";
import { useState } from "preact/hooks"; import { useState } from "preact/hooks";
export const SmallRating = ( export const SmallRating = (
@@ -24,27 +24,30 @@ export const SmallRating = (
}; };
export const Rating = ( export const Rating = (
props: { max?: number; rating: number }, { max, rating = useSignal(0) }: {
max?: number;
rating: Signal<number | undefined>;
},
) => { ) => {
const [rating, setRating] = useState(props.rating);
const [hover, setHover] = useState(0); const [hover, setHover] = useState(0);
const max = useSignal(props.max || 5);
const ratingValue = rating.value || 0;
return ( return (
<div <div
class="flex items-center gap-2 px-5 rounded-2xl bg-gray-200 z-10" class="flex items-center gap-2 px-5 rounded-2xl bg-gray-200 z-10 h-full"
style={{ color: "var(--foreground)", background: "var(--background)" }} style={{ color: "var(--foreground)", background: "var(--background)" }}
> >
{Array.from({ length: max.value }).map((_, i) => { {Array.from({ length: max || 5 }).map((_, i) => {
return ( return (
<span <span
class={`cursor-pointer opacity-${ class={`cursor-pointer opacity-${
(i + 1) <= rating ? 100 : (i + 1) <= hover ? 20 : 100 (i + 1) <= ratingValue ? 100 : (i + 1) <= hover ? 20 : 100
}`} }`}
onMouseOver={() => setHover(i + 1)} onMouseOver={() => setHover(i + 1)}
onClick={() => setRating(i + 1)} onClick={() => (rating.value = i + 1)}
> >
{(i + 1) <= rating || (i + 1) <= hover {(i + 1) <= ratingValue || (i + 1) <= hover
? <IconStarFilled class="w-4 h-4" /> ? <IconStarFilled class="w-4 h-4" />
: <IconStar class="w-4 h-4" />} : <IconStar class="w-4 h-4" />}
</span> </span>

View File

@@ -17,3 +17,5 @@ export { default as IconSearch } from "https://deno.land/x/tabler_icons_tsx@0.0.
export { default as IconGhost } from "https://deno.land/x/tabler_icons_tsx@0.0.3/tsx/ghost.tsx"; export { default as IconGhost } from "https://deno.land/x/tabler_icons_tsx@0.0.3/tsx/ghost.tsx";
export { default as IconBrandYoutube } from "https://deno.land/x/tabler_icons_tsx@0.0.3/tsx/brand-youtube.tsx"; export { default as IconBrandYoutube } from "https://deno.land/x/tabler_icons_tsx@0.0.3/tsx/brand-youtube.tsx";
export { default as IconWand } from "https://deno.land/x/tabler_icons_tsx@0.0.5/tsx/wand.tsx"; export { default as IconWand } from "https://deno.land/x/tabler_icons_tsx@0.0.5/tsx/wand.tsx";
export { default as IconMenu2 } from "https://deno.land/x/tabler_icons_tsx@0.0.5/tsx/menu-2.tsx";
export { default as IconAlertCircle } from "https://deno.land/x/tabler_icons_tsx@0.0.5/tsx/alert-circle.tsx";

View File

@@ -12,21 +12,29 @@ export type Props = {
searchResults?: GenericResource[]; searchResults?: GenericResource[];
}; };
function getQFromUrl(u: string | URL): string | null {
try {
const _u = typeof u === "string" ? new URL(u) : u;
return _u?.searchParams.get("q");
} catch (_e) {
return null;
}
}
export const MainLayout = ( export const MainLayout = (
{ children, url, context, searchResults }: Props, { children, url, context, searchResults }: Props,
) => { ) => {
const _url = typeof url === "string" ? new URL(url) : url; const q = getQFromUrl(url);
const hasSearch = _url?.search?.includes("q=");
if (hasSearch) { if (typeof q === "string") {
return ( return (
<Search <Search
q={_url.searchParams.get("q") || ""}
{...context} {...context}
q={q}
results={searchResults} results={searchResults}
/> />
); );
} }
return <>{children}</>; return children;
}; };

View File

@@ -48,6 +48,7 @@
"camelcase-css": "npm:camelcase-css", "camelcase-css": "npm:camelcase-css",
"thumbhash": "npm:thumbhash@^0.1.1", "thumbhash": "npm:thumbhash@^0.1.1",
"tsx": "npm:tsx@^4.19.2", "tsx": "npm:tsx@^4.19.2",
"turndown": "npm:turndown@^7.2.2",
"yaml": "https://deno.land/std@0.197.0/yaml/mod.ts", "yaml": "https://deno.land/std@0.197.0/yaml/mod.ts",
"zod": "npm:zod@^3.24.1", "zod": "npm:zod@^3.24.1",
"fs": "https://deno.land/std/fs/mod.ts" "fs": "https://deno.land/std/fs/mod.ts"

View File

@@ -11,6 +11,7 @@ import * as $admin_log_index from "./routes/admin/log/index.tsx";
import * as $admin_performance_index from "./routes/admin/performance/index.tsx"; import * as $admin_performance_index from "./routes/admin/performance/index.tsx";
import * as $api_articles_name_ from "./routes/api/articles/[name].ts"; import * as $api_articles_name_ from "./routes/api/articles/[name].ts";
import * as $api_articles_create_index from "./routes/api/articles/create/index.ts"; import * as $api_articles_create_index from "./routes/api/articles/create/index.ts";
import * as $api_articles_enhance_name_ from "./routes/api/articles/enhance/[name].ts";
import * as $api_articles_index from "./routes/api/articles/index.ts"; import * as $api_articles_index from "./routes/api/articles/index.ts";
import * as $api_auth_callback from "./routes/api/auth/callback.ts"; import * as $api_auth_callback from "./routes/api/auth/callback.ts";
import * as $api_auth_login from "./routes/api/auth/login.ts"; import * as $api_auth_login from "./routes/api/auth/login.ts";
@@ -57,7 +58,9 @@ import * as $KMenu_commands_create_movie from "./islands/KMenu/commands/create_m
import * as $KMenu_commands_create_recipe from "./islands/KMenu/commands/create_recipe.ts"; import * as $KMenu_commands_create_recipe from "./islands/KMenu/commands/create_recipe.ts";
import * as $KMenu_commands_create_recommendations from "./islands/KMenu/commands/create_recommendations.ts"; import * as $KMenu_commands_create_recommendations from "./islands/KMenu/commands/create_recommendations.ts";
import * as $KMenu_commands_create_series from "./islands/KMenu/commands/create_series.ts"; import * as $KMenu_commands_create_series from "./islands/KMenu/commands/create_series.ts";
import * as $KMenu_commands_enhance_article_infos from "./islands/KMenu/commands/enhance_article_infos.ts";
import * as $KMenu_types from "./islands/KMenu/types.ts"; import * as $KMenu_types from "./islands/KMenu/types.ts";
import * as $KMenuButton from "./islands/KMenuButton.tsx";
import * as $Link from "./islands/Link.tsx"; import * as $Link from "./islands/Link.tsx";
import * as $Recommendations from "./islands/Recommendations.tsx"; import * as $Recommendations from "./islands/Recommendations.tsx";
import * as $Search from "./islands/Search.tsx"; import * as $Search from "./islands/Search.tsx";
@@ -74,6 +77,7 @@ const manifest = {
"./routes/admin/performance/index.tsx": $admin_performance_index, "./routes/admin/performance/index.tsx": $admin_performance_index,
"./routes/api/articles/[name].ts": $api_articles_name_, "./routes/api/articles/[name].ts": $api_articles_name_,
"./routes/api/articles/create/index.ts": $api_articles_create_index, "./routes/api/articles/create/index.ts": $api_articles_create_index,
"./routes/api/articles/enhance/[name].ts": $api_articles_enhance_name_,
"./routes/api/articles/index.ts": $api_articles_index, "./routes/api/articles/index.ts": $api_articles_index,
"./routes/api/auth/callback.ts": $api_auth_callback, "./routes/api/auth/callback.ts": $api_auth_callback,
"./routes/api/auth/login.ts": $api_auth_login, "./routes/api/auth/login.ts": $api_auth_login,
@@ -127,7 +131,10 @@ const manifest = {
"./islands/KMenu/commands/create_recommendations.ts": "./islands/KMenu/commands/create_recommendations.ts":
$KMenu_commands_create_recommendations, $KMenu_commands_create_recommendations,
"./islands/KMenu/commands/create_series.ts": $KMenu_commands_create_series, "./islands/KMenu/commands/create_series.ts": $KMenu_commands_create_series,
"./islands/KMenu/commands/enhance_article_infos.ts":
$KMenu_commands_enhance_article_infos,
"./islands/KMenu/types.ts": $KMenu_types, "./islands/KMenu/types.ts": $KMenu_types,
"./islands/KMenuButton.tsx": $KMenuButton,
"./islands/Link.tsx": $Link, "./islands/Link.tsx": $Link,
"./islands/Recommendations.tsx": $Recommendations, "./islands/Recommendations.tsx": $Recommendations,
"./islands/Search.tsx": $Search, "./islands/Search.tsx": $Search,

View File

@@ -5,6 +5,7 @@ import { menus } from "@islands/KMenu/commands.ts";
import { MenuEntry } from "@islands/KMenu/types.ts"; import { MenuEntry } from "@islands/KMenu/types.ts";
import * as icons from "@components/icons.tsx"; import * as icons from "@components/icons.tsx";
import { IS_BROWSER } from "$fresh/runtime.ts"; import { IS_BROWSER } from "$fresh/runtime.ts";
import { isKMenuOpen } from "@lib/kmenu.ts";
const KMenuEntry = ( const KMenuEntry = (
{ entry, activeIndex, index }: { { entry, activeIndex, index }: {
entry: MenuEntry; entry: MenuEntry;
@@ -21,7 +22,7 @@ const KMenuEntry = (
: "text-gray-400" : "text-gray-400"
}`} }`}
> >
{entry?.icon && icons[entry.icon]({ class: "w-4 h-4 mr-1" })} {entry?.icon && icons[entry.icon]({ class: "min-w-4 h-4 mr-1" })}
{entry.title} {entry.title}
</div> </div>
); );
@@ -42,7 +43,7 @@ export const KMenu = (
const input = useRef<HTMLInputElement>(null); const input = useRef<HTMLInputElement>(null);
const commandInput = useSignal(""); const commandInput = useSignal("");
const visible = useSignal(false); const visible = isKMenuOpen;
if (visible.value === false) { if (visible.value === false) {
setTimeout(() => { setTimeout(() => {
activeMenuType.value = "main"; activeMenuType.value = "main";
@@ -168,13 +169,15 @@ export const KMenu = (
style={{ background: "#2B2930", color: "#818181" }} style={{ background: "#2B2930", color: "#818181" }}
> >
<div <div
class={`grid h-12 text-gray-400 ${ class={`grid min-h-12 text-gray-400 ${
activeState.value !== "loading" && "border-b" (activeState.value === "normal" || activeState.value === "input") &&
"border-b"
} border-gray-500 `} } border-gray-500 `}
style={{ style={{
gridTemplateColumns: activeState.value !== "loading" gridTemplateColumns:
? "auto 1fr" (activeState.value === "normal" || activeState.value === "input")
: "1fr", ? "auto 1fr"
: "1fr",
}} }}
> >
{(activeState.value === "normal" || activeState.value === "input") && {(activeState.value === "normal" || activeState.value === "input") &&
@@ -198,12 +201,18 @@ export const KMenu = (
)} )}
{activeState.value === "loading" && ( {activeState.value === "loading" && (
<div class="py-3 px-4 flex items-center gap-2"> <div class="py-3 px-4 flex items-center gap-2">
<icons.IconLoader2 class="animate-spin w-4 h-4" /> <icons.IconLoader2 class="animate-spin min-w-4 h-4" />
{loadingText.value || "Loading..."} {loadingText.value || "Loading..."}
</div> </div>
)} )}
{activeState.value === "error" && (
<div class="py-3 px-4 flex items-center gap-2 text-red-400">
<icons.IconAlertCircle class="min-w-4 h-4" />
{loadingText.value || "An error occurred"}
</div>
)}
</div> </div>
{activeState.value === "normal" && {(activeState.value === "normal" || activeState.value === "input") &&
( (
<div <div
class="" class=""

View File

@@ -7,6 +7,7 @@ import { addSeriesInfo } from "@islands/KMenu/commands/add_series_infos.ts";
import { createNewSeries } from "@islands/KMenu/commands/create_series.ts"; import { createNewSeries } from "@islands/KMenu/commands/create_series.ts";
import { updateAllRecommendations } from "@islands/KMenu/commands/create_recommendations.ts"; import { updateAllRecommendations } from "@islands/KMenu/commands/create_recommendations.ts";
import { createNewRecipe } from "@islands/KMenu/commands/create_recipe.ts"; import { createNewRecipe } from "@islands/KMenu/commands/create_recipe.ts";
import { enhanceArticleInfo } from "@islands/KMenu/commands/enhance_article_infos.ts";
export const menus: Record<string, Menu> = { export const menus: Record<string, Menu> = {
main: { main: {
@@ -77,6 +78,7 @@ export const menus: Record<string, Menu> = {
createNewSeries, createNewSeries,
createNewRecipe, createNewRecipe,
addMovieInfos, addMovieInfos,
enhanceArticleInfo,
// updateAllRecommendations, // updateAllRecommendations,
], ],
}, },

View File

@@ -8,39 +8,53 @@ export const addMovieInfos: MenuEntry = {
meta: "", meta: "",
icon: "IconReportSearch", icon: "IconReportSearch",
cb: async (state, context) => { cb: async (state, context) => {
state.activeState.value = "loading"; try {
const movie = context as ReviewResource; state.activeState.value = "loading";
const movie = context as ReviewResource;
const query = movie.name; const query = movie.name;
const response = await fetch( const response = await fetch(
`/api/tmdb/query?q=${encodeURIComponent(query)}`, `/api/tmdb/query?q=${encodeURIComponent(query)}`,
); );
const json = await response.json() as TMDBMovie[]; if (!response.ok) {
throw new Error(await response.text());
}
const menuID = `result/${movie.name}`; const json = await response.json() as TMDBMovie[];
state.menus[menuID] = { const menuID = `result/${movie.name}`;
title: "Select",
entries: json.map((m) => ({
title: `${m.title} released ${m.release_date}`,
cb: async () => {
state.activeState.value = "loading";
await fetch(`/api/movies/enhance/${movie.name}/`, {
method: "POST",
body: JSON.stringify({ tmdbId: m.id }),
});
state.visible.value = false;
state.activeState.value = "normal";
globalThis.location.reload();
},
})),
};
state.activeMenu.value = menuID; state.menus[menuID] = {
state.commandInput.value = ""; title: "Select",
state.activeState.value = "normal"; entries: json.map((m) => ({
title: `${m.title} released ${m.release_date}`,
cb: async () => {
try {
state.activeState.value = "loading";
await fetch(`/api/movies/enhance/${movie.name}/`, {
method: "POST",
body: JSON.stringify({ tmdbId: m.id }),
});
state.visible.value = false;
state.activeState.value = "normal";
globalThis.location.reload();
} catch (e) {
state.activeState.value = "error";
state.loadingText.value = e.message;
}
},
})),
};
state.activeMenu.value = menuID;
state.commandInput.value = "";
state.activeState.value = "normal";
} catch (e) {
state.activeState.value = "error";
state.loadingText.value = e.message;
}
}, },
visible: () => { visible: () => {
const loc = globalThis["location"]; const loc = globalThis["location"];

View File

@@ -8,39 +8,53 @@ export const addSeriesInfo: MenuEntry = {
meta: "", meta: "",
icon: "IconReportSearch", icon: "IconReportSearch",
cb: async (state, context) => { cb: async (state, context) => {
state.activeState.value = "loading"; try {
const series = context as ReviewResource; state.activeState.value = "loading";
const series = context as ReviewResource;
const query = series.name; const query = series.name;
const response = await fetch( const response = await fetch(
`/api/tmdb/query?q=${encodeURIComponent(query)}&type=serie`, `/api/tmdb/query?q=${encodeURIComponent(query)}&type=serie`,
); );
const json = await response.json() as TMDBSeries[]; if (!response.ok) {
throw new Error(await response.text());
}
const menuID = `result/${series.name}`; const json = await response.json() as TMDBSeries[];
state.menus[menuID] = { const menuID = `result/${series.name}`;
title: "Select",
entries: json.map((m) => ({
title: `${m.name || m.original_name} released ${m.first_air_date}`,
cb: async () => {
state.activeState.value = "loading";
await fetch(`/api/series/enhance/${series.name}/`, {
method: "POST",
body: JSON.stringify({ tmdbId: m.id }),
});
state.visible.value = false;
state.activeState.value = "normal";
//window.location.reload();
},
})),
};
state.commandInput.value = ""; state.menus[menuID] = {
state.activeMenu.value = menuID; title: "Select",
state.activeState.value = "normal"; entries: json.map((m) => ({
title: `${m.name || m.original_name} released ${m.first_air_date}`,
cb: async () => {
try {
state.activeState.value = "loading";
await fetch(`/api/series/enhance/${series.name}/`, {
method: "POST",
body: JSON.stringify({ tmdbId: m.id }),
});
state.visible.value = false;
state.activeState.value = "normal";
//window.location.reload();
} catch (e) {
state.activeState.value = "error";
state.loadingText.value = e.message;
}
},
})),
};
state.commandInput.value = "";
state.activeMenu.value = menuID;
state.activeState.value = "normal";
} catch (e) {
state.activeState.value = "error";
state.loadingText.value = e.message;
}
}, },
visible: () => { visible: () => {
const loc = globalThis["location"]; const loc = globalThis["location"];

View File

@@ -22,14 +22,16 @@ export const createNewArticle: MenuEntry = {
state.activeState.value = "loading"; state.activeState.value = "loading";
fetchStream("/api/articles/create?url=" + value, (chunk) => { fetchStream("/api/articles/create?url=" + value, (chunk) => {
if (chunk.startsWith("id:")) { if (chunk.type === "error") {
state.activeState.value = "error";
state.loadingText.value = chunk.message;
} else if (chunk.type === "finished") {
state.loadingText.value = "Finished"; state.loadingText.value = "Finished";
setTimeout(() => { setTimeout(() => {
window.location.href = "/articles/" + globalThis.location.href = "/articles/" + chunk.url;
chunk.replace("id:", "").trim();
}, 500); }, 500);
} else { } else {
state.loadingText.value = chunk; state.loadingText.value = chunk.message;
} }
}); });
} }

View File

@@ -31,35 +31,52 @@ export const createNewMovie: MenuEntry = {
let currentQuery: string; let currentQuery: string;
const search = debounce(async function search(query: string) { const search = debounce(async function search(query: string) {
currentQuery = query; try {
if (query.length < 2) { currentQuery = query;
return; if (query.length < 2) {
return;
}
const response = await fetch("/api/tmdb/query?q=" + query);
if (!response.ok) {
throw new Error(await response.text());
}
const movies = await response.json() as TMDBMovie[];
if (query !== currentQuery) return;
state.menus["input_link"] = {
title: "Search",
entries: movies.map((r) => {
return {
title: `${r.title} - ${r.release_date}`,
cb: async () => {
try {
state.activeState.value = "loading";
const response = await fetch("/api/movies/" + r.id, {
method: "POST",
});
if (!response.ok) {
throw new Error(await response.text());
}
const movie = await response.json() as ReviewResource;
unsub();
globalThis.location.href = "/movies/" + movie.name;
} catch (e) {
state.activeState.value = "error";
state.loadingText.value = e.message;
}
},
};
}),
};
state.activeMenu.value = "input_link";
} catch (e) {
state.activeState.value = "error";
state.loadingText.value = e.message;
} }
const response = await fetch("/api/tmdb/query?q=" + query);
const movies = await response.json() as TMDBMovie[];
if (query !== currentQuery) return;
state.menus["input_link"] = {
title: "Search",
entries: movies.map((r) => {
return {
title: `${r.title} - ${r.release_date}`,
cb: async () => {
state.activeState.value = "loading";
const response = await fetch("/api/movies/" + r.id, {
method: "POST",
});
const movie = await response.json() as ReviewResource;
unsub();
globalThis.location.href = "/movies/" + movie.name;
},
};
}),
};
state.activeMenu.value = "input_link";
}, 500); }, 500);
const unsub = state.commandInput.subscribe((value) => { const unsub = state.commandInput.subscribe((value) => {

View File

@@ -21,15 +21,17 @@ export const createNewRecipe: MenuEntry = {
state.activeState.value = "loading"; state.activeState.value = "loading";
fetchStream("/api/recipes/create?url=" + value, (chunk) => { fetchStream("/api/recipes/create?url=" + value, (msg) => {
if (chunk.startsWith("id:")) { if (msg.type === "error") {
state.activeState.value = "error";
state.loadingText.value = msg.message;
} else if (msg.type === "finished") {
state.loadingText.value = "Finished"; state.loadingText.value = "Finished";
setTimeout(() => { setTimeout(() => {
globalThis.location.href = "/recipes/" + globalThis.location.href = "/recipes/" + msg.url;
chunk.replace("id:", "").trim();
}, 500); }, 500);
} else { } else {
state.loadingText.value = chunk; state.loadingText.value = msg.message;
} }
}); });
} }

View File

@@ -10,12 +10,15 @@ export const updateAllRecommendations: MenuEntry = {
state.activeState.value = "loading"; state.activeState.value = "loading";
fetchStream("/api/recommendation/all", (chunk) => { fetchStream("/api/recommendation/all", (chunk) => {
if (chunk.toLowerCase().includes("finish")) { if (chunk.type === "error") {
state.activeState.value = "error";
state.loadingText.value = chunk.message;
} else if (chunk.type === "finished") {
setTimeout(() => { setTimeout(() => {
window.location.reload(); globalThis.location.reload();
}, 500); }, 500);
} else { } else {
state.loadingText.value = chunk; state.loadingText.value = chunk.message;
} }
}); });
}, },

View File

@@ -31,38 +31,55 @@ export const createNewSeries: MenuEntry = {
let currentQuery: string; let currentQuery: string;
const search = debounce(async function search(query: string) { const search = debounce(async function search(query: string) {
currentQuery = query; try {
if (query.length < 2) { currentQuery = query;
return; if (query.length < 2) {
return;
}
const response = await fetch(
"/api/tmdb/query?q=" + query + "&type=series",
);
if (!response.ok) {
throw new Error(await response.text());
}
const series = await response.json() as TMDBSeries[];
if (query !== currentQuery) return;
state.menus["input_link"] = {
title: "Search",
entries: series.map((r) => {
return {
title: `${r.name} - ${r.first_air_date}`,
cb: async () => {
try {
state.activeState.value = "loading";
const response = await fetch("/api/series/" + r.id, {
method: "POST",
});
if (!response.ok) {
throw new Error(await response.text());
}
const series = await response.json() as ReviewResource;
unsub();
globalThis.location.href = "/series/" + series.name;
} catch (e) {
state.activeState.value = "error";
state.loadingText.value = e.message;
}
},
};
}),
};
state.commandInput.value = "";
state.activeMenu.value = "input_link";
} catch (e) {
state.activeState.value = "error";
state.loadingText.value = e.message;
} }
const response = await fetch(
"/api/tmdb/query?q=" + query + "&type=series",
);
const series = await response.json() as TMDBSeries[];
if (query !== currentQuery) return;
state.menus["input_link"] = {
title: "Search",
entries: series.map((r) => {
return {
title: `${r.name} - ${r.first_air_date}`,
cb: async () => {
state.activeState.value = "loading";
const response = await fetch("/api/series/" + r.id, {
method: "POST",
});
const series = await response.json() as ReviewResource;
unsub();
globalThis.location.href = "/series/" + series.name;
},
};
}),
};
state.commandInput.value = "";
state.activeMenu.value = "input_link";
}, 500); }, 500);
const unsub = state.commandInput.subscribe((value) => { const unsub = state.commandInput.subscribe((value) => {

View File

@@ -0,0 +1,41 @@
import { getCookie } from "@lib/string.ts";
import { MenuEntry } from "../types.ts";
import { ArticleResource } from "@lib/marka/schema.ts";
import { fetchStream } from "@lib/helpers.ts";
export const enhanceArticleInfo: MenuEntry = {
title: "Enhance Article Info",
meta: "Update metadata and content from source url",
icon: "IconReportSearch",
cb: (state, context) => {
state.activeState.value = "loading";
const article = context as ArticleResource;
fetchStream(
`/api/articles/enhance/${article.name}/`,
(chunk) => {
if (chunk.type === "error") {
state.activeState.value = "error";
state.loadingText.value = chunk.message;
} else if (chunk.type == "finished") {
state.loadingText.value = "Finished";
setTimeout(() => {
state.visible.value = false;
state.activeState.value = "normal";
globalThis.location.reload();
}, 500);
} else {
state.loadingText.value = chunk.message;
}
},
{ method: "POST" },
);
},
visible: () => {
const loc = globalThis["location"];
if (!getCookie("session_cookie")) return false;
return (loc?.pathname?.includes("article") &&
!loc.pathname.endsWith("articles"));
},
};

14
islands/KMenuButton.tsx Normal file
View File

@@ -0,0 +1,14 @@
import { Button } from "@components/Button.tsx";
import { IconMenu2 } from "@components/icons.tsx";
import { isKMenuOpen } from "@lib/kmenu.ts";
export default function KMenuButton() {
return (
<Button
class="fixed bottom-4 right-4 md:hidden bg-gray-800 text-white p-3 rounded-full shadow-lg z-50"
onClick={() => (isKMenuOpen.value = true)}
>
<IconMenu2 class="w-6 h-6" />
</Button>
);
}

View File

@@ -23,7 +23,7 @@ export async function fetchQueryResource(url: URL, type = "") {
url.searchParams.set("status", "not-seen"); url.searchParams.set("status", "not-seen");
} }
if (type) { if (type) {
url.searchParams.set("types", type); url.searchParams.set("type", type);
} }
const response = await fetch(url); const response = await fetch(url);
const jsonData = await response.json(); const jsonData = await response.json();
@@ -55,8 +55,8 @@ const SearchResultImage = ({ src }: { src: string }) => {
return ( return (
<Image <Image
class="object-cover w-12 h-12 rounded-full" class="object-cover w-12 h-12 rounded-full"
width="50" width={100}
height="50" height={100}
src={src} src={src}
alt="preview image" alt="preview image"
/> />
@@ -114,6 +114,7 @@ const Search = (
const searchQuery = useSignal(q); const searchQuery = useSignal(q);
const data = useSignal<GenericResource[] | undefined>(results); const data = useSignal<GenericResource[] | undefined>(results);
const isLoading = useSignal(false); const isLoading = useSignal(false);
const rating = useSignal<number | undefined>(undefined);
const showSeenStatus = useSignal(false); const showSeenStatus = useSignal(false);
const inputRef = useRef<HTMLInputElement>(null); const inputRef = useRef<HTMLInputElement>(null);
@@ -122,8 +123,10 @@ const Search = (
if (u.searchParams.get("q") !== searchQuery.value) { if (u.searchParams.get("q") !== searchQuery.value) {
u.searchParams.set("q", searchQuery.value); u.searchParams.set("q", searchQuery.value);
} }
if (showSeenStatus.value) { if (showSeenStatus.value === true) {
u.searchParams.set("rating", "0"); u.searchParams.set("rating", "0");
} else if (rating.value) {
u.searchParams.set("rating", rating.value.toString());
} else { } else {
u.searchParams.delete("rating"); u.searchParams.delete("rating");
} }
@@ -162,7 +165,7 @@ const Search = (
useEffect(() => { useEffect(() => {
debouncedFetchData(); // Call the debounced fetch function with the updated search query debouncedFetchData(); // Call the debounced fetch function with the updated search query
}, [searchQuery.value, showSeenStatus.value]); }, [searchQuery.value, showSeenStatus.value, rating.value]);
useEffect(() => { useEffect(() => {
debouncedFetchData(); debouncedFetchData();
@@ -187,8 +190,12 @@ const Search = (
onInput={handleInputChange} onInput={handleInputChange}
/> />
</div> </div>
<Checkbox label="seen" checked={showSeenStatus} /> <Checkbox label="unrated" checked={showSeenStatus} />
<Rating rating={4} /> <div
class={showSeenStatus.value ? "opacity-10" : ""}
>
<Rating rating={rating} />
</div>
</header> </header>
{data.value?.length && !isLoading.value {data.value?.length && !isLoading.value
? <SearchResultList showEmoji={!type} result={data.value} /> ? <SearchResultList showEmoji={!type} result={data.value} />

View File

@@ -7,6 +7,7 @@ export const PROXY_PASSWORD = Deno.env.get("PROXY_PASSWORD");
export const TMDB_API_KEY = Deno.env.get("TMDB_API_KEY"); export const TMDB_API_KEY = Deno.env.get("TMDB_API_KEY");
export const OPENAI_API_KEY = Deno.env.get("OPENAI_API_KEY"); export const OPENAI_API_KEY = Deno.env.get("OPENAI_API_KEY");
export const YOUTUBE_API_KEY = Deno.env.get("YOUTUBE_API_KEY"); export const YOUTUBE_API_KEY = Deno.env.get("YOUTUBE_API_KEY");
export const UNSPLASH_API_KEY = Deno.env.get("UNSPLASH_API_KEY");
export const TELEGRAM_API_KEY = Deno.env.get("TELEGRAM_API_KEY")!; export const TELEGRAM_API_KEY = Deno.env.get("TELEGRAM_API_KEY")!;
export const GITEA_SERVER = Deno.env.get("GITEA_SERVER"); export const GITEA_SERVER = Deno.env.get("GITEA_SERVER");
@@ -18,6 +19,7 @@ const duration = Deno.env.get("SESSION_DURATION");
export const SESSION_DURATION = duration ? +duration : (60 * 60 * 24); export const SESSION_DURATION = duration ? +duration : (60 * 60 * 24);
export const MARKA_API_KEY = Deno.env.get("MARKA_API_KEY"); export const MARKA_API_KEY = Deno.env.get("MARKA_API_KEY");
export const MARKA_API_URL = Deno.env.get("MARKA_API_URL");
export const JWT_SECRET = Deno.env.get("JWT_SECRET"); export const JWT_SECRET = Deno.env.get("JWT_SECRET");

View File

@@ -31,19 +31,54 @@ export const fixRenderedMarkdown = (content: string) => {
}); });
}; };
export async function fetchStream(url: string, cb: (chunk: string) => void) { type StreamMessage = {
const response = await fetch(url); type: "info";
const reader = response?.body?.getReader(); message: string;
if (reader) { } | {
while (true) { type: "error";
const { done, value } = await reader.read(); message: string;
if (done) return; } | {
const data = new TextDecoder().decode(value); type: "warning";
data message: string;
.split("$") } | {
.filter((d) => d && d.length) type: "finished";
.map((d) => cb(Array.isArray(d) ? d[0] : d)); url: string;
} };
export async function fetchStream(
url: string,
cb: (chunk: StreamMessage) => void,
init?: RequestInit,
) {
const res = await fetch(url, init);
if (!res.body) return;
let buffer = "";
const reader = res.body
.pipeThrough(new TextDecoderStream())
.pipeThrough(
new TransformStream<string, string>({
transform(chunk, controller) {
buffer += chunk;
let idx;
while ((idx = buffer.indexOf("\n")) >= 0) {
const line = buffer.slice(0, idx).trim();
buffer = buffer.slice(idx + 1);
if (line) controller.enqueue(line);
}
},
flush(controller) {
const line = buffer.trim();
if (line) controller.enqueue(line);
},
}),
)
.getReader();
while (true) {
const { done, value } = await reader.read();
if (done) break;
cb(JSON.parse(value));
} }
} }
@@ -58,32 +93,53 @@ export function hashString(message: string) {
} }
export const createStreamResponse = () => { export const createStreamResponse = () => {
let controller: ReadableStreamController<ArrayBufferView>; const encoder = new TextEncoder();
const body = new ReadableStream({ let controller: ReadableStreamDefaultController<Uint8Array>;
start(cont) {
controller = cont; const body = new ReadableStream<Uint8Array>({
start(c) {
controller = c;
}, },
}); });
const response = new Response(body, { const response = new Response(body, {
headers: { headers: {
"content-type": "text/plain", // newline-delimited JSON
"content-type": "application/x-ndjson; charset=utf-8",
// prevent intermediaries from buffering/transforming
"cache-control": "no-cache, no-transform",
"x-content-type-options": "nosniff", "x-content-type-options": "nosniff",
// nginx hint to disable proxy buffering
"x-accel-buffering": "no",
// if you control compression, keep it off for streams
// "content-encoding": "identity",
}, },
}); });
function cancel() { const send = (obj: unknown) => {
controller.close(); controller.enqueue(encoder.encode(JSON.stringify(obj) + "\n")); // ← delimiter
};
const cancel = () => controller.close();
function info(message: string) {
return send({ type: "info", message });
} }
function enqueue(chunk: string) { function error(message: string) {
controller?.enqueue(new TextEncoder().encode("$" + chunk)); return send({ type: "error", message });
}
function warning(message: string) {
return send({ type: "warning", message });
} }
return { return {
response, response,
cancel, cancel,
enqueue, send,
info,
error,
warning,
}; };
}; };

3
lib/kmenu.ts Normal file
View File

@@ -0,0 +1,3 @@
import { signal } from "@preact/signals";
export const isKMenuOpen = signal(false);

View File

@@ -41,7 +41,6 @@ export async function getLogs() {
date: new Date(date), date: new Date(date),
} as Log; } as Log;
}); });
console.log(logs);
// Return the logs sorted by date // Return the logs sorted by date
return logs.sort((a, b) => a.date.getTime() - b.date.getTime()); return logs.sort((a, b) => a.date.getTime() - b.date.getTime());

View File

@@ -38,13 +38,13 @@ export function createLogger(scope: string, _options?: LoggerOptions): Logger {
export function loggerFromStream(stream: StreamResponse) { export function loggerFromStream(stream: StreamResponse) {
return { return {
debug: (...data: unknown[]) => debug: (...data: unknown[]) =>
stream.enqueue(`${data.length > 1 ? data.join(" ") : data[0]}`), stream.info(`${data.length > 1 ? data.join(" ") : data[0]}`),
info: (...data: unknown[]) => info: (...data: unknown[]) =>
stream.enqueue(`${data.length > 1 ? data.join(" ") : data[0]}`), stream.info(`${data.length > 1 ? data.join(" ") : data[0]}`),
error: (...data: unknown[]) => error: (...data: unknown[]) =>
stream.enqueue(`[ERROR]: ${data.length > 1 ? data.join(" ") : data[0]}`), stream.error(`[ERROR]: ${data.length > 1 ? data.join(" ") : data[0]}`),
warn: (...data: unknown[]) => warn: (...data: unknown[]) =>
stream.enqueue(`[WARN]: ${data.length > 1 ? data.join(" ") : data[0]}`), stream.warning(`[WARN]: ${data.length > 1 ? data.join(" ") : data[0]}`),
}; };
} }

View File

@@ -1,10 +1,8 @@
import { MARKA_API_KEY } from "../env.ts"; import { createCache } from "../cache.ts";
import { MARKA_API_KEY, MARKA_API_URL } from "../env.ts";
import { getImage } from "../image.ts"; import { getImage } from "../image.ts";
import { GenericResource } from "./schema.ts"; import { GenericResource } from "./schema.ts";
const url = `https://marka.max-richter.dev`;
//const url = "http://localhost:8080";
async function addImageToResource<T extends GenericResource>( async function addImageToResource<T extends GenericResource>(
resource: GenericResource, resource: GenericResource,
): Promise<T> { ): Promise<T> {
@@ -14,7 +12,7 @@ async function addImageToResource<T extends GenericResource>(
const absoluteImageUrl = (imageUrl.startsWith("https://") || const absoluteImageUrl = (imageUrl.startsWith("https://") ||
imageUrl.startsWith("http://")) imageUrl.startsWith("http://"))
? imageUrl ? imageUrl
: `${url}/${imageUrl}`; : `${MARKA_API_URL}/${imageUrl}`;
const image = await getImage(absoluteImageUrl); const image = await getImage(absoluteImageUrl);
return { ...resource, image } as T; return { ...resource, image } as T;
} catch (e) { } catch (e) {
@@ -24,34 +22,68 @@ async function addImageToResource<T extends GenericResource>(
return resource as T; return resource as T;
} }
type Resource = GenericResource & {
content: GenericResource["content"] & Array<GenericResource>;
};
const fetchCache = createCache<Resource>("marka");
const cacheLock = new Map<string, Promise<Resource>>();
async function fetchAndStoreUrl(url: string) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Failed to fetch resource: ${response.status}`);
}
const res = await response.json();
fetchCache.set(url, res);
return res;
}
async function cachedFetch(
url: string,
): Promise<Resource | undefined> {
if (fetchCache.has(url)) {
fetchAndStoreUrl(url); // Fetch the url in the background
return fetchCache.get(url);
}
if (cacheLock.has(url)) return cacheLock.get(url);
const response = fetchAndStoreUrl(url);
cacheLock.set(url, response);
const res = await response;
cacheLock.delete(url);
return res;
}
export async function fetchResource<T extends GenericResource>( export async function fetchResource<T extends GenericResource>(
resource: string, resource: string,
): Promise<T | undefined> { ): Promise<T | undefined> {
try { try {
const response = await fetch( const d = `${MARKA_API_URL}/resources/${resource}`;
`${url}/resources/${resource}`, const res = await cachedFetch(d);
); if (!res) return;
const res = await response.json();
return addImageToResource<T>(res); return addImageToResource<T>(res);
} catch (_e) { } catch (_e) {
return; return;
} }
} }
export async function listResources<T = GenericResource>( export async function listResources<T extends GenericResource>(
resource: string, resource: string,
): Promise<T[]> { ): Promise<T[]> {
try { try {
const response = await fetch( const d = `${MARKA_API_URL}/resources/${resource}`;
`${url}/resources/${resource}`, const list = await cachedFetch(d);
); if (!list) return [];
const list = await response.json();
return Promise.all( return Promise.all(
list?.content list?.content
.filter((a: GenericResource) => a?.content?._type) .filter((a) => a?.content?._type)
.map((res: GenericResource) => addImageToResource(res)), .map((res) => addImageToResource(res) as Promise<T>),
); );
} catch (_e) { } catch (_e) {
console.log(`Failed to fetch resource: ${resource}`, _e);
return []; return [];
} }
} }
@@ -62,7 +94,7 @@ export async function createResource(
) { ) {
const isJson = typeof content === "object" && const isJson = typeof content === "object" &&
!(content instanceof ArrayBuffer); !(content instanceof ArrayBuffer);
const fetchUrl = `${url}/resources/${path}`; const fetchUrl = `${MARKA_API_URL}/resources/${path}`;
const headers = new Headers(); const headers = new Headers();
headers.append("Content-Type", isJson ? "application/json" : ""); headers.append("Content-Type", isJson ? "application/json" : "");
if (MARKA_API_KEY) { if (MARKA_API_KEY) {
@@ -74,7 +106,12 @@ export async function createResource(
body: isJson ? JSON.stringify(content) : content, body: isJson ? JSON.stringify(content) : content,
}); });
if (!response.ok) { if (!response.ok) {
throw new Error(`Failed to create resource: ${response.status}`); const text = await response.text();
throw new Error(
`failed to create resource (resources/${path}): ${
text || response.status
}`,
);
} }
return response.json(); return response.json();
} }

View File

@@ -195,6 +195,23 @@ respond with a plain unordered list each item starting with the year the movie w
return recommendations; return recommendations;
}; };
export async function createUnsplashSearchTerm(content: string) {
if (!openAI) return;
const chatCompletion = await openAI.chat.completions.create({
model: model,
messages: [
{
role: "system",
content:
"Please respond with a search term for unsplash for the following article",
},
{ role: "user", content: content.slice(0, 10_000) },
],
});
return chatCompletion.choices[0].message.content?.toLowerCase();
}
export async function createTags(content: string) { export async function createTags(content: string) {
if (!openAI) return; if (!openAI) return;
const chatCompletion = await openAI.chat.completions.create({ const chatCompletion = await openAI.chat.completions.create({

View File

@@ -9,7 +9,7 @@ export async function fetchHtmlWithPlaywright(
fetchUrl: string, fetchUrl: string,
streamResponse: ReturnType<typeof createStreamResponse>, streamResponse: ReturnType<typeof createStreamResponse>,
): Promise<string> { ): Promise<string> {
streamResponse.enqueue("booting up playwright"); streamResponse.info("booting up playwright");
const config: Parameters<typeof firefox.launch>[0] = {}; const config: Parameters<typeof firefox.launch>[0] = {};
if (env.PROXY_SERVER) { if (env.PROXY_SERVER) {
@@ -24,7 +24,7 @@ export async function fetchHtmlWithPlaywright(
// Launch the Playwright browser // Launch the Playwright browser
const browser = await firefox.launch(config); const browser = await firefox.launch(config);
streamResponse.enqueue("fetching html"); streamResponse.info("fetching html");
try { try {
// Open a new browser context and page // Open a new browser context and page
@@ -42,7 +42,7 @@ export async function fetchHtmlWithPlaywright(
return html; return html;
} catch (error) { } catch (error) {
streamResponse.enqueue("error fetching html"); streamResponse.error("error fetching html");
console.error(error); console.error(error);
return ""; return "";
} finally { } finally {

View File

@@ -18,8 +18,9 @@ export const IngredientGroupSchema = z.object({
export type IngredientGroup = z.infer<typeof IngredientGroupSchema>; export type IngredientGroup = z.infer<typeof IngredientGroupSchema>;
const recipeSchema = z.object({ const recipeSchema = z.object({
_type: z.literal("Recipe"),
name: z.string().describe( name: z.string().describe(
"Title of the Recipe, without the name of the website or author", "Name of the Recipe, without the name of the website or author",
), ),
description: z.string().describe( description: z.string().describe(
"Optional, short description of the recipe", "Optional, short description of the recipe",
@@ -41,11 +42,7 @@ const recipeSchema = z.object({
export type Recipe = z.infer<typeof recipeSchema>; export type Recipe = z.infer<typeof recipeSchema>;
const noRecipeSchema = z.object({ const noRecipeSchema = z.literal("none").describe("No Recipe found");
errorMessages: z.array(z.string()).describe(
"List of error messages, if no recipe was found",
),
});
export const recipeResponseSchema = z.union([recipeSchema, noRecipeSchema]); export const recipeResponseSchema = z.union([recipeSchema, noRecipeSchema]);

View File

@@ -74,7 +74,7 @@ export function getRecommendation(
} }
export async function getSimilarMovies(id: string) { export async function getSimilarMovies(id: string) {
const recs = getRecommendation(id, "movie"); const recs = getRecommendation(id, "movies");
if (!recs?.keywords?.length) return; if (!recs?.keywords?.length) return;
const recommendations = await openai.getMovieRecommendations( const recommendations = await openai.getMovieRecommendations(

View File

@@ -1,26 +1,26 @@
export const resources = { export const resources = {
"home": { "home": {
emoji: "House with Garden.png", emoji: "home_icon.png",
name: "Home", name: "Home",
link: "/", link: "/",
}, },
"recipe": { "recipe": {
emoji: "Fork and Knife with Plate.png", emoji: "recipes_icon.png",
name: "Recipes", name: "Recipes",
link: "/recipes", link: "/recipes",
}, },
"movie": { "movie": {
emoji: "Popcorn.png", emoji: "movies_icon.png",
name: "Movies", name: "Movies",
link: "/movies", link: "/movies",
}, },
"article": { "article": {
emoji: "Writing Hand Medium-Light Skin Tone.png", emoji: "articles_icon.png",
name: "Articles", name: "Articles",
link: "/articles", link: "/articles",
}, },
"series": { "series": {
emoji: "Television.png", emoji: "tv_series_icon.png",
name: "Series", name: "Series",
link: "/series", link: "/series",
}, },

View File

@@ -19,7 +19,7 @@ export function parseResourceUrl(_url: string | URL): SearchParams | undefined {
try { try {
const url = typeof _url === "string" ? new URL(_url) : _url; const url = typeof _url === "string" ? new URL(_url) : _url;
let query = url.searchParams.get("q") || "*"; let query = url.searchParams.get("q") || "*";
if (!query) { if (!(typeof query === "string")) {
return undefined; return undefined;
} }
query = decodeURIComponent(query); query = decodeURIComponent(query);
@@ -54,12 +54,14 @@ export async function searchResource(
{ q, tags = [], types, rating }: SearchParams, { q, tags = [], types, rating }: SearchParams,
): Promise<GenericResource[]> { ): Promise<GenericResource[]> {
const resources = (await Promise.all([ const resources = (await Promise.all([
(!types || types.includes("movie")) && listResources("movies"), (!types || types.includes("movies")) && listResources("movies"),
(!types || types.includes("series")) && listResources("series"), (!types || types.includes("series")) && listResources("series"),
(!types || types.includes("article")) && listResources("articles"), (!types || types.includes("articles")) && listResources("articles"),
(!types || types.includes("recipe")) && listResources("recipes"), (!types || types.includes("recipes")) && listResources("recipes"),
])).flat().filter(isResource); ])).flat().filter(isResource);
console.log({ types, rating, tags, q, resourceLength: resources.length });
const results: Record<string, GenericResource> = {}; const results: Record<string, GenericResource> = {};
for (const resource of resources) { for (const resource of resources) {
@@ -71,9 +73,18 @@ export async function searchResource(
results[resource.name] = resource; results[resource.name] = resource;
} }
// Select not-rated resources
if ( if (
!(resource.name in results) && rating === 0 &&
rating && resource.content.reviewRating?.ratingValue && resource.content?.reviewRating?.ratingValue === undefined
) {
results[resource.name] = resource;
}
if (
typeof rating === "number" &&
rating !== 0 &&
resource.content.reviewRating?.ratingValue &&
parseRating(resource.content.reviewRating.ratingValue) >= rating parseRating(resource.content.reviewRating.ratingValue) >= rating
) { ) {
results[resource.name] = resource; results[resource.name] = resource;
@@ -81,6 +92,7 @@ export async function searchResource(
} }
if (q.length && q !== "*") { if (q.length && q !== "*") {
q = decodeURIComponent(q);
const fuzzyResult = fuzzysort.go(q, resources, { const fuzzyResult = fuzzysort.go(q, resources, {
keys: [ keys: [
"name", "name",
@@ -92,6 +104,7 @@ export async function searchResource(
], ],
threshold: 0.3, threshold: 0.3,
}); });
console.log({ fuzzyResult });
for (const result of fuzzyResult) { for (const result of fuzzyResult) {
results[result.obj.name] = result.obj; results[result.obj.name] = result.obj;
} }

View File

@@ -1,23 +1,37 @@
export function formatDate(date: Date): string { export function formatDate(date?: string | Date): string {
if (!date) return "";
if (typeof date === "string") {
try {
const d = new Date(date);
return formatDate(d);
} catch (_e) {
return "";
}
}
const options = { year: "numeric", month: "long", day: "numeric" } as const; const options = { year: "numeric", month: "long", day: "numeric" } as const;
return new Intl.DateTimeFormat("en-US", options).format(date); return new Intl.DateTimeFormat("en-US", options).format(date);
} }
export function safeFileName(inputString: string): string { export function safeFileName(input: string): string {
let fileName = inputString.toLowerCase(); return input
fileName = fileName.replace(/ /g, "_"); .normalize("NFKD")
fileName = fileName.replace(/[^\w.-]/g, ""); .replace(/[\u0300-\u036f]/g, "")
fileName = fileName.replaceAll(":", ""); .replace(/[\s-]+/g, "_")
return fileName; .replace(/-+/g, "-")
.replace(/[^A-Za-z0-9_]+/g, "")
.replace(/_+/g, "_")
// Trim underscores/dots from ends and prevent leading dots
.replace(/^[_\.]+|[_\.]+$/g, "").replace(/^\.+/, "")
.toLowerCase();
} }
export function toUrlSafeString(input: string): string { export function toUrlSafeString(input: string): string {
return input return input
.trim() // Remove leading and trailing whitespace .normalize("NFKD")
.toLowerCase() // Convert to lowercase .replace(/[\u0300-\u036f]/g, "")
.replace(/[^a-z0-9\s-]/g, "") // Remove non-alphanumeric characters except spaces and hyphens .replace(/[^A-Za-z0-9 _-]+/g, "")
.replace(/\s+/g, "-") // Replace spaces with hyphens .replace(/\s+/g, " ")
.replace(/-+/g, "-"); // Remove consecutive hyphens .trim();
} }
export function extractHashTags(inputString: string) { export function extractHashTags(inputString: string) {

29
lib/unsplash.ts Normal file
View File

@@ -0,0 +1,29 @@
import { UNSPLASH_API_KEY } from "./env.ts";
const API_URL = "https://api.unsplash.com";
export async function getImageBySearchTerm(
searchTerm: string,
): Promise<string | undefined> {
if (!UNSPLASH_API_KEY) {
throw new Error("UNSPLASH_API_KEY is not set");
}
const url = new URL("/search/photos", API_URL);
url.searchParams.append("query", searchTerm);
url.searchParams.append("per_page", "1");
url.searchParams.append("orientation", "landscape");
const response = await fetch(url.toString(), {
headers: {
Authorization: `Client-ID ${UNSPLASH_API_KEY}`,
},
});
if (!response.ok) {
throw new Error(`Unsplash API request failed: ${response.statusText}`);
}
const data = await response.json();
return data.results[0]?.urls?.regular;
}

View File

@@ -1,6 +1,8 @@
import { JSDOM } from "jsdom"; import { JSDOM } from "jsdom";
import { fetchHtmlWithPlaywright } from "./playwright.ts"; import { fetchHtmlWithPlaywright } from "./playwright.ts";
import { createStreamResponse } from "./helpers.ts"; import { createStreamResponse } from "./helpers.ts";
import { Defuddle } from "defuddle/node";
import TurndownService from "turndown";
/** /**
* Mutates the given JSDOM instance: rewrites all relevant URL-bearing attributes * Mutates the given JSDOM instance: rewrites all relevant URL-bearing attributes
@@ -164,6 +166,8 @@ function absolutizeMetaRefresh(content: string, base: string): string {
return `${delay}; url=${abs}`; return `${delay}; url=${abs}`;
} }
const turndownService = new TurndownService();
export async function webScrape( export async function webScrape(
url: string, url: string,
streamResponse: ReturnType<typeof createStreamResponse>, streamResponse: ReturnType<typeof createStreamResponse>,
@@ -172,5 +176,12 @@ export async function webScrape(
const html = await fetchHtmlWithPlaywright(url, streamResponse); const html = await fetchHtmlWithPlaywright(url, streamResponse);
const dom = new JSDOM(html); const dom = new JSDOM(html);
absolutizeDomUrls(dom, u.origin); absolutizeDomUrls(dom, u.origin);
return dom;
const result = await Defuddle(dom, url);
return {
...result,
dom: dom.window.document,
markdown: turndownService.turndown(result.content),
};
} }

View File

@@ -74,6 +74,11 @@ export interface PageInfo {
resultsPerPage: number; resultsPerPage: number;
} }
export async function getYoutubeVideoCover(id: string): Promise<ArrayBuffer> {
const res = await fetch(`https://i.ytimg.com/vi/${id}/maxresdefault.jpg`);
return res.arrayBuffer();
}
export async function getYoutubeVideoDetails( export async function getYoutubeVideoDetails(
id: string, id: string,
): Promise<Item> { ): Promise<Item> {
@@ -81,6 +86,5 @@ export async function getYoutubeVideoDetails(
`${BASE_URL}videos?part=snippet%2CcontentDetails%2Cstatistics&id=${id}&key=${YOUTUBE_API_KEY}`, `${BASE_URL}videos?part=snippet%2CcontentDetails%2Cstatistics&id=${id}&key=${YOUTUBE_API_KEY}`,
); );
const json = await response.json(); const json = await response.json();
return json?.items[0]; return json?.items[0];
} }

View File

@@ -1,11 +1,9 @@
// deno-lint-ignore-file react-no-danger
import { PageProps } from "$fresh/server.ts"; import { PageProps } from "$fresh/server.ts";
import { Partial } from "$fresh/runtime.ts"; import { Partial } from "$fresh/runtime.ts";
import { useEffect } from "preact/hooks";
export default function App({ Component }: PageProps) { export default function App({ Component }: PageProps) {
const globalCss = Deno const globalCss = Deno.readTextFileSync("./static/global.css");
.readTextFileSync("./static/global.css")
.replaceAll("\n", "");
return ( return (
<html> <html>
@@ -21,7 +19,19 @@ export default function App({ Component }: PageProps) {
<meta name="msapplication-TileColor" content="#da532c" /> <meta name="msapplication-TileColor" content="#da532c" />
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#141218" /> <meta name="theme-color" content="#141218" />
<style>{globalCss}</style> <link
rel="preload"
href="/fonts/work-sans-v18-latin-regular.woff2"
as="font"
type="font/woff2"
/>
<link
rel="preload"
href="/fonts/work-sans-v18-latin-700.woff2"
as="font"
type="font/woff2"
/>
<style dangerouslySetInnerHTML={{ __html: globalCss }} />
<title>Memorium</title> <title>Memorium</title>
</head> </head>
<body f-client-nav> <body f-client-nav>

View File

@@ -2,6 +2,7 @@ import { PageProps } from "$fresh/server.ts";
import { resources } from "@lib/resources.ts"; import { resources } from "@lib/resources.ts";
import { Link } from "@islands/Link.tsx"; import { Link } from "@islands/Link.tsx";
import { Emoji } from "@components/Emoji.tsx"; import { Emoji } from "@components/Emoji.tsx";
import KMenuButton from "@islands/KMenuButton.tsx";
export default function MyLayout({ Component }: PageProps) { export default function MyLayout({ Component }: PageProps) {
return ( return (
@@ -23,12 +24,10 @@ export default function MyLayout({ Component }: PageProps) {
})} })}
</nav> </nav>
</aside> </aside>
<main <main class="py-5">
class="py-5"
style={{ fontFamily: "Work Sans" }}
>
<Component /> <Component />
</main> </main>
<KMenuButton />
</div> </div>
); );
} }

View File

@@ -20,7 +20,7 @@ export default function Greet(
<MainLayout <MainLayout
url={props.url} url={props.url}
title="Recipes" title="Recipes"
context={{ type: "recipe" }} context={{ type: "recipes" }}
> >
<code> <code>
<pre class="text-white"> <pre class="text-white">

View File

@@ -3,19 +3,78 @@ import { Defuddle } from "defuddle/node";
import { AccessDeniedError, BadRequestError } from "@lib/errors.ts"; import { AccessDeniedError, BadRequestError } from "@lib/errors.ts";
import { createStreamResponse, isValidUrl } from "@lib/helpers.ts"; import { createStreamResponse, isValidUrl } from "@lib/helpers.ts";
import * as openai from "@lib/openai.ts"; import * as openai from "@lib/openai.ts";
import * as unsplash from "@lib/unsplash.ts";
import { getYoutubeVideoDetails } from "@lib/youtube.ts"; import { getYoutubeVideoDetails } from "@lib/youtube.ts";
import { import {
extractYoutubeId, extractYoutubeId,
formatDate,
isYoutubeLink, isYoutubeLink,
safeFileName,
toUrlSafeString, toUrlSafeString,
} from "@lib/string.ts"; } from "@lib/string.ts";
import { createLogger } from "@lib/log/index.ts"; import { createLogger } from "@lib/log/index.ts";
import { createResource } from "@lib/marka/index.ts"; import { createResource } from "@lib/marka/index.ts";
import { webScrape } from "@lib/webScraper.ts"; import { webScrape } from "@lib/webScraper.ts";
import { ArticleResource } from "@lib/marka/schema.ts"; import { ArticleResource } from "@lib/marka/schema.ts";
import { fileExtension } from "https://deno.land/x/file_extension@v2.1.0/mod.ts";
const log = createLogger("api/article"); const log = createLogger("api/article");
async function getUnsplashCoverImage(
content: string,
streamResponse: ReturnType<typeof createStreamResponse>,
): Promise<string | undefined> {
try {
streamResponse.info("creating unsplash search term");
const searchTerm = await openai.createUnsplashSearchTerm(content);
if (!searchTerm) return;
streamResponse.info(`searching for ${searchTerm}`);
const unsplashUrl = await unsplash.getImageBySearchTerm(searchTerm);
return unsplashUrl;
} catch (e) {
log.error("Failed to get unsplash cover image", e);
return undefined;
}
}
function ext(str: string) {
try {
const u = new URL(str);
if (u.searchParams.has("fm")) {
return u.searchParams.get("fm")!;
}
return fileExtension(u.pathname);
} catch (_e) {
return fileExtension(str);
}
}
async function fetchAndStoreCover(
imageUrl: string | undefined,
title: string,
streamResponse?: ReturnType<typeof createStreamResponse>,
): Promise<string | undefined> {
if (!imageUrl) return;
const imagePath = `articles/images/${safeFileName(title)}_cover.${
ext(imageUrl)
}`;
try {
streamResponse?.info("downloading image");
const res = await fetch(imageUrl);
streamResponse?.info("saving image");
if (!res.ok) {
console.log(`Failed to download remote image: ${imageUrl}`, res.status);
return;
}
const buffer = await res.arrayBuffer();
await createResource(imagePath, buffer);
return `resources/${imagePath}`;
} catch (err) {
console.log(`Failed to save image: ${imageUrl}`, err);
return;
}
}
async function processCreateArticle( async function processCreateArticle(
{ fetchUrl, streamResponse }: { { fetchUrl, streamResponse }: {
fetchUrl: string; fetchUrl: string;
@@ -24,36 +83,48 @@ async function processCreateArticle(
) { ) {
log.info("create article from url", { url: fetchUrl }); log.info("create article from url", { url: fetchUrl });
streamResponse.enqueue("downloading article"); streamResponse.info("downloading article");
const doc = await webScrape(fetchUrl, streamResponse); const result = await webScrape(fetchUrl, streamResponse);
const result = await Defuddle(doc, fetchUrl, { log.debug("downloaded and parse parsed", result);
markdown: true,
});
log.debug("downloaded and parse parsed", { streamResponse.info("parsed article, creating tags with openai");
url: fetchUrl,
content: result.content,
});
streamResponse.enqueue("parsed article, creating tags with openai"); const aiMeta = await openai.extractArticleMetadata(result.markdown);
const aiMeta = await openai.extractArticleMetadata(result.content); streamResponse.info("postprocessing article");
streamResponse.enqueue("postprocessing article");
const title = result?.title || aiMeta?.headline || ""; const title = result?.title || aiMeta?.headline || "";
const id = toUrlSafeString(title);
let coverImagePath: string | undefined = undefined;
if (result?.image?.length) {
log.debug("using local image for cover image", { image: result.image });
coverImagePath = await fetchAndStoreCover(
result.image,
title,
streamResponse,
);
} else {
const urlPath = await getUnsplashCoverImage(
result.markdown,
streamResponse,
);
coverImagePath = await fetchAndStoreCover(urlPath, title, streamResponse);
log.debug("using unsplash for cover image", { image: coverImagePath });
}
const url = toUrlSafeString(title);
const newArticle: ArticleResource["content"] = { const newArticle: ArticleResource["content"] = {
_type: "Article", _type: "Article",
headline: title, headline: title,
articleBody: result.content, articleBody: result.markdown,
url: fetchUrl, url: fetchUrl,
datePublished: result?.published || aiMeta?.datePublished || datePublished: formatDate(
new Date().toISOString(), result?.published || aiMeta?.datePublished || undefined,
image: result?.image, ),
image: coverImagePath,
author: { author: {
_type: "Person", _type: "Person",
name: (result.schemaOrgData?.author?.name || aiMeta?.author || "") name: (result.schemaOrgData?.author?.name || aiMeta?.author || "")
@@ -64,11 +135,16 @@ async function processCreateArticle(
}, },
} as const; } as const;
streamResponse.enqueue("writing to disk"); streamResponse.info("writing to disk");
await createResource(`articles/${id}.md`, newArticle); log.debug("writing to disk", {
...newArticle,
articleBody: newArticle.articleBody?.slice(0, 200),
});
streamResponse.enqueue("id: " + id); await createResource(`articles/${url}.md`, newArticle);
streamResponse.send({ type: "finished", url });
} }
async function processCreateYoutubeVideo( async function processCreateYoutubeVideo(
@@ -81,36 +157,48 @@ async function processCreateYoutubeVideo(
url: fetchUrl, url: fetchUrl,
}); });
streamResponse.enqueue("getting video infos from youtube api"); streamResponse.info("getting video infos from youtube api");
const youtubeId = extractYoutubeId(fetchUrl); const youtubeId = extractYoutubeId(fetchUrl);
const video = await getYoutubeVideoDetails(youtubeId); const video = await getYoutubeVideoDetails(youtubeId);
streamResponse.enqueue("shortening title with openai"); streamResponse.info("shortening title with openai");
const newId = await openai.shortenTitle(video.snippet.title); const videoTitle = await openai.shortenTitle(video.snippet.title) ||
video.snippet.title;
const id = newId || youtubeId; const thumbnail = video?.snippet?.thumbnails?.maxres;
const coverImagePath = await fetchAndStoreCover(
thumbnail.url,
videoTitle || video.snippet.title,
streamResponse,
);
const newArticle: ArticleResource["content"] = { const newArticle: ArticleResource["content"] = {
_type: "Article", _type: "Article",
headline: video.snippet.title, headline: video.snippet.title,
articleBody: video.snippet.description, articleBody: video.snippet.description,
image: coverImagePath,
url: fetchUrl, url: fetchUrl,
datePublished: new Date(video.snippet.publishedAt).toISOString(), datePublished: formatDate(video.snippet.publishedAt),
author: { author: {
_type: "Person", _type: "Person",
name: video.snippet.channelTitle, name: video.snippet.channelTitle,
}, },
}; };
streamResponse.enqueue("creating article"); streamResponse.info("creating article");
await createResource(`articles/${id}.md`, newArticle); const filename = toUrlSafeString(videoTitle);
streamResponse.enqueue("finished"); await createResource(
`articles/${filename}.md`,
newArticle,
);
streamResponse.enqueue("id: " + id); streamResponse.info("finished");
streamResponse.send({ type: "finished", url: filename });
} }
export const handler: Handlers = { export const handler: Handlers = {

View File

@@ -0,0 +1,191 @@
import { FreshContext, Handlers } from "$fresh/server.ts";
import { fileExtension } from "https://deno.land/x/file_extension@v2.1.0/mod.ts";
import { formatDate, safeFileName } from "@lib/string.ts";
import { createStreamResponse } from "@lib/helpers.ts";
import {
AccessDeniedError,
BadRequestError,
NotFoundError,
} from "@lib/errors.ts";
import { createResource, fetchResource } from "@lib/marka/index.ts";
import { ArticleResource } from "@lib/marka/schema.ts";
import { webScrape } from "@lib/webScraper.ts";
import * as openai from "@lib/openai.ts";
import * as unsplash from "@lib/unsplash.ts";
import { createLogger } from "@lib/log/index.ts";
function ext(str: string) {
try {
const u = new URL(str);
if (u.searchParams.has("fm")) {
return u.searchParams.get("fm")!;
}
return fileExtension(u.pathname);
} catch (_e) {
return fileExtension(str);
}
}
const log = createLogger("api/article/enhance");
async function getUnsplashCoverImage(
content: string,
streamResponse: ReturnType<typeof createStreamResponse>,
): Promise<string | undefined> {
try {
streamResponse.info("creating unsplash search term");
const searchTerm = await openai.createUnsplashSearchTerm(content);
if (!searchTerm) return;
streamResponse.info(`searching for ${searchTerm}`);
const unsplashUrl = await unsplash.getImageBySearchTerm(searchTerm);
return unsplashUrl;
} catch (e) {
log.error("Failed to get unsplash cover image", e);
return undefined;
}
}
async function fetchAndStoreCover(
imageUrl: string | undefined,
title: string,
streamResponse: ReturnType<typeof createStreamResponse>,
): Promise<string | undefined> {
if (!imageUrl) return;
const imagePath = `articles/images/${safeFileName(title)}_cover.${
ext(imageUrl)
}`;
try {
streamResponse.info("downloading cover");
const res = await fetch(imageUrl);
if (!res.ok) {
log.error(`Failed to download remote image: ${imageUrl}`, {
status: res.status,
});
return;
}
const buffer = await res.arrayBuffer();
streamResponse.info("saving cover");
await createResource(imagePath, buffer);
return `resources/${imagePath}`;
} catch (err) {
log.error(`Failed to save image: ${imageUrl}`, err);
return;
}
}
async function processEnhanceArticle(
name: string,
streamResponse: ReturnType<typeof createStreamResponse>,
) {
const article = await fetchResource<ArticleResource>(
`articles/${name}`,
);
if (!article) {
throw new NotFoundError();
}
const fetchUrl = article.content?.url;
if (!fetchUrl) {
throw new BadRequestError("Article has no URL to enhance from.");
}
log.info("enhancing article from url", { url: fetchUrl });
streamResponse.info("scraping url");
const result = await webScrape(fetchUrl, streamResponse);
streamResponse.info("parsing content");
log.debug("downloaded and parsed", result);
streamResponse.info("extracting metadata with openai");
const aiMeta = await openai.extractArticleMetadata(result.markdown);
const title = result?.title || aiMeta?.headline ||
article.content?.headline || "";
article.content ??= {
_type: "Article",
headline: title,
url: fetchUrl,
};
article.content.articleBody = result.markdown;
article.content.datePublished ??= formatDate(
result?.published || aiMeta?.datePublished || undefined,
);
if (!article.content.author?.name || article.content.author.name === "") {
article.content.author = {
_type: "Person",
name: (result.schemaOrgData?.author?.name || aiMeta?.author || "")
.replace(
"@",
"twitter:",
),
};
}
if (!article.content.image) {
let coverImagePath: string | undefined = undefined;
if (result?.image?.length) {
log.debug("using local image for cover image", { image: result.image });
coverImagePath = await fetchAndStoreCover(
result.image,
title,
streamResponse,
);
} else {
const urlPath = await getUnsplashCoverImage(
result.content,
streamResponse,
);
coverImagePath = await fetchAndStoreCover(urlPath, title, streamResponse);
log.debug("using unsplash for cover image", { image: coverImagePath });
}
if (coverImagePath) {
article.content.image = coverImagePath;
}
}
log.debug("writing to disk", {
name: name,
article: {
...article,
content: {
...article.content,
articleBody: article.content.articleBody?.slice(0, 200),
},
},
});
streamResponse.info("writing to disk");
await createResource(`articles/${name}`, article.content);
streamResponse.send({ type: "finished", url: name.replace(/$\.md/, "") });
}
const POST = (
_req: Request,
ctx: FreshContext,
): Response => {
const session = ctx.state.session;
if (!session) {
throw new AccessDeniedError();
}
const streamResponse = createStreamResponse();
processEnhanceArticle(ctx.params.name, streamResponse)
.catch((err) => {
log.error(err);
streamResponse.error(err.message);
})
.finally(() => {
streamResponse.cancel();
});
return streamResponse.response;
};
export const handler: Handlers = {
POST,
};

View File

@@ -2,7 +2,7 @@ import { Handlers } from "$fresh/server.ts";
import { json } from "@lib/helpers.ts"; import { json } from "@lib/helpers.ts";
export const handler: Handlers = { export const handler: Handlers = {
async GET() { GET() {
return json([]); return json([]);
}, },
}; };

View File

@@ -2,8 +2,13 @@ import { Handlers } from "$fresh/server.ts";
import { json } from "@lib/helpers.ts"; import { json } from "@lib/helpers.ts";
import * as tmdb from "@lib/tmdb.ts"; import * as tmdb from "@lib/tmdb.ts";
import { fileExtension } from "https://deno.land/x/file_extension@v2.1.0/mod.ts"; import { fileExtension } from "https://deno.land/x/file_extension@v2.1.0/mod.ts";
import { isString, safeFileName } from "@lib/string.ts"; import {
import { AccessDeniedError } from "@lib/errors.ts"; formatDate,
isString,
safeFileName,
toUrlSafeString,
} from "@lib/string.ts";
import { AccessDeniedError, BadRequestError } from "@lib/errors.ts";
import { createResource, fetchResource } from "@lib/marka/index.ts"; import { createResource, fetchResource } from "@lib/marka/index.ts";
import { ReviewResource } from "@lib/marka/schema.ts"; import { ReviewResource } from "@lib/marka/schema.ts";
@@ -14,26 +19,22 @@ export const handler: Handlers = {
}, },
async POST(_, ctx) { async POST(_, ctx) {
const session = ctx.state.session; const session = ctx.state.session;
if (!session) { if (!session) throw new AccessDeniedError();
throw new AccessDeniedError();
}
const tmdbId = parseInt(ctx.params.name); const tmdbId = parseInt(ctx.params.name);
if (Number.isNaN(tmdbId)) throw new BadRequestError();
const movieDetails = await tmdb.getMovie(tmdbId); const [movieDetails, movieCredits] = await Promise.all([
const movieCredits = await tmdb.getMovieCredits(tmdbId); tmdb.getMovie(tmdbId),
tmdb.getMovieCredits(tmdbId),
]);
const releaseDate = movieDetails.release_date; const name = movieDetails.title ||
const posterPath = movieDetails.poster_path; movieDetails.original_title ||
const director = movieCredits?.crew?.filter?.((person) =>
person.job === "Director"
)[0];
movieDetails.overview;
let finalPath = "";
const name = movieDetails.title || movieDetails.original_title ||
ctx.params.name; ctx.params.name;
const posterPath = movieDetails.poster_path;
let finalPath = "";
if (posterPath) { if (posterPath) {
const poster = await tmdb.getMoviePoster(posterPath); const poster = await tmdb.getMoviePoster(posterPath);
const extension = fileExtension(posterPath); const extension = fileExtension(posterPath);
@@ -41,33 +42,32 @@ export const handler: Handlers = {
await createResource(finalPath, poster); await createResource(finalPath, poster);
} }
const tags: string[] = []; const keywords = movieDetails.genres
if (movieDetails.genres) { ?.map((g) => g.name?.toLowerCase())
tags.push( .filter(isString) || [];
...movieDetails.genres.map((g) => g.name?.toLowerCase()).filter(
isString,
),
);
}
const movie: ReviewResource["content"] = { const movie: ReviewResource["content"] = {
_type: "Review", _type: "Review",
image: `resources/${finalPath}`, image: `resources/${finalPath}`,
datePublished: releaseDate, datePublished: formatDate(movieDetails.release_date),
tmdbId, tmdbId,
author: { author: {
_type: "Person", _type: "Person",
name: director?.name, name: movieCredits.crew?.filter?.((person) =>
person.job === "Director"
)[0]?.name,
}, },
itemReviewed: { itemReviewed: {
name: name, name,
}, },
reviewBody: "", reviewBody: "",
keywords: tags, keywords,
}; };
await createResource(`movies/${safeFileName(name)}.md`, movie); const fileName = toUrlSafeString(name);
return json(movie); await createResource(`movies/${fileName}.md`, movie);
return json({ name: fileName });
}, },
}; };

View File

@@ -1,7 +1,12 @@
import { FreshContext, Handlers } from "$fresh/server.ts"; import { FreshContext, Handlers } from "$fresh/server.ts";
import { fileExtension } from "https://deno.land/x/file_extension@v2.1.0/mod.ts"; import { fileExtension } from "https://deno.land/x/file_extension@v2.1.0/mod.ts";
import * as tmdb from "@lib/tmdb.ts"; import * as tmdb from "@lib/tmdb.ts";
import { formatDate, isString, safeFileName } from "@lib/string.ts"; import {
formatDate,
isString,
safeFileName,
toUrlSafeString,
} from "@lib/string.ts";
import { json } from "@lib/helpers.ts"; import { json } from "@lib/helpers.ts";
import { import {
AccessDeniedError, AccessDeniedError,
@@ -39,15 +44,16 @@ const POST = async (
const movieCredits = !movie.content?.author && const movieCredits = !movie.content?.author &&
await tmdb.getMovieCredits(tmdbId); await tmdb.getMovieCredits(tmdbId);
const releaseDate = movieDetails.release_date;
if (releaseDate && !movie.content?.datePublished) {
movie.content = movie.content || {};
movie.content.datePublished = formatDate(new Date(releaseDate));
}
const director = movieCredits && const director = movieCredits &&
movieCredits?.crew?.filter?.((person) => person.job === "Director")[0]; movieCredits?.crew?.filter?.((person) => person.job === "Director")[0];
movie.content ??= {
_type: "Review",
};
movie.content.datePublished ??= formatDate(movieDetails.release_date);
if (director && !movie.content?.author) { if (director && !movie.content?.author) {
movie.content = movie.content || {};
movie.content.author = { movie.content.author = {
_type: "Person", _type: "Person",
name: director.name, name: director.name,
@@ -65,22 +71,19 @@ const POST = async (
]; ];
} }
if (!movie.name) { movie.content.tmdbId ??= tmdbId;
movie.name = tmdbId;
}
let finalPath = ""; let finalPath = "";
const posterPath = movieDetails.poster_path; const posterPath = movieDetails.poster_path;
if (posterPath && !movie.content?.image) { if (posterPath && !movie.content.image) {
const poster = await tmdb.getMoviePoster(posterPath); const poster = await tmdb.getMoviePoster(posterPath);
const extension = fileExtension(posterPath); const extension = fileExtension(posterPath);
finalPath = `movies/images/${safeFileName(name)}_cover.${extension}`; finalPath = `movies/images/${safeFileName(name)}_cover.${extension}`;
await createResource(finalPath, poster); await createResource(finalPath, poster);
movie.content = movie.content || {};
movie.content.image = finalPath; movie.content.image = finalPath;
} }
await createResource(`movies/${safeFileName(movie.name)}.md`, movie); await createResource(`movies/${toUrlSafeString(movie.name)}.md`, movie);
createRecommendationResource(movie, movieDetails.overview); createRecommendationResource(movie, movieDetails.overview);

View File

@@ -1,7 +1,7 @@
import { Handlers } from "$fresh/server.ts"; import { Handlers } from "$fresh/server.ts";
import { json } from "@lib/helpers.ts"; import { json } from "@lib/helpers.ts";
import { AccessDeniedError } from "@lib/errors.ts"; import { AccessDeniedError, BadRequestError } from "@lib/errors.ts";
import { searchResource } from "@lib/search.ts"; import { parseResourceUrl, searchResource } from "@lib/search.ts";
export const handler: Handlers = { export const handler: Handlers = {
async GET(req, ctx) { async GET(req, ctx) {
@@ -10,18 +10,13 @@ export const handler: Handlers = {
throw new AccessDeniedError(); throw new AccessDeniedError();
} }
const url = new URL(req.url); const s = parseResourceUrl(req.url);
if (!s) {
throw new BadRequestError();
}
const types = url.searchParams.get("types")?.split(","); console.log(s);
const tags = url.searchParams?.get("tags")?.split(","); const resources = await searchResource(s);
const authors = url.searchParams?.get("authors")?.split(",");
const resources = await searchResource({
q: url.searchParams.get("q") || "",
types,
tags,
authors,
});
return json(resources); return json(resources);
}, },

View File

@@ -5,12 +5,11 @@ import * as openai from "@lib/openai.ts";
import { createLogger } from "@lib/log/index.ts"; import { createLogger } from "@lib/log/index.ts";
import recipeSchema from "@lib/recipeSchema.ts"; import recipeSchema from "@lib/recipeSchema.ts";
import { fileExtension } from "https://deno.land/x/file_extension@v2.1.0/mod.ts"; import { fileExtension } from "https://deno.land/x/file_extension@v2.1.0/mod.ts";
import { safeFileName } from "@lib/string.ts"; import { safeFileName, toUrlSafeString } from "@lib/string.ts";
import { parseJsonLdToRecipeSchema } from "./parseJsonLd.ts"; import { parseJsonLdToRecipeSchema } from "./parseJsonLd.ts";
import z from "zod"; import z from "zod";
import { createResource } from "@lib/marka/index.ts"; import { createResource } from "@lib/marka/index.ts";
import { webScrape } from "@lib/webScraper.ts"; import { webScrape } from "@lib/webScraper.ts";
import { Defuddle } from "defuddle/node";
import { RecipeResource } from "@lib/marka/schema.ts"; import { RecipeResource } from "@lib/marka/schema.ts";
const log = createLogger("api/article"); const log = createLogger("api/article");
@@ -23,18 +22,14 @@ async function processCreateRecipeFromUrl(
) { ) {
log.info("create article from url", { url: fetchUrl }); log.info("create article from url", { url: fetchUrl });
streamResponse.enqueue("downloading article"); streamResponse.info("downloading article");
const doc = await webScrape(fetchUrl, streamResponse); const result = await webScrape(fetchUrl, streamResponse);
const result = await Defuddle(doc, fetchUrl, { streamResponse.info("download success");
markdown: true,
});
streamResponse.enqueue("download success");
const jsonLds = Array.from( const jsonLds = Array.from(
doc?.querySelectorAll( result.dom?.querySelectorAll(
"script[type='application/ld+json']", "script[type='application/ld+json']",
), ),
) as unknown as HTMLScriptElement[]; ) as unknown as HTMLScriptElement[];
@@ -42,26 +37,26 @@ async function processCreateRecipeFromUrl(
let recipe: z.infer<typeof recipeSchema> | undefined = undefined; let recipe: z.infer<typeof recipeSchema> | undefined = undefined;
if (jsonLds.length > 0) { if (jsonLds.length > 0) {
for (const jsonLd of jsonLds) { for (const jsonLd of jsonLds) {
recipe = parseJsonLdToRecipeSchema(jsonLd.textContent || ""); if (jsonLd.textContent) {
if (recipe) break; recipe = parseJsonLdToRecipeSchema(jsonLd.textContent);
if (recipe) break;
}
} }
} }
if (!recipe) { if (!recipe) {
const res = await openai.extractRecipe(result.content); const res = await openai.extractRecipe(result.markdown);
if (!res || "errorMessages" in res) { if (!res || res === "none") {
const errorMessage = res?.errorMessages?.[0] || streamResponse.error(`failed to extract recipe: ${res}`);
"could not extract recipe";
streamResponse.enqueue(`failed to extract recipe: ${errorMessage}`);
return; return;
} }
recipe = res; recipe = res;
} }
const id = safeFileName(recipe?.name || ""); const id = toUrlSafeString(recipe?.name || "");
if (!recipe) { if (!recipe) {
streamResponse.enqueue("failed to parse recipe"); streamResponse.error("failed to parse recipe");
streamResponse.cancel(); streamResponse.cancel();
return; return;
} }
@@ -76,28 +71,26 @@ async function processCreateRecipeFromUrl(
}; };
if (newRecipe?.image && newRecipe.image.length > 5) { if (newRecipe?.image && newRecipe.image.length > 5) {
const extension = fileExtension(new URL(newRecipe.image).pathname); const extension = fileExtension(newRecipe.image);
const finalPath = `resources/recipes/images/${ const finalPath = `recipes/images/${safeFileName(id)}_cover.${extension}`;
safeFileName(id) streamResponse.info("downloading image");
}_cover.${extension}`;
streamResponse.enqueue("downloading image");
try { try {
streamResponse.enqueue("downloading image"); streamResponse.info("downloading image");
const res = await fetch(newRecipe.image); const res = await fetch(newRecipe.image);
streamResponse.enqueue("saving image"); streamResponse.info("saving image");
const buffer = await res.arrayBuffer(); const buffer = await res.arrayBuffer();
await createResource(finalPath, buffer); await createResource(finalPath, buffer);
newRecipe.image = finalPath; newRecipe.image = `resources/${finalPath}`;
} catch (err) { } catch (err) {
console.log("Failed to save image", err); console.log("Failed to save image", err);
} }
} }
streamResponse.enqueue("finished processing, creating file"); streamResponse.info("finished processing, creating file");
await createResource(`recipes/${id}.md`, newRecipe); await createResource(`recipes/${id}.md`, newRecipe);
streamResponse.enqueue("id: " + id); streamResponse.send({ type: "finished", url: id });
} }
export const handler: Handlers = { export const handler: Handlers = {
@@ -119,7 +112,7 @@ export const handler: Handlers = {
processCreateRecipeFromUrl({ fetchUrl, streamResponse }).then((article) => { processCreateRecipeFromUrl({ fetchUrl, streamResponse }).then((article) => {
log.debug("created article from link", { article }); log.debug("created article from link", { article });
}).catch((err) => { }).catch((err) => {
streamResponse.enqueue(`error creating recipe: ${err}`); streamResponse.error(`creating recipe: ${err}`);
log.error(err); log.error(err);
}).finally(() => { }).finally(() => {
streamResponse.cancel(); streamResponse.cancel();

View File

@@ -1,5 +1,4 @@
import recipeSchema from "@lib/recipeSchema.ts"; import recipeSchema, { Recipe } from "@lib/recipeSchema.ts";
import { parseIngredients } from "@lib/parseIngredient.ts";
export function parseJsonLdToRecipeSchema(jsonLdContent: string) { export function parseJsonLdToRecipeSchema(jsonLdContent: string) {
try { try {
@@ -19,12 +18,7 @@ export function parseJsonLdToRecipeSchema(jsonLdContent: string) {
return; return;
} }
// Map and parse ingredients into the new schema const recipeInstructions = Array.isArray(data.recipeInstructions)
const ingredients = parseIngredients(
data?.recipeIngredient?.join("\n") || "",
);
const instructions = Array.isArray(data.recipeInstructions)
? data.recipeInstructions.map((instr: unknown) => { ? data.recipeInstructions.map((instr: unknown) => {
if (!instr) return ""; if (!instr) return "";
if (typeof instr === "string") return instr; if (typeof instr === "string") return instr;
@@ -36,43 +30,41 @@ export function parseJsonLdToRecipeSchema(jsonLdContent: string) {
: []; : [];
// Parse servings // Parse servings
const servings = parseServings(data.recipeYield); const recipeYield = parseServings(data.recipeYield);
// Parse times // Parse times
const prepTime = parseDuration(data.prepTime);
const cookTime = parseDuration(data.cookTime);
const totalTime = parseDuration(data.totalTime); const totalTime = parseDuration(data.totalTime);
// Extract tags // Extract tags
const tags = data.keywords const keywords = data.keywords
? Array.isArray(data.keywords) ? Array.isArray(data.keywords)
? data.keywords ? data.keywords
: data.keywords.split(",").map((tag: string) => tag.trim()) : data.keywords.split(",").map((tag: string) => tag.trim())
: []; : [];
// Build the recipe object // Build the recipe object
const recipe = { const recipe: Recipe = {
_type: "Recipe", _type: "Recipe",
title: data.name || "Unnamed Recipe", name: data.name || "Unnamed Recipe",
image: pickImage(image || data.image || ""), image: pickImage(image || data.image || ""),
author: Array.isArray(data.author) author: {
? data.author.map((a: { name: string }) => a.name).join(", ") "_type": "Person",
: data.author?.name || "", name: Array.isArray(data.author)
? data.author.map((a: { name: string }) => a.name).join(", ")
: data.author?.name || "",
},
description: data.description || "", description: data.description || "",
ingredients, recipeIngredient: data.recipeIngredient,
instructions, recipeInstructions,
servings, recipeYield,
prepTime,
cookTime,
totalTime, totalTime,
tags, keywords,
notes: data.notes || [],
}; };
// Validate against the schema // Validate against the schema
return recipeSchema.parse(recipe); return recipeSchema.parse(recipe);
} catch (error) { } catch (error) {
console.error("Invalid JSON-LD content or parsing error:", error); console.log("Invalid JSON-LD content or parsing error:", error);
return undefined; return undefined;
} }
} }

View File

@@ -21,7 +21,7 @@ async function processUpdateRecommendations(
return true; return true;
}) as ReviewResource[]; }) as ReviewResource[];
streamResponse.enqueue("Fetched all movies"); streamResponse.info("fetched all movies");
let done = 0; let done = 0;
const total = movies.length; const total = movies.length;
@@ -41,7 +41,7 @@ async function processUpdateRecommendations(
console.log(err); console.log(err);
} }
done++; done++;
streamResponse.enqueue( streamResponse.info(
`${Math.floor((done / total) * 100)}% [${ `${Math.floor((done / total) * 100)}% [${
done + 1 done + 1
}/${total}] ${movie.name}`, }/${total}] ${movie.name}`,
@@ -50,7 +50,7 @@ async function processUpdateRecommendations(
console.log(err); console.log(err);
}); });
streamResponse.enqueue("100% Finished"); streamResponse.info("100% Finished");
} }
export const handler: Handlers = { export const handler: Handlers = {

View File

@@ -2,10 +2,19 @@ import { Handlers } from "$fresh/server.ts";
import { json } from "@lib/helpers.ts"; import { json } from "@lib/helpers.ts";
import * as tmdb from "@lib/tmdb.ts"; import * as tmdb from "@lib/tmdb.ts";
import { fileExtension } from "https://deno.land/x/file_extension@v2.1.0/mod.ts"; import { fileExtension } from "https://deno.land/x/file_extension@v2.1.0/mod.ts";
import { isString, safeFileName } from "@lib/string.ts"; import { formatDate, isString, safeFileName } from "@lib/string.ts";
import { AccessDeniedError } from "@lib/errors.ts"; import { AccessDeniedError, BadRequestError } from "@lib/errors.ts";
import { createResource, fetchResource } from "@lib/marka/index.ts"; import { createResource, fetchResource } from "@lib/marka/index.ts";
import { ReviewResource } from "@lib/marka/schema.ts"; import { ReviewResource } from "@lib/marka/schema.ts";
import { toUrlSafeString } from "@lib/string.ts";
function pickDirector(
credits: Awaited<ReturnType<typeof tmdb.getSeriesCredits>>,
createdBy?: { name?: string }[],
): string | undefined {
const crewDirector = credits?.crew?.find?.((p) => p.job === "Director");
return crewDirector?.name ?? createdBy?.[0]?.name;
}
export const handler: Handlers = { export const handler: Handlers = {
async GET(_, ctx) { async GET(_, ctx) {
@@ -19,54 +28,54 @@ export const handler: Handlers = {
} }
const tmdbId = parseInt(ctx.params.name); const tmdbId = parseInt(ctx.params.name);
if (Number.isNaN(tmdbId)) throw new BadRequestError();
const seriesDetails = await tmdb.getSeries(tmdbId); const [seriesDetails, seriesCredits] = await Promise.all([
const seriesCredits = await tmdb.getSeriesCredits(tmdbId); tmdb.getSeries(tmdbId),
tmdb.getSeriesCredits(tmdbId),
]);
const releaseDate = seriesDetails.first_air_date; const name = seriesDetails.name ||
const posterPath = seriesDetails.poster_path; seriesDetails.original_name ||
const director = ctx.params.name;
seriesCredits?.crew?.filter?.((person) => person.job === "Director")[0] ||
seriesDetails.created_by?.[0];
let finalPath = ""; let finalPath = "";
const name = seriesDetails.name || seriesDetails.original_name || const posterPath = seriesDetails.poster_path;
ctx.params.name;
if (posterPath) { if (posterPath) {
const poster = await tmdb.getMoviePoster(posterPath); const poster = await tmdb.getMoviePoster(posterPath);
const extension = fileExtension(posterPath); const extension = fileExtension(posterPath);
const imagePath = `series/images/${
finalPath = `series/images/${safeFileName(name)}_cover.${extension}`; safeFileName(name)
await createResource(finalPath, poster); }_cover.${extension}`;
await createResource(imagePath, poster);
finalPath = imagePath;
} }
const tags: string[] = []; const keywords = seriesDetails.genres
if (seriesDetails.genres) { ?.map((g) => g.name?.toLowerCase())
tags.push( .filter(isString) ??
...seriesDetails.genres.map((g) => g.name?.toLowerCase()).filter( [];
isString,
),
);
}
const series: ReviewResource["content"] = { const series: ReviewResource["content"] = {
_type: "Review", _type: "Review",
image: `resources/${finalPath}`, image: `resources/${finalPath}`,
datePublished: releaseDate, datePublished: formatDate(seriesDetails.first_air_date),
tmdbId, tmdbId,
author: { author: {
_type: "Person", _type: "Person",
name: director?.name, name: pickDirector(seriesCredits, seriesDetails?.created_by),
}, },
itemReviewed: { itemReviewed: {
name: name, name: name,
}, },
reviewBody: "", reviewBody: "",
keywords: tags, keywords: keywords,
}; };
await createResource(`series/${safeFileName(name)}.md`, series); const fileName = toUrlSafeString(name);
return json(series); await createResource(`series/${fileName}.md`, series);
return json({ name: fileName });
}, },
}; };

View File

@@ -19,9 +19,9 @@ const GET = async (
throw new BadRequestError(); throw new BadRequestError();
} }
const type = u.searchParams.get("type") || "movie"; const type = u.searchParams.get("type") || "movies";
const res = type === "movie" const res = type === "movies"
? await searchMovie(query) ? await searchMovie(query)
: await searchTVShow(query); : await searchTVShow(query);

View File

@@ -50,7 +50,7 @@ export default function Greet(
context={article} context={article}
> >
<RedirectSearchHandler /> <RedirectSearchHandler />
<KMenu type="main" context={{ type: "article" }} /> <KMenu type="main" context={article} />
<MetaTags resource={article} /> <MetaTags resource={article} />
<PageHero <PageHero

View File

@@ -17,7 +17,7 @@ export const handler: Handlers<
const articles = await listResources<ArticleResource>("articles"); const articles = await listResources<ArticleResource>("articles");
const searchParams = parseResourceUrl(req.url); const searchParams = parseResourceUrl(req.url);
const searchResults = searchParams && const searchResults = searchParams &&
await searchResource({ ...searchParams, types: ["article"] }); await searchResource({ ...searchParams, types: ["articles"] });
return ctx.render({ articles, searchResults }); return ctx.render({ articles, searchResults });
}, },
}; };
@@ -32,7 +32,7 @@ export default function Greet(
<MainLayout <MainLayout
url={props.url} url={props.url}
title="Articles" title="Articles"
context={{ type: "article" }} context={{ type: "articles" }}
searchResults={searchResults} searchResults={searchResults}
> >
<header class="flex gap-4 items-center mb-5 md:hidden"> <header class="flex gap-4 items-center mb-5 md:hidden">
@@ -47,10 +47,11 @@ export default function Greet(
<h3 class="text-2xl text-white font-light">📝 Articles</h3> <h3 class="text-2xl text-white font-light">📝 Articles</h3>
</header> </header>
<RedirectSearchHandler /> <RedirectSearchHandler />
<KMenu type="main" context={{ type: "article" }} /> <KMenu type="main" context={{ type: "articles" }} />
<Grid> <Grid>
{articles?.map((doc) => ( {articles?.map((doc, i) => (
<ResourceCard <ResourceCard
key={doc.name || i}
sublink="articles" sublink="articles"
res={doc} res={doc}
/> />

View File

@@ -12,14 +12,12 @@ export default function Home(props: PageProps) {
<RedirectSearchHandler /> <RedirectSearchHandler />
<KMenu type="main" context={false} /> <KMenu type="main" context={false} />
<MainLayout url={props.url}> <MainLayout url={props.url}>
<h1 class="text-4xl mb-4 mt-3 text-white flex gap-2">
<img src="/favicon.png" class="w-8 h-8 inline" />
Resources
</h1>
<div class="flex flex-wrap items-center gap-4"> <div class="flex flex-wrap items-center gap-4">
{Object.values(resources).filter((v) => v.link !== "/").map((m) => { {Object.values(resources).filter((v) => v.link !== "/").map((m) => {
return ( return (
<Card <Card
splotch
key={m.link}
title={`${m.name}`} title={`${m.name}`}
backgroundSize={80} backgroundSize={80}
image={`${ image={`${

View File

@@ -72,7 +72,7 @@ export default async function Greet(
{movie.name && ( {movie.name && (
<Recommendations <Recommendations
id={movie.name} id={movie.name}
type="movie" type="movies"
/> />
)} )}
<div class="px-8 text-white mt-10"> <div class="px-8 text-white mt-10">

View File

@@ -22,7 +22,7 @@ export default async function MovieIndex(
const allMovies = await listResources<ReviewResource>("movies"); const allMovies = await listResources<ReviewResource>("movies");
const searchParams = parseResourceUrl(props.url); const searchParams = parseResourceUrl(props.url);
const searchResults = searchParams && const searchResults = searchParams &&
await searchResource({ ...searchParams, types: ["movie"] }); await searchResource({ ...searchParams, types: ["movies"] });
const movies = allMovies.sort((a, b) => const movies = allMovies.sort((a, b) =>
sortOptional( sortOptional(
a.content.reviewRating?.ratingValue, a.content.reviewRating?.ratingValue,
@@ -34,11 +34,11 @@ export default async function MovieIndex(
<MainLayout <MainLayout
url={props.url} url={props.url}
title="Movies" title="Movies"
context={{ type: "movie" }} context={{ type: "movies" }}
searchResults={searchResults} searchResults={searchResults}
> >
<RedirectSearchHandler /> <RedirectSearchHandler />
<KMenu type="main" context={{ type: "movie" }} /> <KMenu type="main" context={{ type: "movies" }} />
<header class="flex gap-4 items-center mb-5 md:hidden"> <header class="flex gap-4 items-center mb-5 md:hidden">
<a <a
class="px-4 ml-4 py-2 bg-gray-300 text-gray-800 rounded-lg flex items-center gap-1" class="px-4 ml-4 py-2 bg-gray-300 text-gray-800 rounded-lg flex items-center gap-1"
@@ -52,7 +52,7 @@ export default async function MovieIndex(
</header> </header>
<Grid> <Grid>
{movies?.map((doc, i) => { {movies?.map((doc, i) => {
return <ResourceCard key={i} res={doc} />; return <ResourceCard key={doc.name || i} res={doc} />;
})} })}
</Grid> </Grid>
</MainLayout> </MainLayout>

View File

@@ -16,7 +16,7 @@ export const handler: Handlers<
const recipes = await listResources<RecipeResource>("recipes"); const recipes = await listResources<RecipeResource>("recipes");
const searchParams = parseResourceUrl(req.url); const searchParams = parseResourceUrl(req.url);
const searchResults = searchParams && const searchResults = searchParams &&
await searchResource({ ...searchParams, types: ["recipe"] }); await searchResource({ ...searchParams, types: ["recipes"] });
return ctx.render({ recipes, searchResults }); return ctx.render({ recipes, searchResults });
}, },
}; };
@@ -32,10 +32,10 @@ export default function Greet(
url={props.url} url={props.url}
title="Recipes" title="Recipes"
searchResults={searchResults} searchResults={searchResults}
context={{ type: "recipe" }} context={{ type: "recipes" }}
> >
<RedirectSearchHandler /> <RedirectSearchHandler />
<KMenu type="main" context={{ type: "recipe" }} /> <KMenu type="main" context={{ type: "recipes" }} />
<header class="flex gap-4 items-center mb-2 lg:mb-5 md:hidden"> <header class="flex gap-4 items-center mb-2 lg:mb-5 md:hidden">
<a <a
class="px-4 lg:ml-4 py-2 bg-gray-300 text-gray-800 rounded-lg flex items-center gap-1" class="px-4 lg:ml-4 py-2 bg-gray-300 text-gray-800 rounded-lg flex items-center gap-1"

View File

@@ -9,7 +9,7 @@ import { Star } from "@components/Stars.tsx";
import { MetaTags } from "@components/MetaTags.tsx"; import { MetaTags } from "@components/MetaTags.tsx";
import { parseRating } from "@lib/helpers.ts"; import { parseRating } from "@lib/helpers.ts";
import { fetchResource } from "@lib/marka/index.ts"; import { fetchResource } from "@lib/marka/index.ts";
import { ReviewResource } from "@lib/marka/schema.ts"; import { getNameOfResource, ReviewResource } from "@lib/marka/schema.ts";
export const handler: Handlers<{ serie: ReviewResource; session: unknown }> = { export const handler: Handlers<{ serie: ReviewResource; session: unknown }> = {
async GET(_, ctx) { async GET(_, ctx) {
@@ -61,7 +61,7 @@ export default function Greet(
)} )}
</PageHero.Header> </PageHero.Header>
<PageHero.Footer> <PageHero.Footer>
<PageHero.Title>{serie.name}</PageHero.Title> <PageHero.Title>{serie.content.itemReviewed?.name}</PageHero.Title>
<PageHero.Subline <PageHero.Subline
entries={[ entries={[
author?.name && author?.name &&

View File

@@ -50,7 +50,9 @@ export default function Greet(
</header> </header>
<Grid> <Grid>
{series?.map((doc, i) => { {series?.map((doc, i) => {
return <ResourceCard key={i} sublink="series" res={doc} />; return (
<ResourceCard key={doc.name || i} sublink="series" res={doc} />
);
})} })}
</Grid> </Grid>
</MainLayout> </MainLayout>

Binary file not shown.

After

Width:  |  Height:  |  Size: 162 KiB

BIN
static/emojis/home_icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 190 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 174 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 144 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 185 KiB

File diff suppressed because one or more lines are too long

BIN
static/noise.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

BIN
static/splotch_1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 394 KiB

BIN
static/splotch_2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 407 KiB

BIN
static/splotch_3.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 390 KiB

View File

@@ -229,8 +229,9 @@ function rgbaToDataURL(w, h, rgba) {
function updateThumbhashImages() { function updateThumbhashImages() {
document.querySelectorAll("[data-thumb]").forEach((entry) => { document.querySelectorAll("[data-thumb]").forEach((entry) => {
const hash = entry.getAttribute("data-thumb"); const hash = entry.getAttribute("data-thumb");
if (entry.getAttribute("data-thumb-decoded")) return;
if (!hash) return; if (!hash) return;
entry.setAttribute("data-thumb-decoded", true);
const decodedString = atob(hash); const decodedString = atob(hash);