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(location): 添加地理位置信息支持,城市、国家和坐标提取
Timothy Yin072d139f363f
diff --git a/app/components/DateRangeIndicator.vue b/app/components/DateRangeIndicator.vueindex efa1ee90..5c0f90b2 100644--- a/app/components/DateRangeIndicator.vue+++ b/app/components/DateRangeIndicator.vue@@ -44,7 +44,7 @@ const mobileVariants = {<!-- Desktop Date Range Indicator --><motion.divv-if="shouldShow && !isMobile"- class="fixed top-4 left-4 z-50 lg:top-6 lg:left-6 flex flex-col gap-1 bg-black/40 backdrop-blur-3xl rounded-xl border border-white/10 px-4 py-2 shadow-2xl"+ class="fixed top-4 left-4 z-50 lg:top-6 lg:left-6 flex flex-col gap-1 bg-black/40 backdrop-blur-3xl rounded-xl border border-white/10 px-4 py-2 pb-4 shadow-2xl":initial="dateRangeVariants.initial":animate="dateRangeVariants.animate":exit="dateRangeVariants.initial"@@ -55,7 +55,7 @@ const mobileVariants = {}"><span class="text-white text-4xl font-black leading-normal tracking-wide">{{ dateRange }}</span>- <span v-if="locations" class="text-white/60 text-xl font-bold">{{ locations }}</span>+ <span v-if="locations" class="text-white/80 text-xl font-bold">{{ locations }}</span></motion.div><!-- Mobile Date Range Indicator -->@@ -72,10 +72,10 @@ const mobileVariants = {}"><div- class="bg-black/60 backdrop-blur-3xl border-b border-white/10 px-4 py-2 shadow-2xl"+ class="bg-black/60 backdrop-blur-3xl border-b border-white/10 px-4 py-2 shadow-2xl flex flex-col"><span class="text-white text-lg font-medium">{{ dateRange }}</span>- <span v-if="locations" class="text-white/60 text-xs ml-2">{{ locations }}</span>+ <span v-if="locations" class="text-white/80 text-xs">{{ locations }}</span></div></motion.div></AnimatePresence>diff --git a/app/components/masonry/Root.vue b/app/components/masonry/Root.vueindex 6d5518e2..b3fd1347 100644--- a/app/components/masonry/Root.vue+++ b/app/components/masonry/Root.vue@@ -97,18 +97,41 @@ const handleVisibilityChange = ({updateDateRange()}+const visibleCities = ref<string>()+const updateDateRange = () => {if (visiblePhotos.value.size === 0) {dateRange.value = undefined+ visibleCities.value = undefinedreturn}- const visibleDates = Array.from(visiblePhotos.value)+ const visiblePhotosArray = Array.from(visiblePhotos.value)++ // Calculate visible dates+ const visibleDates = visiblePhotosArray.map((index) => props.photos[index]?.dateTaken).filter((date): date is string => Boolean(date)).map((date) => dayjs(date)).sort((a, b) => (a.isBefore(b) ? -1 : 1))+ // Calculate visible cities+ const cities = visiblePhotosArray+ .map((index) => props.photos[index]?.city)+ .filter((city): city is string => Boolean(city))++ const uniqueCities = [...new Set(cities)]++ if (uniqueCities.length === 0) {+ visibleCities.value = undefined+ } else if (uniqueCities.length === 1) {+ visibleCities.value = uniqueCities[0]+ } else if (uniqueCities.length <= 3) {+ visibleCities.value = uniqueCities.join('、')+ } else {+ visibleCities.value = `${uniqueCities.slice(0, 2).join('、')} 等 ${uniqueCities.length} 个城市`+ }+if (visibleDates.length === 0) {dateRange.value = undefinedreturn@@ -182,6 +205,7 @@ const handleOpenViewer = (index: number) => {<div class="relative w-full"><DateRangeIndicator:date-range="dateRange"+ :locations="visibleCities":is-visible="!!dateRange && showFloatingActions":is-mobile="isMobile"/>diff --git a/app/components/photo/InfoPanel.vue b/app/components/photo/InfoPanel.vueindex 8956b505..327c2126 100644--- a/app/components/photo/InfoPanel.vue+++ b/app/components/photo/InfoPanel.vue@@ -56,6 +56,15 @@ const formatExposureTime = (}const gpsCoordinates = computed(() => {+ // 优先使用数据库中存储的坐标+ if (props.currentPhoto.latitude && props.currentPhoto.longitude) {+ return {+ latitude: props.currentPhoto.latitude,+ longitude: props.currentPhoto.longitude,+ }+ }++ // 如果数据库中没有,尝试从EXIF数据中获取if (!props.exifData) return nullconst { GPSLatitude, GPSLongitude } = props.exifDataif (GPSLatitude && GPSLongitude) {@@ -103,6 +112,27 @@ const formatedExifData = computed<Record<string, KVData[]>>(() => {icon: 'tabler:grid-dots',}: null,+ props.currentPhoto.country+ ? {+ label: '国家',+ value: props.currentPhoto.country,+ icon: 'tabler:map-pin',+ }+ : null,+ props.currentPhoto.city+ ? {+ label: '城市',+ value: props.currentPhoto.city,+ icon: 'tabler:building',+ }+ : null,+ props.currentPhoto.latitude && props.currentPhoto.longitude+ ? {+ label: 'GPS坐标',+ value: `${props.currentPhoto.latitude.toFixed(6)}, ${props.currentPhoto.longitude.toFixed(6)}`,+ icon: 'tabler:gps',+ }+ : null,props.exifData?.Artist? {label: '艺术家',diff --git a/server/api/photos/location-stats.get.ts b/server/api/photos/location-stats.get.tsnew file mode 100644index 00000000..b2c6332f--- /dev/null+++ b/server/api/photos/location-stats.get.ts@@ -0,0 +1,62 @@+import { sql } from 'drizzle-orm'++export default eventHandler(async (event) => {+ await requireUserSession(event)++ try {+ // 获取有地理位置信息的照片总数+ const photosWithLocationResult = await useDB()+ .select({ count: sql<number>`count(*)` })+ .from(tables.photos)+ .where(sql`latitude IS NOT NULL AND longitude IS NOT NULL`)++ const photosWithLocation = photosWithLocationResult[0]?.count || 0++ // 获取总照片数+ const totalPhotosResult = await useDB()+ .select({ count: sql<number>`count(*)` })+ .from(tables.photos)++ const totalPhotos = totalPhotosResult[0]?.count || 0++ // 获取按国家分组的统计+ const countriesResult = await useDB()+ .select({+ country: tables.photos.country,+ count: sql<number>`count(*)`+ })+ .from(tables.photos)+ .where(sql`country IS NOT NULL`)+ .groupBy(tables.photos.country)+ .orderBy(sql`count(*) DESC`)++ // 获取按城市分组的统计+ const citiesResult = await useDB()+ .select({+ city: tables.photos.city,+ country: tables.photos.country,+ count: sql<number>`count(*)`+ })+ .from(tables.photos)+ .where(sql`city IS NOT NULL`)+ .groupBy(tables.photos.city, tables.photos.country)+ .orderBy(sql`count(*) DESC`)+ .limit(20) // 只返回前20个最常见的城市++ return {+ statistics: {+ totalPhotos,+ photosWithLocation,+ locationCoverage: totalPhotos > 0 ? (photosWithLocation / totalPhotos * 100).toFixed(1) : '0',+ },+ countries: countriesResult,+ cities: citiesResult,+ }+ } catch (error) {+ logger.chrono.error('Failed to fetch location statistics:', error)+ throw createError({+ statusCode: 500,+ statusMessage: 'Failed to fetch location statistics',+ })+ }+})diff --git a/server/api/photos/locations.get.ts b/server/api/photos/locations.get.tsnew file mode 100644index 00000000..dfb9a9ea--- /dev/null+++ b/server/api/photos/locations.get.ts@@ -0,0 +1,55 @@+import { eq, and, sql, desc } from 'drizzle-orm'++export default eventHandler(async (event) => {+ await requireUserSession(event)++ const query = getQuery(event)+ const { country, city, hasLocation } = query++ let whereConditions = []++ // 如果指定了只显示有位置信息的照片+ if (hasLocation === 'true') {+ whereConditions.push(sql`latitude IS NOT NULL AND longitude IS NOT NULL`)+ }++ // 如果指定了国家筛选+ if (country && typeof country === 'string') {+ whereConditions.push(eq(tables.photos.country, country))+ }++ // 如果指定了城市筛选+ if (city && typeof city === 'string') {+ whereConditions.push(eq(tables.photos.city, city))+ }++ try {+ const photos = await useDB()+ .select({+ id: tables.photos.id,+ title: tables.photos.title,+ thumbnailUrl: tables.photos.thumbnailUrl,+ dateTaken: tables.photos.dateTaken,+ latitude: tables.photos.latitude,+ longitude: tables.photos.longitude,+ country: tables.photos.country,+ city: tables.photos.city,+ locationName: tables.photos.locationName,+ tags: tables.photos.tags,+ })+ .from(tables.photos)+ .where(whereConditions.length > 0 ? and(...whereConditions) : undefined)+ .orderBy(desc(tables.photos.dateTaken))++ return {+ photos,+ total: photos.length,+ }+ } catch (error) {+ logger.chrono.error('Failed to fetch photos with location:', error)+ throw createError({+ statusCode: 500,+ statusMessage: 'Failed to fetch photos',+ })+ }+})diff --git a/server/database/migrations/0001_narrow_spot.sql b/server/database/migrations/0001_narrow_spot.sqlnew file mode 100644index 00000000..814815be--- /dev/null+++ b/server/database/migrations/0001_narrow_spot.sql@@ -0,0 +1,5 @@+ALTER TABLE `photos` ADD `latitude` real;--> statement-breakpoint+ALTER TABLE `photos` ADD `longitude` real;--> statement-breakpoint+ALTER TABLE `photos` ADD `country` text;--> statement-breakpoint+ALTER TABLE `photos` ADD `city` text;--> statement-breakpoint+ALTER TABLE `photos` ADD `location_name` text;\ No newline at end of filediff --git a/server/database/migrations/meta/0001_snapshot.json b/server/database/migrations/meta/0001_snapshot.jsonnew file mode 100644index 00000000..5efa3c8c--- /dev/null+++ b/server/database/migrations/meta/0001_snapshot.json@@ -0,0 +1,251 @@+{+ "version": "6",+ "dialect": "sqlite",+ "id": "de563135-f904-40ae-aea3-82a77eb2f160",+ "prevId": "5783985a-a690-46a1-941f-c7174b99bd62",+ "tables": {+ "photos": {+ "name": "photos",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "width": {+ "name": "width",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "height": {+ "name": "height",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "aspect_ratio": {+ "name": "aspect_ratio",+ "type": "real",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "date_taken": {+ "name": "date_taken",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "storage_key": {+ "name": "storage_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "file_size": {+ "name": "file_size",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_modified": {+ "name": "last_modified",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "original_url": {+ "name": "original_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "thumbnail_url": {+ "name": "thumbnail_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "thumbnail_hash": {+ "name": "thumbnail_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "tags": {+ "name": "tags",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "exif": {+ "name": "exif",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "latitude": {+ "name": "latitude",+ "type": "real",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "longitude": {+ "name": "longitude",+ "type": "real",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "country": {+ "name": "country",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "city": {+ "name": "city",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "location_name": {+ "name": "location_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "photos_id_unique": {+ "name": "photos_id_unique",+ "columns": [+ "id"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "users": {+ "name": "users",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "password": {+ "name": "password",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "avatar": {+ "name": "avatar",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "is_admin": {+ "name": "is_admin",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ }+ },+ "indexes": {+ "users_name_unique": {+ "name": "users_name_unique",+ "columns": [+ "name"+ ],+ "isUnique": true+ },+ "users_email_unique": {+ "name": "users_email_unique",+ "columns": [+ "email"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ }+ },+ "views": {},+ "enums": {},+ "_meta": {+ "schemas": {},+ "tables": {},+ "columns": {}+ },+ "internal": {+ "indexes": {}+ }+}\ No newline at end of filediff --git a/server/database/migrations/meta/_journal.json b/server/database/migrations/meta/_journal.jsonindex 89812612..27f8baf6 100644--- a/server/database/migrations/meta/_journal.json+++ b/server/database/migrations/meta/_journal.json@@ -8,6 +8,13 @@"when": 1756139400238,"tag": "0000_curvy_scarlet_witch","breakpoints": true+ },+ {+ "idx": 1,+ "version": "6",+ "when": 1756737014171,+ "tag": "0001_narrow_spot",+ "breakpoints": true}]}\ No newline at end of filediff --git a/server/database/schema.ts b/server/database/schema.tsindex 37d9a00d..ab3bb320 100644--- a/server/database/schema.ts+++ b/server/database/schema.ts@@ -26,5 +26,11 @@ export const photos = sqliteTable('photos', {thumbnailUrl: text('thumbnail_url'),thumbnailHash: text('thumbnail_hash'),tags: text('tags', { mode: 'json' }).$type<string[]>(),- exif: text('exif', {mode: 'json'}).$type<NeededExif>()+ exif: text('exif', {mode: 'json'}).$type<NeededExif>(),+ // 地理位置信息+ latitude: real('latitude'),+ longitude: real('longitude'),+ country: text('country'),+ city: text('city'),+ locationName: text('location_name'),})diff --git a/server/services/location/geocoding.ts b/server/services/location/geocoding.tsnew file mode 100644index 00000000..e442ea3e--- /dev/null+++ b/server/services/location/geocoding.ts@@ -0,0 +1,170 @@+import { Logger } from '~~/server/utils/logger'++export interface LocationInfo {+ latitude: number+ longitude: number+ country?: string+ city?: string+ locationName?: string+}++export interface GeocodingProvider {+ reverseGeocode(lat: number, lon: number): Promise<LocationInfo | null>+}++/**+ * OpenStreetMap Nominatim API 地理编码提供者+ * 免费的地理编码服务,适合开发和小规模使用+ */+class NominatimGeocodingProvider implements GeocodingProvider {+ private readonly baseUrl = 'https://nominatim.openstreetmap.org'+ private readonly userAgent = 'chronoframe/1.0'+ private lastRequestTime = 0+ private readonly rateLimitMs = 1000 // Nominatim 要求至少1秒间隔++ async reverseGeocode(lat: number, lon: number): Promise<LocationInfo | null> {+ try {+ // 应用速率限制+ await this.applyRateLimit()++ const url = new URL('/reverse', this.baseUrl)+ url.searchParams.set('lat', lat.toString())+ url.searchParams.set('lon', lon.toString())+ url.searchParams.set('format', 'json')+ url.searchParams.set('addressdetails', '1')+ url.searchParams.set('accept-language', 'zh-CN,zh,en')++ const response = await fetch(url.toString(), {+ headers: {+ 'User-Agent': this.userAgent,+ },+ })++ if (!response.ok) {+ logger.location.warn(`Nominatim API responded with status ${response.status}`)+ return null+ }++ const data = await response.json()++ if (!data || data.error) {+ logger.location.warn('Nominatim API returned error:', data?.error)+ return null+ }++ const address = data.address || {}++ // 提取国家信息+ const country = address.country || address.country_code?.toUpperCase()++ // 提取城市信息(优先级:city > town > village > hamlet)+ const city = address.city ||+ address.town ||+ address.village ||+ address.hamlet ||+ address.county ||+ address.state++ // 构建位置名称+ const locationName = data.display_name++ return {+ latitude: lat,+ longitude: lon,+ country,+ city,+ locationName,+ }+ } catch (error) {+ logger.location.error('Reverse geocoding failed:', error)+ return null+ }+ }++ private async applyRateLimit(): Promise<void> {+ const now = Date.now()+ const timeSinceLastRequest = now - this.lastRequestTime++ if (timeSinceLastRequest < this.rateLimitMs) {+ const delay = this.rateLimitMs - timeSinceLastRequest+ await new Promise(resolve => setTimeout(resolve, delay))+ }++ this.lastRequestTime = Date.now()+ }+}++/**+ * 从GPS坐标中提取地理位置信息+ */+export async function extractLocationFromGPS(+ gpsLatitude?: number,+ gpsLongitude?: number,+ provider: GeocodingProvider = new NominatimGeocodingProvider()+): Promise<LocationInfo | null> {+ if (!gpsLatitude || !gpsLongitude) {+ return null+ }++ // 验证坐标范围+ if (Math.abs(gpsLatitude) > 90 || Math.abs(gpsLongitude) > 180) {+ logger.location.warn(`Invalid GPS coordinates: ${gpsLatitude}, ${gpsLongitude}`)+ return null+ }++ logger.location.info(`Reverse geocoding coordinates: ${gpsLatitude}, ${gpsLongitude}`)++ try {+ const locationInfo = await provider.reverseGeocode(gpsLatitude, gpsLongitude)++ if (locationInfo) {+ logger.location.success(`Location found: ${locationInfo.city}, ${locationInfo.country}`)+ } else {+ logger.location.warn('No location found for coordinates')+ }++ return locationInfo+ } catch (error) {+ logger.location.error('Location extraction failed:', error)+ return null+ }+}++/**+ * 解析EXIF GPS数据为十进制度数+ */+export function parseGPSCoordinates(exifData: any): { latitude?: number; longitude?: number } {+ try {+ let latitude: number | undefined+ let longitude: number | undefined++ // 尝试从GPSLatitude和GPSLongitude获取+ if (exifData.GPSLatitude && exifData.GPSLongitude) {+ latitude = parseFloat(exifData.GPSLatitude.toString())+ longitude = parseFloat(exifData.GPSLongitude.toString())+ }++ // 如果上面的方法失败,尝试从GPSCoordinates获取+ if ((!latitude || !longitude) && exifData.GPSCoordinates) {+ const coords = exifData.GPSCoordinates.toString()+ const match = coords.match(/([-+]?\d+\.?\d*)[°,\s]+([-+]?\d+\.?\d*)/)+ if (match) {+ latitude = parseFloat(match[1])+ longitude = parseFloat(match[2])+ }+ }++ // 应用GPS参考(南纬为负,西经为负)+ if (latitude && exifData.GPSLatitudeRef === 'S') {+ latitude = -Math.abs(latitude)+ }+ if (longitude && exifData.GPSLongitudeRef === 'W') {+ longitude = -Math.abs(longitude)+ }++ return { latitude, longitude }+ } catch (error) {+ logger.location.error('Failed to parse GPS coordinates:', error)+ return {}+ }+}diff --git a/server/services/photo/pipeline-async.ts b/server/services/photo/pipeline-async.tsindex 71622f37..cc3838a2 100644--- a/server/services/photo/pipeline-async.ts+++ b/server/services/photo/pipeline-async.ts@@ -9,6 +9,7 @@ import { getStorageManager } from '~~/server/plugins/storage'import { compressUint8Array } from '~~/shared/utils/u8array'import { StorageObject } from '../storage'import { extractExifData, extractPhotoInfo } from '../image/exif'+import { extractLocationFromGPS, parseGPSCoordinates } from '../location/geocoding'const generatePhotoId = (s3key: string) => {return path.basename(s3key, path.extname(s3key)).replace(/ /g, '_')@@ -110,6 +111,24 @@ async function processPhotoInternal(const photoInfo = extractPhotoInfo(s3key, exifData)+ // 处理地理位置信息+ let locationInfo = null+ if (exifData) {+ const { latitude, longitude } = parseGPSCoordinates(exifData)+ if (latitude && longitude) {+ locationInfo = await new Promise<any>((resolve, reject) => {+ setImmediate(async () => {+ try {+ const result = await extractLocationFromGPS(latitude, longitude)+ resolve(result)+ } catch (error) {+ reject(error)+ }+ })+ })+ }+ }+const thumbnailObject = await new Promise<any>((resolve, reject) => {setImmediate(async () => {try {@@ -142,6 +161,12 @@ async function processPhotoInternal(thumbnailUrl: storageProvider.getPublicUrl(thumbnailObject.key),thumbnailHash: thumbnailHash ? compressUint8Array(thumbnailHash) : null,exif: exifData,+ // 地理位置信息+ latitude: locationInfo?.latitude || null,+ longitude: locationInfo?.longitude || null,+ country: locationInfo?.country || null,+ city: locationInfo?.city || null,+ locationName: locationInfo?.locationName || null,}log.info(`Async processing completed for ${s3key}`)diff --git a/server/utils/logger.ts b/server/utils/logger.tsindex 56c7cc87..7153ae7b 100644--- a/server/utils/logger.ts+++ b/server/utils/logger.ts@@ -13,6 +13,7 @@ export const logger = {storage: mConsola.withTag('STORAGE'),fs: mConsola.withTag('FS'),image: mConsola.withTag('IMG/PHOTO'),+ location: mConsola.withTag('LOCATION'),dynamic: (id: string) => mConsola.withTag(id.toUpperCase()),}