image viewer page, improved gallery tiling, thumbnail generation and caching

This commit is contained in:
wisplite
2025-11-23 21:37:21 -06:00
parent c7d478271d
commit 751a724a4b
10 changed files with 333 additions and 17 deletions
+2 -1
View File
@@ -1,2 +1,3 @@
backend/raster.db
backend/media
backend/media
backend/cache
+3
View File
@@ -8,6 +8,7 @@ require (
github.com/bytedance/sonic/loader v0.2.4 // indirect
github.com/cloudwego/base64x v0.1.5 // indirect
github.com/cloudwego/iasm v0.2.0 // indirect
github.com/disintegration/imaging v1.6.2 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/gabriel-vasile/mimetype v1.4.9 // indirect
github.com/gin-contrib/cors v1.7.6 // indirect
@@ -32,10 +33,12 @@ require (
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.3.0 // indirect
golang.org/x/arch v0.18.0 // indirect
golang.org/x/crypto v0.39.0 // indirect
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8 // indirect
golang.org/x/net v0.41.0 // indirect
golang.org/x/sys v0.33.0 // indirect
golang.org/x/text v0.26.0 // indirect
+7
View File
@@ -16,6 +16,8 @@ github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg=
github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/disintegration/imaging v1.6.2 h1:w1LecBlG2Lnp8B3jk5zSuNqd7b4DXhcjwek1ei82L+c=
github.com/disintegration/imaging v1.6.2/go.mod h1:44/5580QXChDfwIclfc/PCwrr44amcmDAg8hxG0Ewe4=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=
@@ -85,6 +87,8 @@ github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZN
github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd h1:CmH9+J6ZSsIjUK3dcGsnCnO41eRBOnY12zwkn5qVwgc=
github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd/go.mod h1:hPqNNc0+uJM6H+SuU8sEs5K5IQeKccPqeSjfgcKGgPk=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
@@ -111,6 +115,8 @@ golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI=
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
golang.org/x/crypto v0.39.0 h1:SHs+kF4LP+f+p14esP5jAoDpHU8Gu/v9lFRK6IT5imM=
golang.org/x/crypto v0.39.0/go.mod h1:L+Xg3Wf6HoL4Bn4238Z6ft6KfEpN0tJGo53AAPC632U=
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8 h1:hVwzHzIUGRjiF7EcUjqNxk3NCfkPxbDKRdnNE1Rpg0U=
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac=
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
golang.org/x/net v0.41.0 h1:vBTly1HeNPEn3wtREYfy4GZ/NECgw2Cnl+nK6Nz3uvw=
@@ -121,6 +127,7 @@ golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y=
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw=
golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk=
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.20.0 h1:gK/Kv2otX8gz+wn7Rmb3vT96ZwuoxnQlY+HlJVj7Qug=
+50
View File
@@ -4,6 +4,7 @@ import (
"net/http"
"os"
"path/filepath"
"strconv"
"github.com/gin-gonic/gin"
"github.com/wisplite/raster/internal/services"
@@ -103,4 +104,53 @@ func RegisterMediaRoutes(rg *gin.RouterGroup) {
}
c.File(mediaData.Path)
})
media.GET("/thumb/:albumId/:mediaId", func(c *gin.Context) {
albumID := c.Param("albumId")
mediaID := c.Param("mediaId")
widthStr := c.Query("width")
heightStr := c.Query("height")
width, _ := strconv.Atoi(widthStr)
height, _ := strconv.Atoi(heightStr)
if albumID == "root" {
albumID = ""
}
isPublic, err := services.IsAlbumPublic(albumID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
allowed := false
if isPublic {
allowed = true
} else {
accessToken := c.GetHeader("Authorization")
userID, err := services.ValidateAccessToken(accessToken)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
accessLevel, err := services.CheckUserAlbumAccess(userID, albumID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if accessLevel >= 0 {
allowed = true
} else {
c.JSON(http.StatusForbidden, gin.H{"error": "user does not have permission to view media in this album"})
return
}
}
if allowed {
thumbPath, err := services.GetThumbnail(albumID, mediaID, width, height)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.File(thumbPath)
}
})
}
+106 -12
View File
@@ -7,8 +7,12 @@ import (
_ "image/jpeg"
_ "image/png"
"mime/multipart"
"os"
"path/filepath"
"github.com/disintegration/imaging"
"github.com/google/uuid"
"github.com/rwcarlsen/goexif/exif"
"github.com/wisplite/raster/internal/db"
"github.com/wisplite/raster/internal/models"
"gorm.io/datatypes"
@@ -31,30 +35,54 @@ func UploadMedia(file *multipart.FileHeader, albumID string, accessToken string)
albumPath = "root"
}
// Extract metadata (dimensions)
// Extract metadata (dimensions and file info)
var meta datatypes.JSON
metadataMap := map[string]interface{}{
"originalFilename": file.Filename,
"fileSize": file.Size,
"contentType": file.Header.Get("Content-Type"),
}
src, err := file.Open()
if err == nil {
defer src.Close()
cfg, _, err := image.DecodeConfig(src)
cfg, format, err := image.DecodeConfig(src)
if err == nil {
m := map[string]int{
"width": cfg.Width,
"height": cfg.Height,
metadataMap["width"] = cfg.Width
metadataMap["height"] = cfg.Height
metadataMap["format"] = format
// Check for EXIF orientation
src.Seek(0, 0)
x, err := exif.Decode(src)
if err == nil {
orient, err := x.Get(exif.Orientation)
if err == nil {
val, err := orient.Int(0)
if err == nil {
if val >= 5 && val <= 8 {
metadataMap["width"] = cfg.Height
metadataMap["height"] = cfg.Width
}
}
}
}
b, _ := json.Marshal(m)
meta = datatypes.JSON(b)
}
}
b, _ := json.Marshal(metadataMap)
meta = datatypes.JSON(b)
mediaID := uuid.New().String()
mediaPath := fmt.Sprintf("media/%s/%s.%s", albumPath, mediaID, file.Filename)
media := models.Media{
ID: mediaID,
AlbumID: albumID,
Path: mediaPath,
Type: file.Header.Get("Content-Type"),
Metadata: meta,
ID: mediaID,
AlbumID: albumID,
Path: mediaPath,
Type: file.Header.Get("Content-Type"),
Title: file.Filename,
Description: "",
Metadata: meta,
}
result := db.GetDB().Create(&media)
if result.Error != nil {
@@ -100,3 +128,69 @@ func GetMedia(albumID string, mediaID string) (models.Media, error) {
}
return media, nil
}
func GetThumbnail(albumID string, mediaID string, width int, height int) (string, error) {
media, err := GetMedia(albumID, mediaID)
if err != nil {
return "", err
}
if width == 0 {
width = 200
}
if height == 0 {
height = 200
}
cacheDir := "cache/thumbnails"
if err := os.MkdirAll(cacheDir, 0755); err != nil {
return "", err
}
ext := filepath.Ext(media.Path)
if ext == "" {
ext = ".jpg"
}
thumbName := fmt.Sprintf("%s_%dx%d%s", mediaID, width, height, ext)
thumbPath := filepath.Join(cacheDir, thumbName)
if _, err := os.Stat(thumbPath); err == nil {
return thumbPath, nil
}
srcImage, err := imaging.Open(media.Path)
if err != nil {
return "", err
}
f, err := os.Open(media.Path)
if err == nil {
x, err := exif.Decode(f)
f.Close()
if err == nil {
orient, err := x.Get(exif.Orientation)
if err == nil {
val, err := orient.Int(0)
if err == nil {
switch val {
case 3:
srcImage = imaging.Rotate180(srcImage)
case 6:
srcImage = imaging.Rotate270(srcImage)
case 8:
srcImage = imaging.Rotate90(srcImage)
}
}
}
}
}
dstImage := imaging.Fill(srcImage, width, height, imaging.Center, imaging.Lanczos)
err = imaging.Save(dstImage, thumbPath)
if err != nil {
return "", err
}
return thumbPath, nil
}
+2
View File
@@ -1,4 +1,5 @@
import { Navigate, Routes, Route, useNavigate, useLocation } from 'react-router-dom'
import Viewer from './viewer'
import Gallery from './gallery'
import Login from './account/login'
import { getServerUrl } from './hooks/getConstants'
@@ -41,6 +42,7 @@ function App() {
<Routes>
<Route path="/" element={<RedirectHandler />} />
<Route path="/gallery/*" element={<Gallery />} />
<Route path="/viewer/:albumId/:mediaId" element={<Viewer />} />
<Route path="/login" element={<Login />} />
<Route path="/onboarding/createRootUser" element={<CreateRootUser />} />
</Routes>
+10 -4
View File
@@ -5,14 +5,14 @@ import { useState, useEffect } from 'react'
import { getServerUrl } from '../../hooks/getConstants'
import { useAccount } from '../../contexts/useAccount'
import { useNotifier } from '../../contexts/useNotifier'
import { useNavigate } from 'react-router-dom'
export default function MediaList({ albumId, albumName }) {
const { getAccessToken } = useAccount()
const [open, setOpen] = useState(false)
const [media, setMedia] = useState([])
const [aspectRatios, setAspectRatios] = useState({})
const { showError } = useNotifier()
const navigate = useNavigate()
useEffect(() => {
let ignore = false;
const getMedia = async () => {
@@ -73,10 +73,16 @@ export default function MediaList({ albumId, albumName }) {
flexGrow: ar,
flexBasis: `${220 * ar}px`,
}}
className="relative bg-[#1A1A1A] rounded-md overflow-hidden border border-[#2B2B2B] min-w-[100px]"
className="relative bg-[#1A1A1A] rounded-md overflow-hidden border border-[#2B2B2B] min-w-[100px] hover:scale-102 transition-all duration-300 cursor-pointer"
onClick={() => {
navigate(`/viewer/${albumId ? albumId : 'root'}/${item.ID}`)
}}
>
<div className="absolute top-0 left-0 w-full h-full bg-gradient-to-b from-[#1A1A1A] via-transparent to-transparent flex items-start justify-start opacity-0 hover:opacity-100 transition-all duration-300">
<p className="text-white text-sm truncate max-w-[100%] p-2 red-hat-mono">{item.Title}</p>
</div>
<AuthImage
src={`${getServerUrl()}/api/media/${albumId ? albumId : 'root'}/${item.ID}`}
src={`${getServerUrl()}/api/media/thumb/${albumId ? albumId : 'root'}/${item.ID}`}
token={getAccessToken()}
alt={item.Title}
className="w-full h-full object-cover"
@@ -0,0 +1,18 @@
import AuthImage from '../../components/AuthImage'
import { getServerUrl } from '../../hooks/getConstants'
export default function ImageViewer({ albumId, mediaId, token, title }) {
const src = `${getServerUrl()}/api/media/${albumId}/${mediaId}`
return (
<div className="flex-1 flex items-center justify-center bg-black relative overflow-hidden h-full">
<AuthImage
src={src}
token={token}
alt={title}
className="max-w-full max-h-full object-contain"
/>
</div>
)
}
@@ -0,0 +1,51 @@
export default function MetadataPanel({ mediaItem }) {
if (!mediaItem) return <div className="w-80 bg-[#1A1A1A] h-full border-l border-[#2B2B2B] p-4 text-white">Loading...</div>
return (
<div className="w-80 bg-[#1A1A1A] h-full border-l border-[#2B2B2B] p-6 text-white overflow-y-auto flex-shrink-0">
<h2 className="text-xl font-bold mb-6 red-hat-mono break-words">{mediaItem.Title}</h2>
<div className="space-y-6">
<div className="space-y-2">
<h3 className="text-sm font-semibold text-gray-400 uppercase tracking-wider">Details</h3>
<div className="bg-[#222] rounded p-3 space-y-2 text-sm">
<div className="flex justify-between">
<span className="text-gray-500">Type</span>
<span className="text-white">{mediaItem.Type || 'Unknown'}</span>
</div>
<div className="flex justify-between">
<span className="text-gray-500">Size</span>
{/* Placeholder for size formatting if not available */}
<span className="text-white">{mediaItem.Metadata?.fileSize ? (mediaItem.Metadata.fileSize / 1024 / 1024).toFixed(2) + ' MB' : 'N/A'}</span>
</div>
<div className="flex justify-between">
<span className="text-gray-500">Uploaded</span>
<span className="text-white">{mediaItem.CreatedAt ? new Date(mediaItem.CreatedAt).toLocaleDateString() : '-'}</span>
</div>
</div>
</div>
<div className="space-y-2">
<h3 className="text-sm font-semibold text-gray-400 uppercase tracking-wider">EXIF Data</h3>
<p className="text-xs text-gray-500 italic">Metadata editing not yet implemented.</p>
{/* Placeholder for EXIF data */}
<div className="bg-[#222] rounded p-3 space-y-2 text-sm opacity-50">
<div className="flex justify-between">
<span className="text-gray-500">Camera</span>
<span className="text-white">-</span>
</div>
<div className="flex justify-between">
<span className="text-gray-500">ISO</span>
<span className="text-white">-</span>
</div>
<div className="flex justify-between">
<span className="text-gray-500">Aperture</span>
<span className="text-white">-</span>
</div>
</div>
</div>
</div>
</div>
)
}
+84
View File
@@ -0,0 +1,84 @@
import { useEffect, useState } from 'react'
import { useParams, useLocation, useNavigate } from 'react-router-dom'
import ImageViewer from './components/ImageViewer'
import MetadataPanel from './components/MetadataPanel'
import { useAccount } from '../contexts/useAccount'
import { getServerUrl } from '../hooks/getConstants'
import { useNotifier } from '../contexts/useNotifier'
import { ArrowLeft } from 'lucide-react'
export default function Viewer() {
const { albumId, mediaId } = useParams()
const location = useLocation()
const navigate = useNavigate()
const { getAccessToken } = useAccount()
const { showError } = useNotifier()
const [mediaItem, setMediaItem] = useState(location.state?.mediaItem || null)
useEffect(() => {
if (mediaItem) return
const fetchMediaDetails = async () => {
try {
// Use '' if albumId is 'root'
const targetAlbumId = albumId === 'root' ? '' : albumId
const response = await fetch(`${getServerUrl()}/api/media/getAllMediaInAlbum?albumId=${targetAlbumId}`, {
headers: {
'Authorization': getAccessToken()
}
})
const data = await response.json()
if (data.error) {
showError(data.error)
} else {
const found = data.media.find(m => m.ID === mediaId)
if (found) {
setMediaItem(found)
} else {
showError("Media not found")
}
}
} catch (err) {
showError("Failed to fetch media details")
}
}
fetchMediaDetails()
}, [albumId, mediaId, getAccessToken, showError, mediaItem])
const handleBack = () => {
if (window.history.state && window.history.state.idx > 0) {
navigate(-1)
} else {
// Fallback if opened directly
navigate('/gallery')
}
}
return (
<div className="flex flex-col h-screen w-full bg-[#141414]">
<div className="flex items-center h-14 px-4 border-b border-[#2B2B2B] bg-[#141414] flex-shrink-0 gap-4">
<button onClick={handleBack} className="text-gray-400 hover:text-white transition-colors p-1 cursor-pointer">
<ArrowLeft size={20} />
</button>
<span className="text-white font-medium truncate red-hat-mono">
{mediaItem ? mediaItem.Title : 'Loading...'}
</span>
</div>
<div className="flex flex-1 overflow-hidden">
<ImageViewer
albumId={albumId === 'root' ? '' : albumId}
mediaId={mediaId}
token={getAccessToken()}
title={mediaItem?.Title || ''}
/>
<MetadataPanel mediaItem={mediaItem} />
</div>
</div>
)
}