Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.
TypeScript albumsexif-extractiongeocodinglive-photomotion-photophoto-galleryphoto-sharingwebgl-viewer
feat(open-graph): implement instance-specific Open Graph metadata handling
Ahmet Ömerb5a56f60ee72
diff --git a/app/app.vue b/app/app.vueindex d2a2a4f3..6ad68a3c 100644--- a/app/app.vue+++ b/app/app.vue@@ -55,6 +55,7 @@ const { data, refresh, status } = await useFetch(() => apiEndpoint.value, {})const photos = computed(() => (data.value as Photo[]) || [])+await useInstanceOpenGraph(photos)const { switchToIndex, closeViewer, clearReturnRoute } = useViewerState()const {diff --git a/app/components/OgImage/Home.takumi.vue b/app/components/OgImage/Home.takumi.vueindex ec49a2ce..7cf78bad 100644--- a/app/components/OgImage/Home.takumi.vue+++ b/app/components/OgImage/Home.takumi.vue@@ -3,21 +3,21 @@ const props = defineProps<{appTitle?: stringslogan?: stringauthor?: string+ avatarUrl?: stringphotoCountLabel?: stringphotoCount?: numberthumbnails?: string[]}>()const { $i18n } = useNuxtApp()const title = computed(() => props.appTitle || 'ChronoFrame')-const photoCountLabel = computed(- () =>- props.photoCountLabel ||- $i18n.t(- 'plural.photo',- { count: props.photoCount || 0 },- props.photoCount || 0,- ),+const avatar = computed(+ () => props.avatarUrl || '/web-app-manifest-512x512.png',)+const countLabel = computed(() => {+ if (props.photoCountLabel) return props.photoCountLabel+ if (typeof props.photoCount !== 'number') return ''+ return $i18n.t('plural.photo', { count: props.photoCount }, props.photoCount)+})const covers = computed(() => (props.thumbnails || []).slice(0, 3))</script>@@ -28,6 +28,10 @@ const covers = computed(() => (props.thumbnails || []).slice(0, 3))<span class="og-home__dot" />PHOTOGRAPHY</div><div class="og-home__heading">+ <img+ :src="avatar"+ class="og-home__avatar"+ /><h1 class="og-home__title">{{ title.slice(0, 50) }}</h1>@@ -44,10 +48,17 @@ const covers = computed(() => (props.thumbnails || []).slice(0, 3))class="og-home__author">{{ author.slice(0, 40) }}</span>- <span class="og-home__count">{{ photoCountLabel }}</span>+ <span+ v-if="countLabel"+ class="og-home__count"+ >{{ countLabel }}</span+ ></div></div>- <div class="og-home__gallery">+ <div+ v-if="covers.length"+ class="og-home__gallery"+ ><div class="og-home__frame"><imgv-if="covers[0]"@@ -91,6 +102,15 @@ const covers = computed(() => (props.thumbnails || []).slice(0, 3))</div></div></div>+ <div+ v-else+ class="og-home__mark"+ >+ <img+ :src="avatar"+ class="og-home__mark-image"+ />+ </div></div></template>@@ -99,6 +119,7 @@ const covers = computed(() => (props.thumbnails || []).slice(0, 3))width: 100%;height: 100%;display: flex;+ overflow: hidden;background: #f5f3ee;color: #242c29;font-family: 'Rubik', 'Noto Sans SC', sans-serif;@@ -131,22 +152,29 @@ const covers = computed(() => (props.thumbnails || []).slice(0, 3)).og-home__heading {display: flex;flex-direction: column;- gap: 24px;+ gap: 20px;+}+.og-home__avatar {+ width: 96px;+ height: 96px;+ border-radius: 48px;+ object-fit: cover;+ background: #d8dfd3;}.og-home__title {margin: 0;- font-size: 64px;+ font-size: 56px;font-weight: 700;line-height: 1.12;letter-spacing: -2px;- line-clamp: 3;+ line-clamp: 2;}.og-home__slogan {margin: 0;font-size: 26px;line-height: 1.5;color: #6b746d;- line-clamp: 3;+ line-clamp: 2;}.og-home__footer {display: flex;@@ -186,6 +214,21 @@ const covers = computed(() => (props.thumbnails || []).slice(0, 3))height: 100%;object-fit: cover;}+.og-home__mark {+ width: 560px;+ height: 480px;+ display: flex;+ align-items: center;+ justify-content: center;+ flex-shrink: 0;+}+.og-home__mark-image {+ width: 360px;+ height: 360px;+ border-radius: 180px;+ object-fit: cover;+ background: #d8dfd3;+}.og-home__placeholder {position: relative;display: flex;diff --git a/app/composables/useInstanceOpenGraph.ts b/app/composables/useInstanceOpenGraph.tsnew file mode 100644index 00000000..e85564f2--- /dev/null+++ b/app/composables/useInstanceOpenGraph.ts@@ -0,0 +1,170 @@+import type { ComputedRef } from 'vue'++/**+ * Share metadata for this ChronoFrame instance.+ *+ * The instance name is the share title and the slogan (the line under the+ * title on the homepage) is the description. The generated image uses the+ * instance avatar. Photo pages keep their own title, description, and image.+ */+export async function useInstanceOpenGraph(photos: ComputedRef<Photo[]>) {+ const route = useRoute()+ const nuxtApp = useNuxtApp()+ const requestURL = useRequestURL()+ const { loggedIn } = useUserSession()+ const i18n = useShareI18n()++ const appTitle = useSettingRef('app:title')+ const appSlogan = useSettingRef('app:slogan')+ const appAuthor = useSettingRef('app:author')+ const appAvatar = useSettingRef('app:avatarUrl')++ const siteName = computed(+ () => cleanShareText(appTitle.value, 80) || 'ChronoFrame',+ )+ const slogan = computed(() => cleanShareText(appSlogan.value, 200))+ const author = computed(() => cleanShareText(appAuthor.value, 80))+ const avatarUrl = computed(() => resolveShareAvatar(appAvatar.value))++ const photoId = computed(() => {+ const slug = route.params.slug+ if (Array.isArray(slug)) return slug[0] || null+ if (typeof slug === 'string' && slug.length > 0) return slug+ return null+ })+ const currentPhoto = computed(() =>+ photoId.value+ ? photos.value.find((photo) => photo.id === photoId.value)+ : undefined,+ )+ const isHome = computed(() => route.path === '/')++ // Logged-in visitors load every photo, including hidden ones. The public+ // preview must keep using the anonymous collection.+ const publicPhotoRequest = useFetch<Photo[]>('/api/photos/visible', {+ key: 'og-public-photos',+ immediate: loggedIn.value && isHome.value,+ })+ const { data: publicPhotos, execute: loadPublicPhotos } = publicPhotoRequest++ const previewPhotos = computed(() => {+ if (!isHome.value) return []+ if (loggedIn.value) return publicPhotos.value || []+ return photos.value+ })++ const shareTitle = computed(() => {+ if (!photoId.value) return siteName.value+ return (+ cleanShareText(currentPhoto.value?.title, 80) ||+ translate(i18n, 'title.fallback.photo', 'Photo')+ )+ })+ const shareDescription = computed(() => {+ const instanceDescription = slogan.value || author.value+ if (!photoId.value) return instanceDescription || undefined+ return (+ cleanShareText(currentPhoto.value?.description, 200) ||+ instanceDescription ||+ undefined+ )+ })+ const canonicalUrl = computed(+ () => new URL(route.path, requestURL.origin).href,+ )++ useSeoMeta({+ description: shareDescription,+ ogType: () => (photoId.value ? 'article' : 'website'),+ ogSiteName: siteName,+ ogTitle: shareTitle,+ ogDescription: shareDescription,+ ogUrl: canonicalUrl,+ twitterCard: 'summary_large_image',+ twitterTitle: shareTitle,+ twitterDescription: shareDescription,+ })++ watch([isHome, loggedIn], ([home, authed]) => {+ if (home && authed && !publicPhotos.value) void loadPublicPhotos()+ })++ function updateOgImage() {+ const id = photoId.value+ nuxtApp.runWithContext(() => {+ if (id) {+ defineOgImage(+ 'Photo',+ {+ photo:+ currentPhoto.value?.id === id ? currentPhoto.value : undefined,+ appTitle: siteName.value,+ },+ { alt: shareTitle.value },+ )+ return+ }++ const visiblePhotos = previewPhotos.value+ const count = visiblePhotos.length+ defineOgImage(+ 'Home',+ {+ appTitle: siteName.value,+ slogan: slogan.value,+ author: author.value,+ avatarUrl: avatarUrl.value,+ photoCount: isHome.value ? count : undefined,+ photoCountLabel: isHome.value ? photoCountLabel(i18n, count) : '',+ thumbnails: visiblePhotos+ .map((photo) => photo.thumbnailUrl)+ .filter((url): url is string => Boolean(url))+ .slice(0, 3),+ },+ { alt: siteName.value },+ )+ })+ }++ watch(+ [+ photoId,+ currentPhoto,+ previewPhotos,+ isHome,+ siteName,+ slogan,+ author,+ avatarUrl,+ shareTitle,+ () => i18n?.locale.value,+ ],+ updateOgImage,+ )+ // nuxt-og-image skips client updates during hydration.+ onMounted(updateOgImage)++ await publicPhotoRequest+ updateOgImage()+}++function useShareI18n() {+ try {+ return useI18n()+ } catch {+ return null+ }+}++function translate(+ i18n: ReturnType<typeof useShareI18n>,+ key: string,+ fallback: string,+) {+ return i18n?.t(key) || fallback+}++function photoCountLabel(i18n: ReturnType<typeof useShareI18n>, count: number) {+ if (!i18n) return count === 1 ? '1 photo' : `${count} photos`+ return i18n.t('plural.photo', { count }, count)+}diff --git a/app/pages/[...slug].vue b/app/pages/[...slug].vueindex 6be63d30..165bcdb3 100644--- a/app/pages/[...slug].vue+++ b/app/pages/[...slug].vue@@ -7,7 +7,6 @@ definePageMeta({const route = useRoute()const router = useRouter()-const { t } = useI18n()const { switchToIndex, closeViewer, openViewer } = useViewerState()const { isViewerOpen, scopedPhotos } = storeToRefs(useViewerState())@@ -16,63 +15,6 @@ const { photos } = usePhotos()const slug = computed(() => (route.params.slug as string[]) || [])const photoId = computed(() => slug.value[0] || null)-const currentPhoto = computed(() =>- photos.value.find((photo) => photo.id === photoId.value),-)--const nuxtApp = useNuxtApp()-// This public collection is route-independent; late results must only update-// Home metadata while the current route is still the home page.-const { data: publicPhotos, execute: loadPublicPhotos } = await useFetch<- Photo[]->('/api/photos/visible', { immediate: !photoId.value })-watch(photoId, (id) => {- if (!id && !publicPhotos.value) void loadPublicPhotos()-})--function updateOgImage() {- const id = photoId.value- const appTitle = (getSetting('app:title') as string) || 'ChronoFrame'- nuxtApp.runWithContext(() => {- if (id) {- defineOgImage('Photo', {- photo: currentPhoto.value?.id === id ? currentPhoto.value : undefined,- appTitle,- })- return- }- const visiblePhotos = publicPhotos.value || []- defineOgImage('Home', {- appTitle,- slogan: (getSetting('app:slogan') as string) || '',- author: (getSetting('app:author') as string) || '',- photoCount: visiblePhotos.length,- photoCountLabel: t(- 'plural.photo',- { count: visiblePhotos.length },- visiblePhotos.length,- ),- thumbnails: visiblePhotos- .map((photo) => photo.thumbnailUrl)- .filter((url): url is string => Boolean(url))- .slice(0, 3),- })- })-}-watch(- [- photoId,- currentPhoto,- publicPhotos,- () => route.fullPath,- () => t('plural.photo', 0),- ],- updateOgImage,- { immediate: true },-)-// nuxt-og-image skips client updates during hydration. Reconcile once mounted-// in case the route changed while the initial public-photo request was pending.-onMounted(updateOgImage)// 处理标签查询参数const { clearAllFilters, toggleFilter } = usePhotoFilters()diff --git a/app/utils/open-graph.ts b/app/utils/open-graph.tsnew file mode 100644index 00000000..ad9413e4--- /dev/null+++ b/app/utils/open-graph.ts@@ -0,0 +1,19 @@+const OG_AVATAR_FALLBACK = '/web-app-manifest-512x512.png'++export function cleanShareText(value: unknown, maxLength: number): string {+ if (typeof value !== 'string') return ''+ return value.replace(/\s+/g, ' ').trim().slice(0, maxLength)+}++/**+ * Avatars are rendered inside the generated share image, so only pass URLs the+ * image renderer can fetch: a site-relative path or an absolute http(s) URL.+ */+export function resolveShareAvatar(value: unknown): string {+ if (typeof value !== 'string') return OG_AVATAR_FALLBACK+ const url = value.trim()+ if (!url) return OG_AVATAR_FALLBACK+ if (url.startsWith('/') && !url.startsWith('//')) return url+ if (url.startsWith('https://') || url.startsWith('http://')) return url+ return OG_AVATAR_FALLBACK+}