Merge branch 'main' into feature/scroll-date-IntoView

This commit is contained in:
knom committed 2025-01-24 11:26:05 +00:00
commit 84fdf5d895
106 files changed
+4298 -4937

No files matched your search

+9 -1
View File
@@ -7,4 +7,12 @@ DB_PORT="" # Postgres Port number (Default: 5432)
DB_DATABASE_NAME="" # Name of the database
# Additional configuration
SECURE_COOKIE=false # Set to true to enable secure cookies
SECURE_COOKIE=false # Set to true to enable secure cookies
# Optional
GOOGLE_MAPS_API_KEY="" # Google Maps API Key for heatmap
GEMINI_API_KEY="" # Gemini API Key for parsing search query in "Find"
# Immich Share Link
IMMICH_SHARE_LINK_KEY="" # Share link key for Immich
POWER_TOOLS_ENDPOINT_URL="" # URL of the Power Tools endpoint (Used for share links)
+8 -1
View File
@@ -1,3 +1,10 @@
{
"extends": "next/core-web-vitals"
"extends": "next/core-web-vitals",
"plugins": ["@remotion"],
"overrides": [
{
"files": ["remotion/*.{ts,tsx}"],
"extends": ["plugin:@remotion/recommended"]
}
]
}
+1 -1
View File
@@ -3,7 +3,7 @@ name: ci
on:
push:
branches:
- release
- main
jobs:
release:
+40 -3
View File
@@ -6,6 +6,21 @@ A unofficial immich client to provide better tools to organize and manage your i
[![Immich Power Tools](./screenshots/screenshot-1.png)](https://www.loom.com/embed/13aa90d8ab2e4acab0993bdc8703a750?sid=71498690-b745-473f-b239-a7bdbe6efc21)
### 🎒Features
- **Manage people data in bulk 👫**: Options to update people data in bulk, and with advance filters
- **People Merge Suggestion 🎭**: Option to bulk merge people with suggested faces based on similarity.
- **Update Missing Locations 📍**: Find assets in your library those are without location and update them with the location of the asset.
- **Potential Albums 🖼️**: Find albums that are potential to be created based on the assets and people in your library.
- **Analytics 📈**: Get analytics on your library like assets over time, exif data, etc.
- **Smart Search 🔎**: Search your library with natural language, supports queries like "show me all my photos from 2024 of <person name>"
- **Bulk Date Offset 📅**: Offset the date of selected assets by a given amount of time. Majorly used to fix the date of assets that are out of sync with the actual date.
### Support me 🙏
If you find this tool useful, please consider supporting me by buying me a coffee.
[![Buy me a coffee](https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png)](https://www.buymeacoffee.com/varunraj)
## 💭 Back story
Recently I've migrated my entire Google photos library to Immich, I was able to successfully migrate all my assets along with its albums to immich. But there were few things like people match that was lacking. I loved Immich UI on the whole but for organizing content I felt its quite restricted and I had to do a lot of things in bulk instead of opening each asset and doing it. Hence I built this tool (continuing to itereate) to make my life and any other Immich user's life easier.
@@ -39,6 +54,10 @@ Add the Immich API Key and immich url's to the env file (which you already have
IMMICH_API_KEY= # your_immich_api_key
IMMICH_URL = "http://local-ip-of-immich:port" # Your immich instace ip address and port
EXTERNAL_IMMICH_URL = "https://external-address" # External address of immich
# Optional
GOOGLE_MAPS_API_KEY= # Google Maps API Key
GEMINI_API_KEY= # Gemini API Key
```
Refer here for obtaining Immich API Key: https://immich.app/docs/features/command-line-interface#obtain-the-api-key
@@ -47,7 +66,11 @@ Refer here for obtaining Immich API Key: https://immich.app/docs/features/comman
If you're using portainer, run the docker using `docker run` and add the power tools to the same network as immich.
```bash
# Run the power tools from docker
docker run -d --name immich_power_tools -p 8001:3000 --env-file .env ghcr.io/varun-raj/immich-power-tools:latest
# Add Power tools to the same network as immich
docker network connect immich_default immich_power_tools
```
@@ -86,7 +109,8 @@ bun run dev
- [x] Manage People
- [x] Smart Merge
- [x] Manage Albums
- [ ] Bulk Delete
- [x] Bulk Delete
- [x] Bulk Share
- [ ] Bulk Edit
- [ ] Filters
- [x] Potential Albums
@@ -100,7 +124,7 @@ bun run dev
- [x] Dark Mode
- [x] Dockerize
- [ ] Authentication
- [x] Authentication
- [x] Push to github packages
## Tech Stack
@@ -110,6 +134,19 @@ bun run dev
- [Shadcn](https://shadcn.com/) for UI Components
- [Axios](https://axios-http.com/) for API calls
## External Services
These services are completely optional and you can use the tool without them. Just that they are used for some of the features. But we dont send any personal data to these services.
- [Google Maps](https://maps.google.com/) for heatmap
Google Maps Javascript API Key is used to render the maps layer for heatmap. When rendering the heatmap, we only send the location data to Google Maps and not any other data.
> Code where heatmap data is plotted: [src/pages/assets/geo-heatmap.tsx:32](./src/pages/assets/geo-heatmap.tsx#L32-L35)
- [Gemini](https://gemini.google.com/) for rewind video generation
Google Gemini 1.5 Flash model is used for parsing your search query in "Find" page. We do not send any personal data to Gemini, only data that is sent to Gemini is your search query and rest of the querying happes using [Immich's Smart Search API](https://immich.app/docs/api/search-smart)
> Code where Gemini is used: [src/helpers/gemini.helper.ts](./src/helpers/gemini.helper.ts)
## Contributing
Feel free to contribute to this project, I'm open to any suggestions and improvements. Please read the [CONTRIBUTING.md](./CONTRIBUTING.md) for more details.
Feel free to contribute to this project, I'm open to any suggestions and improvements. Please read the [CONTRIBUTING.md](./CONTRIBUTING.md) for more details.
BIN
View File
Binary file not shown.
+15 -5
View File
@@ -1,6 +1,6 @@
{
"name": "immich-power-tools",
"version": "0.10.1",
"version": "0.13.0",
"private": true,
"scripts": {
"dev": "next dev",
@@ -14,7 +14,9 @@
"url": "https://varunraj.in"
},
"dependencies": {
"@google/generative-ai": "^0.21.0",
"@radix-ui/react-accordion": "^1.2.1",
"@radix-ui/react-alert-dialog": "^1.1.4",
"@radix-ui/react-avatar": "^1.1.0",
"@radix-ui/react-checkbox": "^1.1.2",
"@radix-ui/react-dialog": "^1.1.1",
@@ -30,10 +32,13 @@
"@radix-ui/react-tabs": "^1.1.0",
"@radix-ui/react-toast": "^1.2.1",
"@radix-ui/react-tooltip": "^1.1.2",
"@remotion/cli": "4.0.232",
"@remotion/eslint-plugin": "^4.0.232",
"@tanstack/react-table": "^8.20.1",
"@types/cookie": "^0.6.0",
"@types/qs": "^6.9.15",
"@types/react-calendar-heatmap": "^1.6.7",
"@vis.gl/react-google-maps": "^1.4.2",
"axios": "^1.7.4",
"chrono-node": "^1.4.9",
"class-variance-authority": "^0.7.0",
@@ -43,25 +48,29 @@
"cookie": "^0.6.0",
"date-fns": "^3.6.0",
"drizzle-orm": "^0.33.0",
"jsonwebtoken": "^9.0.2",
"leaflet": "^1.9.4",
"leaflet-defaulticon-compatibility":"0.1.2",
"leaflet-defaulticon-compatibility": "0.1.2",
"lucide-react": "^0.428.0",
"next": "14.2.5",
"next-themes": "^0.3.0",
"pg": "^8.12.0",
"qs": "^6.13.0",
"react": "^18",
"react-calendar-heatmap": "^1.9.0",
"react-day-picker": "9.0.8",
"react-dom": "^18",
"react-grid-gallery": "^1.0.1",
"react-hot-toast": "^2.5.1",
"react-leaflet": "^4.2.1",
"react-mentions": "^4.4.10",
"react-query": "^3.39.3",
"recharts": "^2.12.7",
"remotion": "4.0.232",
"sass": "^1.77.8",
"tailwind-merge": "^2.5.2",
"tailwindcss-animate": "^1.0.7",
"yet-another-react-lightbox": "^3.21.4"
"yet-another-react-lightbox": "^3.21.4",
"zod": "^3.24.1"
},
"devDependencies": {
"@semantic-release/commit-analyzer": "^13.0.0",
@@ -70,11 +79,12 @@
"@semantic-release/npm": "^12.0.1",
"@semantic-release/release-notes-generator": "^14.0.1",
"@types/jsonwebtoken": "^9.0.6",
"@types/leaflet":"^1.9.15",
"@types/leaflet": "^1.9.15",
"@types/node": "^20",
"@types/pg": "^8.11.6",
"@types/react": "^18",
"@types/react-dom": "^18",
"@types/react-mentions": "^4.4.1",
"autoprefixer": "^10.4.20",
"drizzle-kit": "^0.24.0",
"eslint": "^8",
-6
View File
@@ -1,6 +0,0 @@
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
+1
View File
@@ -2,6 +2,7 @@
const config = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};
Binary file not shown.
+72
View File
@@ -0,0 +1,72 @@
import { AbsoluteFill, useCurrentFrame, interpolate, staticFile, Audio, Sequence } from "remotion";
import WelcomeScene from "./rewind/WelcomeScene";
import CountryScene from "./rewind/CountryScene";
import MemoriesScene from "./rewind/MemoriesScene";
import AlbumsScene from "./rewind/AlbumScene";
import FriendsScene from "./rewind/FriendsScene";
import PowertoolsLogo from "./rewind/Powertoolslogo";
export interface Scene {
message: string;
type: string;
emoji: string;
data: any;
}
export const IntroComposition = ({ scenes }: { scenes: Scene[] }) => {
const frame = useCurrentFrame();
const screenDuration = 120;
const renderScene = (scene: Scene) => {
switch (scene.type) {
case "WELCOME":
return <WelcomeScene message={scene.message} emoji={scene.emoji} />;
case "COUNTRY":
return <CountryScene message={scene.message} emoji={scene.emoji} data={scene.data} />;
case "MEMORY":
return <MemoriesScene message={scene.message} emoji={scene.emoji} data={scene.data} />;
case "ALBUM":
return <AlbumsScene message={scene.message} emoji={scene.emoji} data={scene.data} />;
case "FRIEND":
return <FriendsScene message={scene.message} emoji={scene.emoji} data={scene.data} />;
default:
return <WelcomeScene message={scene.message} emoji={scene.emoji} />;
}
};
return (
<AbsoluteFill
style={{
justifyContent: "center",
alignItems: "center",
backgroundColor: "black",
transition: "background-color 1s ease",
fontFamily: "sans-serif",
}}
>
<Sequence name="Logo Intro" durationInFrames={screenDuration}>
<div style={{
width: "100%",
height: "100%",
display: "flex",
justifyContent: "center",
alignItems: "center"
}}>
<PowertoolsLogo size={200} />
</div>
</Sequence>
{scenes.map((scene, index) => (
<Sequence
key={index}
name={`Scene ${index + 1} - ${scene.type}`}
from={screenDuration * (index + 1)}
durationInFrames={screenDuration}
>
{renderScene(scene)}
</Sequence>
))}
<Audio src={staticFile("audio/rewind.mp3")} />
</AbsoluteFill>
);
};
+104
View File
@@ -0,0 +1,104 @@
import React from 'react';
import { Composition } from 'remotion';
import { IntroComposition, Scene } from './Composition';
export const scenes: Scene[] = [
{ message: "Welcome Varun!",
type: "WELCOME",
emoji: "👋",
data: {},
},
{
message: "2024! So much memories!",
type: "TITLE",
emoji: "📅",
data: {
photos: 100,
},
},
{
message: "You've been to 10 new countries!", type: "COUNTRY", emoji: "🌍", data: {
countries: ["India", "USA", "Canada", "UK", "Australia", "New Zealand", "Singapore", "Malaysia", "Thailand", "Japan", "South Korea"],
},
},
{
message: "And 25 new cities!", type: "CITY", emoji: "🏙️", data: {
cities: 25,
},
},
{
message: "Here are some of my favorite memories from this year!", type: "MEMORY", emoji: "🎉", data: {
photos: 100,
images: [
"https://picsum.photos/id/237/200/300",
"https://picsum.photos/id/238/200/300",
"https://picsum.photos/id/239/200/300",
"https://picsum.photos/id/240/200/300",
"https://picsum.photos/id/241/200/300",
],
},
},
{
message: "The most memory filled album of all time!", type: "ALBUM", emoji: "📸", data: {
photos: 100,
albums: [
{
name: "Ladakh 2024",
cover: "https://picsum.photos/id/400/200/300",
},
{
name: "Kerala 2024",
cover: "https://picsum.photos/id/401/200/300",
},
{
name: "Mumbai 2024",
cover: "https://picsum.photos/id/402/200/300",
},
{
name: "Kerala 2023",
cover: "https://picsum.photos/id/403/200/300",
},
],
},
},
{
message: "You made so much memory with Soundarapandian", type: "FRIEND", emoji: "👯", data: {
friends: [
{
name: "Soundarapandian",
cover: "https://i.pravatar.cc/150?img=64",
},
{
name: "Varun",
cover: "https://i.pravatar.cc/150?img=65",
},
],
},
},
{
message: "Lets see what 2025 has in store!", type: "END", emoji: "🚀", data: {
},
},
]
export const RemotionRoot: React.FC = () => {
return (
<>
<Composition
id="Intro"
defaultProps={{ scenes }}
component={IntroComposition}
durationInFrames={scenes.length * 120}
fps={30}
width={720}
height={1280}
/>
</>
);
};
+4
View File
@@ -0,0 +1,4 @@
import { registerRoot } from "remotion";
import { RemotionRoot } from "./Root";
registerRoot(RemotionRoot);
+103
View File
@@ -0,0 +1,103 @@
import React, { useMemo } from 'react';
import { Img, spring, useCurrentFrame, useVideoConfig } from 'remotion';
interface AlbumSceneProps {
message: string;
emoji: string;
data: {
photos: number;
albums: {
name: string;
cover: string;
}[];
};
}
export default function AlbumScene({ message, emoji, data }: AlbumSceneProps) {
const frame = useCurrentFrame();
const { fps } = useVideoConfig();
const albums = useMemo(() => data.albums, [data.albums]);
return (
<div style={{
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
height: "100%",
padding: "20px",
gap: 40
}}>
<div style={{
display: "flex",
flexDirection: "column",
alignItems: "center",
gap: 20
}}>
<span style={{ fontSize: 80 }}>{emoji}</span>
<h1 style={{
fontSize: 50,
color: "white",
textAlign: "center",
margin: 0,
maxWidth: "80%"
}}>
{message}
</h1>
</div>
<div style={{
display: "grid",
gridTemplateColumns: "repeat(2, 1fr)",
gap: 20,
width: "100%",
maxWidth: 600
}}>
{albums.map((album, index) => {
const delay = index * 5;
const scale = spring({
frame: frame - delay,
fps,
from: 0,
to: 1,
config: {
damping: 12,
},
});
return (
<div
key={album.name}
style={{
transform: `scale(${scale})`,
opacity: scale,
}}
>
<Img
src={album.cover}
alt={album.name}
style={{
width: "100%",
height: 200,
objectFit: "cover",
borderRadius: 15,
boxShadow: "0 4px 8px rgba(0,0,0,0.2)",
}}
/>
<p style={{
color: "white",
fontSize: 18,
textAlign: "center",
margin: "10px 0",
fontWeight: "bold"
}}>
{album.name}
</p>
</div>
);
})}
</div>
</div>
);
}
+85
View File
@@ -0,0 +1,85 @@
import React, { useMemo } from 'react';
import { spring, useCurrentFrame, useVideoConfig } from 'remotion';
interface CountrySceneProps {
message: string;
emoji: string;
data: {
countries: string[];
};
}
export default function CountryScene({ message, emoji, data }: CountrySceneProps) {
const frame = useCurrentFrame();
const { fps } = useVideoConfig();
const countries = useMemo(() => data.countries, [data.countries]);
return (
<div style={{
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
height: "100%",
gap: 40
}}>
<div style={{
display: "flex",
flexDirection: "column",
alignItems: "center",
gap: 20
}}>
<span style={{
fontSize: 100
}}>
{emoji}
</span>
<h1 style={{
fontSize: 70,
color: "white",
textAlign: "center",
margin: 0
}}>
{message}
</h1>
</div>
<div style={{
display: "flex",
flexWrap: "wrap",
gap: 20,
justifyContent: "center",
maxWidth: "80%"
}}>
{countries.map((country, index) => {
const delay = index * 5;
const scale = spring({
frame: frame - delay,
fps,
from: 0,
to: 1,
config: {
damping: 12,
},
});
return (
<div
key={country}
style={{
backgroundColor: "rgba(255,255,255,0.1)",
padding: "10px 20px",
borderRadius: 15,
transform: `scale(${scale})`,
opacity: scale,
}}
>
<span style={{ color: "white", fontSize: 24 }}>{country}</span>
</div>
);
})}
</div>
</div>
);
}
+139
View File
@@ -0,0 +1,139 @@
import React from 'react';
import { Img, spring, useCurrentFrame, useVideoConfig } from 'remotion';
interface FriendsSceneProps {
message: string;
emoji: string;
data: {
friends: {
name: string;
cover: string;
}[];
};
}
export default function FriendsScene({ message, emoji, data }: FriendsSceneProps) {
const frame = useCurrentFrame();
const { fps } = useVideoConfig();
return (
<div style={{
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
height: "100%",
padding: "20px"
}}>
<div style={{
display: "flex",
flexDirection: "column",
alignItems: "center",
gap: 20,
marginBottom: 40,
opacity: spring({
frame,
fps,
from: 0,
to: 1,
config: {
mass: 0.5,
damping: 20,
}
})
}}>
<span style={{
fontSize: 80,
transform: `translateY(${spring({
frame,
fps,
from: 0,
to: -10,
config: {
mass: 0.3,
damping: 10,
stiffness: 100
}
})}px)`
}}>{emoji}</span>
<h1 style={{
fontSize: 50,
color: "white",
textAlign: "center",
margin: 0,
maxWidth: "80%",
textShadow: "2px 2px 4px rgba(0,0,0,0.2)"
}}>
{message}
</h1>
</div>
<div style={{
display: "flex",
gap: 30,
justifyContent: "center",
width: "100%"
}}>
{data.friends.map((friend, index) => {
const delay = index * 5;
const scale = spring({
frame: frame - delay,
fps,
from: 0,
to: 1,
config: {
mass: 0.8,
damping: 15,
stiffness: 100
},
});
const rotation = spring({
frame: frame - delay,
fps,
from: 0,
to: index % 2 === 0 ? 8 : -8,
config: {
mass: 0.5,
damping: 20,
stiffness: 80
},
});
return (
<div
key={friend.name}
style={{
transform: `scale(${scale}) rotate(${rotation}deg)`,
opacity: scale
}}
>
<Img
src={friend.cover}
alt={friend.name}
style={{
width: 200,
height: 200,
objectFit: "cover",
borderRadius: "50%",
border: "8px solid white",
boxShadow: "0 8px 16px rgba(0,0,0,0.2)",
}}
/>
<p style={{
color: "white",
fontSize: 24,
textAlign: "center",
margin: "15px 0",
fontWeight: "bold",
textShadow: "1px 1px 2px rgba(0,0,0,0.2)"
}}>
{friend.name}
</p>
</div>
);
})}
</div>
</div>
);
}
+128
View File
@@ -0,0 +1,128 @@
import React, { useMemo, useRef } from 'react'
import { Img, spring, useCurrentFrame, useVideoConfig } from 'remotion';
interface MemoriesSceneProps {
message: string;
emoji: string;
data: {
images: string[];
};
}
export default function MemoriesScene({ message, emoji, data }: MemoriesSceneProps) {
const images = useMemo(() => data.images.map((image, index) => ({
src: image,
rotate: (index % 2 === 0 ? 1 : -1) * 8,
})), [data.images]);
const frame = useCurrentFrame();
const { fps } = useVideoConfig();
const messageOpacity = spring({
frame,
fps,
from: 0,
to: 1,
config: {
mass: 0.5,
damping: 20,
stiffness: 100
}
});
const messageY = spring({
frame,
fps,
from: -20,
to: 0,
config: {
mass: 0.5,
damping: 20,
stiffness: 100
}
});
return (
<div style={{
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
height: "100%",
padding: "20px 0"
}}>
<div style={{
opacity: messageOpacity,
transform: `translateY(${messageY}px)`,
}}>
<span style={{
fontSize: 80,
display: "block",
textAlign: "center",
marginBottom: 20
}}>{emoji}</span>
<p style={{
fontSize: 50,
padding: "0 40px",
color: "white",
marginBottom: 40,
textAlign: "center",
textShadow: "2px 2px 4px rgba(0,0,0,0.2)"
}}>
{message}
</p>
</div>
<div style={{
display: "grid",
gridTemplateColumns: "repeat(2, 1fr)",
gap: 30,
maxWidth: "90%",
placeItems: "center",
}}>
{images.slice(0, 4).map((image, index) => {
const delay = index * 5;
const scale = spring({
frame: frame - delay,
fps,
from: 0,
to: 1,
config: {
mass: 0.8,
damping: 15,
stiffness: 100
},
});
const rotation = spring({
frame: frame - delay,
fps,
from: 0,
to: image.rotate, // Use the stable rotation value directly
config: {
mass: 0.5,
damping: 20,
stiffness: 80
},
});
return (
<Img
key={index}
src={image.src}
alt="memory"
style={{
width: 280,
height: 280,
objectFit: "cover",
borderRadius: 15,
transform: `scale(${scale}) rotate(${rotation}deg)`,
opacity: scale,
boxShadow: "0 8px 16px rgba(0,0,0,0.3)",
border: "8px solid white"
}}
/>
)
})}
</div>
</div>
)
}
+169
View File
@@ -0,0 +1,169 @@
import React from 'react';
import { spring, useCurrentFrame, useVideoConfig, interpolate } from 'remotion';
interface PowertoolsLogoProps {
size?: number;
}
export default function PowertoolsLogo({ size = 379 }: PowertoolsLogoProps) {
const frame = useCurrentFrame();
const { fps } = useVideoConfig();
// Create staggered animations for each rectangle
const scale1 = spring({
frame,
fps,
from: 0,
to: 1,
config: { damping: 12 }
});
const scale2 = spring({
frame: frame - 5,
fps,
from: 0,
to: 1,
config: { damping: 12 }
});
const scale3 = spring({
frame: frame - 10,
fps,
from: 0,
to: 1,
config: { damping: 12 }
});
const scale4 = spring({
frame: frame - 15,
fps,
from: 0,
to: 1,
config: { damping: 12 }
});
const scale5 = spring({
frame: frame - 20,
fps,
from: 0,
to: 1,
config: { damping: 12 }
});
// Text animation
const textOpacity = spring({
frame: frame - 25,
fps,
from: 0,
to: 1,
config: { damping: 12 }
});
// Rewind text animations - bouncing and color changing effect
const rewindRotation = interpolate(
frame,
[0, 30],
[360, 0],
{
extrapolateRight: 'clamp'
}
);
const bounceY = spring({
frame: frame - 25,
fps,
from: -20,
to: 0,
config: { mass: 0.5, damping: 4 }
});
const hue = interpolate(
frame % 120,
[0, 60, 120],
[0, 180, 360]
);
return (
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
<svg width={size} height={size} viewBox="0 0 379 379" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect
x="48"
y="34"
width="283"
height="94.7184"
rx="20"
fill="#FA2921"
transform={`scale(${scale1})`}
transform-origin="center"
/>
<rect
x="49.1551"
y="142.58"
width="97.0286"
height="93.5633"
rx="20"
fill="#ED79B5"
transform={`scale(${scale2})`}
transform-origin="center"
/>
<rect
x="233.971"
y="250.004"
width="97.0286"
height="94.7184"
rx="20"
fill="#18C249"
transform={`scale(${scale3})`}
transform-origin="center"
/>
<rect
x="160.045"
y="142.58"
width="170.955"
height="93.5633"
rx="20"
fill="#1E83F7"
transform={`scale(${scale4})`}
transform-origin="center"
/>
<rect
x="48"
y="250.004"
width="170.955"
height="94.7184"
rx="20"
fill="#FFB400"
transform={`scale(${scale5})`}
transform-origin="center"
/>
</svg>
<div style={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
opacity: textOpacity,
marginTop: 20
}}>
<h1 style={{
color: 'white',
margin: 0,
fontSize: 32
}}>
Immich Power Tools
</h1>
<h2 style={{
color: `hsl(${hue}, 100%, 50%)`,
margin: '10px 0 0 0',
fontSize: 40,
transform: `rotate(${rewindRotation}deg) translateY(${bounceY}px)`,
transformOrigin: 'center',
textShadow: '0 0 10px rgba(255,255,255,0.5)',
fontWeight: 'bold',
letterSpacing: '2px'
}}>
Rewind
</h2>
</div>
</div>
);
}
+81
View File
@@ -0,0 +1,81 @@
import React from 'react'
import { spring, useCurrentFrame, useVideoConfig, interpolate } from 'remotion'
interface WelcomeSceneProps {
message: string;
emoji: string;
}
export default function WelcomeScene({ message, emoji }: WelcomeSceneProps) {
const frame = useCurrentFrame();
const { fps } = useVideoConfig();
const scale = spring({
frame,
fps,
from: 0.5,
to: 1,
config: { damping: 12 }
});
const opacity = spring({
frame,
fps,
from: 0,
to: 1,
config: { damping: 12 }
});
const rotation = spring({
frame,
fps,
from: -5,
to: 0,
config: { damping: 12 }
});
const hue = interpolate(
frame,
[0, 60],
[180, 240],
{ extrapolateRight: 'clamp' }
);
return (
<div style={{
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
transform: `scale(${scale})`,
opacity: opacity,
background: `radial-gradient(circle, rgba(0,0,0,0) 0%, rgba(0,0,0,0.3) 100%)`,
padding: 40,
borderRadius: 20,
}}>
<p style={{
fontSize: 120,
marginTop: 40,
marginBottom: 0,
textAlign: "center",
transform: `translateY(${Math.sin(frame / 30) * 10}px) rotate(${rotation}deg)`,
textShadow: '0 0 20px rgba(255,255,255,0.5)',
}}>
{emoji}
</p>
<p style={{
fontSize: 80,
padding: "0 70px",
color: `hsl(${hue}, 80%, 75%)`,
marginTop: 20,
textAlign: "center",
fontWeight: "bold",
textShadow: '0 0 15px rgba(255,255,255,0.3)',
letterSpacing: "2px",
lineHeight: 1.2
}}>
{message}
</p>
</div>
)
}
@@ -1,86 +0,0 @@
import React, { useEffect, useMemo, useState } from "react";
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "../ui/dialog";
import { Button } from "../ui/button";
import { listAlbums } from "@/handlers/api/album.handler";
import { IAlbum, IAlbumCreate } from "@/types/album";
import { Input } from "../ui/input";
import { Label } from "../ui/label";
import { useToast } from "../ui/use-toast";
interface IProps {
onCreated?: (album: IAlbum) => Promise<void>;
onSubmit?: (data: IAlbumCreate) => Promise<any>;
assetIds?: string[];
}
export default function AlbumCreateDialog({ onSubmit, assetIds }: IProps) {
const [open, setOpen] = useState(false);
const [loading, setLoading] = useState(false);
const [formData, setFormData] = useState({
albumName: "",
});
const { toast } = useToast();
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
if (!onSubmit) return;
setLoading(true);
onSubmit(formData)
.then(() => {
toast({
title: "Album Created",
description: "Album created successfully",
});
setFormData({ albumName: "" });
setOpen(false);
})
.catch((e) => {
toast({
title: "Error",
description: "Failed to create album",
variant: "destructive",
});
})
.finally(() => {
setLoading(false);
});
};
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button>Create Album</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Create Album</DialogTitle>
<DialogDescription>
Create and add photos to a new album
</DialogDescription>
</DialogHeader>
<form onSubmit={handleSubmit} className="flex flex-col gap-2">
<div className="flex flex-col gap-2">
<Label>Album Name</Label>
<Input
placeholder="Album Name"
onChange={(e) => {
setFormData({ ...formData, albumName: e.target.value });
}}
/>
</div>
<div className="self-end">
<Button disabled={loading}>
{loading ? "Creating Album" : "Create Album"}
</Button>
</div>
</form>
</DialogContent>
</Dialog>
);
}
+72 -7
View File
@@ -1,4 +1,4 @@
import React, { useEffect, useMemo, useState } from "react";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import {
Dialog,
DialogContent,
@@ -9,18 +9,28 @@ import {
} from "../ui/dialog";
import { Button } from "../ui/button";
import { listAlbums } from "@/handlers/api/album.handler";
import { IAlbum } from "@/types/album";
import { IAlbum, IAlbumCreate } from "@/types/album";
import { Input } from "../ui/input";
import { usePotentialAlbumContext } from "@/contexts/PotentialAlbumContext";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "../ui/tabs";
import toast from "react-hot-toast";
import { Label } from "../ui/label";
interface IProps {
onSelected: (album: IAlbum) => Promise<void>;
onCreated?: (album: IAlbum) => Promise<void>;
onSubmit?: (data: IAlbumCreate) => Promise<any>;
}
export default function AlbumSelectorDialog({ onSelected }: IProps) {
export default function AlbumSelectorDialog({ onSelected, onCreated, onSubmit }: IProps) {
const [open, setOpen] = useState(false);
const [albums, setAlbums] = useState<IAlbum[]>([]);
const [loading, setLoading] = useState(false);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [search, setSearch] = useState("");
const { selectedIds, assets } = usePotentialAlbumContext();
const [formData, setFormData] = useState({
albumName: "",
});
const fetchData = () => {
return listAlbums()
@@ -42,11 +52,31 @@ export default function AlbumSelectorDialog({ onSelected }: IProps) {
});
}
const handleSubmit = useCallback((e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
if (!onSubmit) return;
setLoading(true);
onSubmit(formData)
.then(() => {
toast.success("Album created successfully");
setFormData({ albumName: "" });
setOpen(false);
})
.catch((e) => {
toast.error("Failed to create album");
})
.finally(() => {
setLoading(false);
});
}, [onSubmit, formData]);
useEffect(() => {
if (open && !albums.length) fetchData();
}, [open]);
const renderContent = () => {
const renderContent = useCallback(() => {
if (loading) return <p>Loading...</p>;
if (errorMessage) return <p>{errorMessage}</p>;
return (
@@ -73,12 +103,36 @@ export default function AlbumSelectorDialog({ onSelected }: IProps) {
</div>
</div>
);
};
}, [albums, filteredAlbums, handleSelect, loading, errorMessage]);
const renderCreateContent = useCallback(() => {
return (
<form onSubmit={handleSubmit} className="flex flex-col gap-4 max-h-[500px] min-h-[500px]">
<p className="text-sm text-zinc-500 dark:text-zinc-400">
Create a new album and add the selected assets to it
</p>
<div className="flex flex-col gap-2">
<Label>Album Name</Label>
<Input
placeholder="Album Name"
onChange={(e) => {
setFormData({ ...formData, albumName: e.target.value });
}}
/>
</div>
<div className="self-end">
<Button disabled={loading} type="submit">
{loading ? "Creating Album" : "Create Album"}
</Button>
</div>
</form>
)
}, [loading, formData, handleSubmit]);
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button>Select Album</Button>
<Button size={"sm"} disabled={!selectedIds.length}>Add to Album</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
@@ -87,7 +141,18 @@ export default function AlbumSelectorDialog({ onSelected }: IProps) {
Select the albums you want to add the selected assets to
</DialogDescription>
</DialogHeader>
{renderContent()}
<Tabs defaultValue="albums" className="w-full">
<TabsList className="w-full">
<TabsTrigger className="w-full" value="albums">Albums</TabsTrigger>
<TabsTrigger className="w-full" value="create">Create</TabsTrigger>
</TabsList>
<TabsContent value="albums">
{renderContent()}
</TabsContent>
<TabsContent value="create">
{renderCreateContent()}
</TabsContent>
</Tabs>
</DialogContent>
</Dialog>
);
+4 -5
View File
@@ -125,22 +125,21 @@ export default function AlbumImages({ album }: AlbumImagesProps) {
index={index}
close={() => setIndex(-1)}
/>
<div className="w-full grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-2 p-2">
<div className="w-full grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-2 p-2">
{images.map((image) => (
<div
key={image.id}
className="w-full h-[200px] overflow-hidden relative"
className="w-full h-[180px] overflow-hidden relative"
>
<LazyImage
loading="lazy"
key={image.id}
src={image.original}
alt={image.originalFileName}
className='overflow-hidden'
className='overflow-hidden max-h-[180px] max-w-[180px] min-h-[180px] min-w-[180px]'
style={{
objectPosition: 'center',
objectFit: 'cover',
height: '100%',
objectFit: 'cover'
}}
onClick={() => handleClick(images.indexOf(image))}
/>
+48 -42
View File
@@ -21,14 +21,16 @@ import { Checkbox } from '@/components/ui/checkbox'
interface AlbumPeopleProps {
album: IAlbum
onSelect: (personId: string) => void
readOnly?: boolean
}
interface IAlbumPerson {
id: string
name: string
numberOfPhotos: number
}
export default function AlbumPeople({ album, onSelect }: AlbumPeopleProps) {
export default function AlbumPeople({ album, onSelect, readOnly }: AlbumPeopleProps) {
const { exImmichUrl } = useConfig()
const router = useRouter()
const { query, pathname } = router
@@ -99,7 +101,7 @@ export default function AlbumPeople({ album, onSelect }: AlbumPeopleProps) {
}
return (
<div className="overflow-y-auto min-w-[200px] sticky top-0 py-4 max-h-[calc(100vh-60px)] min-h-[calc(100vh-60px)] dark:bg-zinc-900 bg-gray-200 flex flex-col gap-2 px-2">
<div className="overflow-y-auto min-w-[200px] sticky top-0 py-4 max-h-[calc(100vh-60px)] min-h-[calc(100vh-60px)] border-r border-gray-200 dark:border-zinc-800 flex flex-col gap-2 px-2">
{selectedPerson && (
<div className='flex flex-col gap-2 bg-white dark:bg-zinc-900 p-2 rounded-md'>
@@ -117,51 +119,56 @@ export default function AlbumPeople({ album, onSelect }: AlbumPeopleProps) {
{selectedPerson.name || "No Name"}
</Link>
</div>
<div className='flex items-center gap-2'>
<PersonMergeDropdown
person={{
...selectedPerson,
assetCount: selectedPerson.numberOfPhotos,
birthDate: null,
thumbnailPath: PERSON_THUBNAIL_PATH(selectedPerson.id),
isHidden: false,
updatedAt: new Date()
}}
triggerClassName='w-full flex-1'
onComplete={(mergedPerson) => {
router.push({
pathname,
query: {
...query,
faceId: mergedPerson.id
}
})
}} />
<Button disabled={hidingPerson} className="!py-0.5 !px-2 text-xs h-7 flex-1" variant="outline" onClick={() => handleHidePerson(selectedPerson.id)}>
Hide
</Button>
</div>
{!readOnly && (
<div className='flex items-center gap-2'>
<PersonMergeDropdown
person={{
...selectedPerson,
assetCount: selectedPerson.numberOfPhotos,
birthDate: null,
thumbnailPath: PERSON_THUBNAIL_PATH(selectedPerson.id),
isHidden: false,
updatedAt: new Date()
}}
triggerClassName='w-full flex-1'
onComplete={(mergedPerson) => {
router.push({
pathname,
query: {
...query,
faceId: mergedPerson.id
}
})
}} />
<Button disabled={hidingPerson} className="!py-0.5 !px-2 text-xs h-7 flex-1" variant="outline" onClick={() => handleHidePerson(selectedPerson.id)}>
Hide
</Button>
</div>
)}
</div>
)}
<div className="flex items-center gap-2 justify-between">
<p className="text-sm font-medium">People</p>
{!selectedPerson && (
<Button variant="outline" className="!py-0.5 !px-2 text-xs h-7" onClick={() => {
setSelectionMode(!selectionMode)
setSelectedPeople([])
}}>
{selectionMode ? "Cancel" : "Select"}
</Button>
)}
{selectedPeople.length > 0 && (
<div className='absolute mx-auto bottom-0 w-full py-2 dark:bg-white bg-black -mx-2 px-2'>
<Button variant="outline" className="!py-0.5 !px-2 text-xs h-7" onClick={handleHideSelectedPeople}>
Hide {selectedPeople.length} people
</Button>
</div>
{!readOnly && (
<>
{!selectedPerson && (
<Button variant="outline" className="!py-0.5 !px-2 text-xs h-7" onClick={() => {
setSelectionMode(!selectionMode)
setSelectedPeople([])
}}>
{selectionMode ? "Cancel" : "Select"}
</Button>
)}
{selectedPeople.length > 0 && (
<div className='absolute mx-auto bottom-0 w-full py-2 bg-white darl:bg-black -mx-2 px-2'>
<Button variant="outline" className="!py-0.5 !px-2 text-xs h-7" onClick={handleHideSelectedPeople}>
Hide {selectedPeople.length} people
</Button>
</div>
)}
</>
)}
</div>
<div className="flex flex-col overflow-x-hidden gap-2">
@@ -188,7 +195,6 @@ export default function AlbumPeople({ album, onSelect }: AlbumPeopleProps) {
/>
)}
<LazyImage
role="button"
className={
cn("cursor-pointer h-10 w-10 min-w-10 rounded-full border-2",
@@ -1,23 +1,23 @@
import React, { useMemo } from 'react'
import React, { useMemo, useState } from 'react'
import Link from 'next/link';
import { useConfig } from '@/contexts/ConfigContext';
import { humanizeBytes, humanizeNumber, pluralize } from '@/helpers/string.helper';
import LazyImage from '@/components/ui/lazy-image';
import { ASSET_THUMBNAIL_PATH } from '@/config/routes';
import { IAlbum } from '@/types/album';
import { Badge } from '@/components/ui/badge';
import { formatDate } from '@/helpers/date.helper';
import { Checkbox } from '@/components/ui/checkbox';
import { differenceInDays } from 'date-fns';
import { FaceIcon } from '@radix-ui/react-icons';
import { Calendar, Camera, Image, User } from 'lucide-react';
import { Calendar, Camera } from 'lucide-react';
interface IAlbumThumbnailProps {
album: IAlbum;
onSelect: (checked: boolean) => void;
selected: boolean;
}
export default function AlbumThumbnail({ album, onSelect }: IAlbumThumbnailProps) {
export default function AlbumThumbnail({ album, onSelect, selected }: IAlbumThumbnailProps) {
const [isSelected, setIsSelected] = useState(selected);
const numberOfDays = useMemo(() => {
return differenceInDays(album.lastPhotoDate, album.firstPhotoDate);
}, [album.firstPhotoDate, album.lastPhotoDate]);
@@ -39,6 +39,7 @@ export default function AlbumThumbnail({ album, onSelect }: IAlbumThumbnailProps
{formatDate(album.firstPhotoDate.toString(), 'MMM d, yyyy')} - {formatDate(album.lastPhotoDate.toString(), 'MMM d, yyyy')}
</div>
<Checkbox
defaultChecked={isSelected}
onCheckedChange={onSelect}
className="absolute top-2 left-2 w-6 h-6 rounded-full border-gray-300 focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
/>
@@ -1,8 +1,8 @@
import "yet-another-react-lightbox/styles.css";
import { usePotentialAlbumContext } from "@/contexts/PotentialAlbumContext";
import { listPotentialAlbumsAssets } from "@/handlers/api/album.handler";
import { IAsset } from "@/types/asset";
import React, { useEffect, useMemo, useState } from "react";
import type { IAsset } from "@/types/asset";
import React, { type MouseEvent, useEffect, useMemo, useState } from "react";
import { Gallery } from "react-grid-gallery";
import Lightbox, { SlideImage, SlideTypes } from "yet-another-react-lightbox";
import Captions from "yet-another-react-lightbox/plugins/captions";
@@ -20,6 +20,7 @@ export default function PotentialAlbumsAssets() {
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [index, setIndex] = useState(-1);
const [lastSelectedIndex, setLastSelectedIndex] = useState(-1);
const fetchAssets = async () => {
setLoading(true);
@@ -40,18 +41,20 @@ export default function PotentialAlbumsAssets() {
width: p.exifImageWidth as number,
height: p.exifImageHeight as number,
isSelected: selectedIds.includes(p.id),
orientation: 1,
tags: [
{
title: "Immich Link",
value: (
<a href={exImmichUrl + "/photos/" + p.id} target="_blank">
<a href={`${exImmichUrl}/photos/${p.id}`} target="_blank" rel="noreferrer">
Open in Immich
</a>
),
},
],
}));
}, [assets, selectedIds]);
}, [assets, selectedIds, exImmichUrl]);
const slides = useMemo(
() =>
@@ -73,17 +76,31 @@ export default function PotentialAlbumsAssets() {
[images]
);
const handleClick = (idx: number) => setIndex(idx);
const handleSelect = (_idx: number, asset: IAsset) => {
const handleSelect = (_idx: number, asset: IAsset, event: MouseEvent<HTMLElement>) => {
event.stopPropagation();
const isPresent = selectedIds.includes(asset.id);
if (isPresent) {
updateContext({
selectedIds: selectedIds.filter((id) => id !== asset.id),
});
} else {
updateContext({ selectedIds: [...selectedIds, asset.id] });
const clickedIndex = images.findIndex((image) => {
return image.id === asset.id
});
if (event.shiftKey) {
const startIndex = Math.min(clickedIndex, lastSelectedIndex);
const endIndex = Math.max(clickedIndex, lastSelectedIndex);
const newSelectedIds = images.slice(startIndex, endIndex + 1).map((image) => image.id);
const allSelectedIds = [...selectedIds, ...newSelectedIds];
const uniqueSelectedIds = [...new Set(allSelectedIds)];
updateContext({ selectedIds: uniqueSelectedIds });
} else {
updateContext({ selectedIds: [...selectedIds, asset.id] });
}
setLastSelectedIndex(clickedIndex);
}
};
useEffect(() => {
@@ -121,7 +138,7 @@ export default function PotentialAlbumsAssets() {
<div className="w-full overflow-y-auto max-h-[calc(100vh-60px)]">
<Gallery
images={images}
onClick={handleClick}
onClick={setIndex}
enableImageSelection={true}
onSelect={handleSelect}
thumbnailImageComponent={LazyGridImage}
@@ -46,7 +46,7 @@ export default function PotentialAlbumsDates() {
}, [filters]);
return (
<div className="overflow-y-auto min-w-[200px] py-4 max-h-[calc(100vh-60px)] min-h-[calc(100vh-60px)] dark:bg-zinc-900 bg-gray-200 flex flex-col gap-2 px-2">
<div className="min-w-[200px] py-4 max-h-[calc(100vh-60px)] min-h-[calc(100vh-60px)] border-r border-gray-200 dark:border-zinc-800 flex flex-col gap-2 px-1">
<div className="flex justify-between items-center gap-2">
<Select
defaultValue={filters.sortBy}
@@ -69,14 +69,15 @@ export default function PotentialAlbumsDates() {
</Button>
</div>
</div>
{dateRecords.map((record) => (
<PotentialDateItem
key={record.date}
record={record}
onSelect={handleSelect}
/>
))}
<div className="overflow-y-auto">
{dateRecords.map((record) => (
<PotentialDateItem
key={record.date}
record={record}
onSelect={handleSelect}
/>
))}
</div>
</div>
);
}
@@ -20,11 +20,11 @@ export default function PotentialDateItem({ record, onSelect }: IProps) {
onClick={() => onSelect(record.date)}
key={record.date}
className={
cn("flex gap-1 flex-col p-2 py-1 rounded-lg hover:dark:bg-zinc-800 border border-transparent hover:bg-zinc-100 px-4",
cn("flex gap-1 flex-col p-2 py-1 rounded-lg hover:dark:bg-zinc-800 border border-transparent hover:bg-zinc-100",
startDate === record.date ? "bg-zinc-100 dark:bg-zinc-800 border-gray-300 dark:border-zinc-700" : "")
}
>
<p className="font-mono text-sm">{dateLabel}</p>
<p className="text-sm">{dateLabel}</p>
<p className="text-xs text-foreground/50">{record.asset_count} Orphan Assets</p>
</div>
);
@@ -0,0 +1,187 @@
import { AlertDialog } from '@/components/ui/alert-dialog';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import { Dialog, DialogTitle, DialogHeader, DialogContent } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { shareAlbums } from '@/handlers/api/album.handler';
import { generateShareLink } from '@/handlers/api/shareLink.handler';
import { IAlbum } from '@/types/album';
import React, { ForwardedRef, forwardRef, useImperativeHandle, useState } from 'react'
import ShareAssetsTrigger from '@/components/shared/ShareAssetsTrigger';
export interface IAlbumShareDialogProps {
}
export interface IAlbumShareDialogRef {
open: (selectedAlbums: IAlbum[]) => void;
close: () => void;
}
interface IAlbumWithLink extends IAlbum {
shareLink?: string;
allowDownload?: boolean;
allowUpload?: boolean;
showMetadata?: boolean;
}
const AlbumShareDialog = forwardRef(({ }: IAlbumShareDialogProps, ref: ForwardedRef<IAlbumShareDialogRef>) => {
const [open, setOpen] = useState(false);
const [selectedAlbums, setSelectedAlbums] = useState<IAlbumWithLink[]>([]);
const [generating, setGenerating] = useState(false);
const [error, setError] = useState<string | null>(null);
const [generated, setGenerated] = useState<boolean>(false);
const [loading, setLoading] = useState(false);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [generatedLink, setGeneratedLink] = useState<string | null>(null);
const [copied, setCopied] = useState(false);
const handleGenerateShareLink = async () => {
setGenerating(true);
const data = selectedAlbums.map((album) => ({
albumId: album.id,
albumName: album.albumName,
assetCount: album.assetCount,
allowDownload: !!album.allowDownload,
allowUpload: !!album.allowUpload,
showMetadata: !!album.showMetadata,
}));
return shareAlbums(data).then((updatedAlbums) => {
setSelectedAlbums(updatedAlbums);
setGenerated(true);
})
.catch((error) => {
setError(error.message);
})
.finally(() => {
setGenerating(false);
});
}
const handleGenerateGlobalShareLink = async () => {
setLoading(true);
return generateShareLink({
albumIds: selectedAlbums.map((album) => album.id),
}).then(({ link }) => {
setGeneratedLink(link);
}).catch((err) => {
setErrorMessage(err.message);
}).finally(() => {
setLoading(false);
});
}
const handleAllowPropertyChange = (albumId: string, property: string, checked: boolean) => {
setSelectedAlbums((prevAlbums) => prevAlbums.map((album) => album.id === albumId ? { ...album, [property]: checked } : album));
}
const handleCopy = () => {
if (generatedLink) {
navigator.clipboard.writeText(generatedLink);
setCopied(true);
setTimeout(() => {
setCopied(false);
}, 2000);
}
}
useImperativeHandle(ref, () => ({
open: (selectedAlbums: IAlbum[]) => {
setSelectedAlbums(selectedAlbums.map((album) => ({ ...album, allowDownload: true, allowUpload: true, showMetadata: true })));
setOpen(true);
},
close: () => {
setOpen(false);
}
}));
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent className="max-w-4xl">
<DialogHeader>
<DialogTitle>Share {selectedAlbums.length} albums</DialogTitle>
</DialogHeader>
<div className="flex flex-col gap-2">
{error && <div className="text-red-500">{error}</div>}
<ol className="flex flex-col gap-4 list-decimal px-4 py-4">
{selectedAlbums.map((album) => (
<li key={album.id}>
<div className="flex justify-between gap-1">
<h3 className="text-sm font-medium">{album.albumName}</h3>
<p className="text-xs border truncate rounded-md px-1 py-0.5 text-muted-foreground">{album.assetCount} Items</p>
</div>
<div className="flex flex-col gap-2">
{album.shareLink ?
<p className="text-xs text-muted-foreground truncate font-mono overflow-x-auto">{album.shareLink}</p> : (
<>
<p className="text-xs text-muted-foreground">No share link generated</p>
<div className="flex gap-2">
<div className="flex items-center gap-1">
<Checkbox checked={album.allowDownload} onCheckedChange={(checked) => handleAllowPropertyChange(album.id, 'allowDownload', !!checked)} />
<Label className="text-xs">Allow Download</Label>
</div>
<div className="flex items-center gap-1">
<Checkbox checked={album.allowUpload} onCheckedChange={(checked) => handleAllowPropertyChange(album.id, 'allowUpload', !!checked)} />
<Label className="text-xs">Allow Upload</Label>
</div>
<div className="flex items-center gap-1">
<Checkbox checked={album.showMetadata} onCheckedChange={(checked) => handleAllowPropertyChange(album.id, 'showMetadata', !!checked)} />
<Label className="text-xs">Show Metadata</Label>
</div>
</div>
</>
)}
</div>
</li>
))}
</ol>
{generatedLink && (
<div className="flex flex-col gap-2 items-center">
<p className="text-sm py-2 text-muted-foreground text-center">Share links all generated</p>
<div className="flex gap-2 w-full">
<Input value={generatedLink} readOnly />
<Button onClick={handleCopy} className='max-w-fit'>
{copied ? 'Copied' : 'Copy'}
</Button>
</div>
</div>
)}
{generated ? (
<>
<p className="text-sm py-2 text-muted-foreground text-center">Share links all generated</p>
</>
) : (
<>
{generating ? <div className="flex justify-center gap-2">
<p className="text-sm py-2 text-muted-foreground">Generating share links...</p>
</div> : (
<div className="flex justify-center gap-2">
<AlertDialog
title="Generate Share Links"
description="Generate share links for the selected albums."
onConfirm={handleGenerateShareLink}
>
<Button disabled={generating}>
Generate For {selectedAlbums.length} albums
</Button>
</AlertDialog>
<ShareAssetsTrigger filters={{ albumIds: selectedAlbums.map((album) => album.id) }} />
</div>
)}
</>
)}
</div>
</DialogContent>
</Dialog>
)
})
AlbumShareDialog.displayName = "AlbumShareDialog";
export default AlbumShareDialog;
@@ -58,7 +58,7 @@ export default function AssetHeatMap() {
const threshold2 = minCount + range * 0.4;
const threshold3 = minCount + range * 0.6;
const threshold4 = minCount + range * 0.8;
if (count === 0) return "bg-zinc-800";
if (count === 0) return "bg-zinc-200 dark:bg-zinc-800";
if (count <= threshold1) return "bg-green-200";
if (count <= threshold2) return "bg-green-400";
if (count <= threshold3) return "bg-green-500";
@@ -1,6 +1,6 @@
import React, { useEffect, useState } from 'react'
import { IAsset } from '@/types/asset';
import { Dialog, DialogTitle, DialogHeader, DialogContent } from '@/components/ui/dialog';
import { Dialog, DialogTitle, DialogHeader, DialogContent, DialogTrigger } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
@@ -11,12 +11,12 @@ import { useToast } from '@/components/ui/use-toast';
interface IProps {
assets: IAsset[];
open: boolean;
toggleOpen: (open: boolean) => void;
onComplete: () => void;
}
export default function AssetOffsetDialog({ assets: _assets, open, toggleOpen }: IProps) {
export default function AssetOffsetDialog({ assets: _assets, onComplete }: IProps) {
const { toast } = useToast();
const [open, setOpen] = useState(false);
const [assets, setAssets] = useState<IAsset[]>(_assets);
const [offsetData, setOffsetData] = useState<{ days: number, hours: number, minutes: number, seconds: number, years: number }>({
days: 0,
@@ -43,7 +43,7 @@ export default function AssetOffsetDialog({ assets: _assets, open, toggleOpen }:
})
.then(() => {
setLoading(false);
toggleOpen(false);
setOpen(false);
})
.catch((error) => {
setLoading(false);
@@ -52,7 +52,8 @@ export default function AssetOffsetDialog({ assets: _assets, open, toggleOpen }:
});
await Promise.all(promises);
setLoading(false);
toggleOpen(false);
setOpen(false);
onComplete();
toast({
title: 'Asset dates offset',
description: 'Asset dates have been offset',
@@ -65,12 +66,17 @@ export default function AssetOffsetDialog({ assets: _assets, open, toggleOpen }:
}, [_assets]);
return (
<Dialog open={open} onOpenChange={toggleOpen}>
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button variant={"default"} size={"sm"} onClick={() => setOpen(true)} disabled={assets.length === 0}>
Offset Dates
</Button>
</DialogTrigger>
<DialogContent className='max-w-[800px]'>
<DialogHeader>
<DialogTitle>Offset Asset Dates</DialogTitle>
</DialogHeader>
<form onSubmit={handleSubmit} className='flex items-center gap-2'>
<form onSubmit={handleSubmit} className='flex items-end gap-2'>
<div>
<Label>Years</Label>
<Input type="number" value={offsetData.years} onChange={(e) => handleChange("years", parseInt(e.target.value))} />
@@ -1,31 +0,0 @@
import { Button } from '@/components/ui/button'
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
import { IAsset } from '@/types/asset';
import { DotsVerticalIcon, HamburgerMenuIcon } from '@radix-ui/react-icons';
import { Clock, PlusIcon } from 'lucide-react'
import React, { useState } from 'react'
import AssetOffsetDialog from './AssetOffsetDialog';
interface IProps {
onAdd?: () => void;
assets: IAsset[];
}
export default function AssetsOptions({ onAdd, assets }: IProps) {
const [open, setOpen] = useState(false);
return (
<>
<DropdownMenu>
<DropdownMenuTrigger asChild className='cursor-pointer'>
<HamburgerMenuIcon className="w-4 h-4" />
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuItem className='flex items-center gap-2' onSelect={() => setOpen(true)}>
<Clock className="w-4 h-4" /> Offset Asset Dates
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
{open && <AssetOffsetDialog assets={assets} open={open} toggleOpen={setOpen} />}
</>
)
}
@@ -1,68 +1,75 @@
import "yet-another-react-lightbox/styles.css";
import { usePotentialAlbumContext } from "@/contexts/PotentialAlbumContext";
import { listPotentialAlbumsAssets } from "@/handlers/api/album.handler";
import { IAsset } from "@/types/asset";
import React, { useEffect, useMemo, useState } from "react";
import React, { useEffect, useMemo, useState, MouseEvent } from "react";
import { Gallery } from "react-grid-gallery";
import Lightbox from "yet-another-react-lightbox";
import Captions from "yet-another-react-lightbox/plugins/captions";
import {
ArrowUpRight,
CalendarArrowDown,
CalendarArrowUp,
Hourglass,
Link,
} from "lucide-react";
import { useMissingLocationContext } from "@/contexts/MissingLocationContext";
import { listMissingLocationAssets } from "@/handlers/api/asset.handler";
import { formatDate, parseDate } from "@/helpers/date.helper";
import { addDays } from "date-fns";
import { useConfig } from "@/contexts/ConfigContext";
import LazyGridImage from "@/components/ui/lazy-grid-image";
export default function MissingLocationAssets() {
interface IProps {
groupBy: "date" | "album";
}
export default function MissingLocationAssets({ groupBy }: IProps) {
const { exImmichUrl } = useConfig();
const { startDate, selectedIds, assets, updateContext } =
const { startDate, albumId, selectedIds, sortOrder, sort, assets, updateContext } =
useMissingLocationContext();
const [loading, setLoading] = useState(false);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [index, setIndex] = useState(-1);
const [lastSelectedIndex, setLastSelectedIndex] = useState(-1);
const fetchAssets = async () => {
if (!startDate) return;
if (!startDate && !albumId) return;
setLoading(true);
updateContext({
assets: [],
});
return listMissingLocationAssets({ startDate })
const filters = groupBy === "date" ? { startDate } : { albumId }
return listMissingLocationAssets(filters)
.then((assets) => updateContext({ assets }))
.catch(setErrorMessage)
.finally(() => setLoading(false));
};
const images = useMemo(() => {
return assets.map((p) => ({
...p,
src: p.url as string,
original: p.previewUrl as string,
width: p.exifImageWidth as number,
height: p.exifImageHeight as number,
isSelected: selectedIds.includes(p.id),
tags: [
{
title: "Immich Link",
value: (
<a href={exImmichUrl + "/photos/" + p.id} target="_blank">
Open in Immich
</a>
),
},
],
}));
}, [assets, selectedIds]);
let sortedAssets: IAsset[];
if (sortOrder === "desc")
sortedAssets = assets.sort((a, b) => new Date(b.dateTimeOriginal).getTime() - new Date(a.dateTimeOriginal).getTime())
else
sortedAssets = assets.sort((a, b) => new Date(a.dateTimeOriginal).getTime() - new Date(b.dateTimeOriginal).getTime());
return sortedAssets.
map((p) => ({
...p,
src: p.url as string,
original: p.previewUrl as string,
width: p.exifImageWidth as number,
height: p.exifImageHeight as number,
isSelected: selectedIds.includes(p.id),
orientation: 1,
tags: [
{
title: "Immich Link",
value: (
<a href={exImmichUrl + "/photos/" + p.id} target="_blank">
Open in Immich
</a>
),
},
],
}));
}, [assets, selectedIds, sortOrder]);
const slides = useMemo(
() =>
@@ -76,20 +83,34 @@ export default function MissingLocationAssets() {
const handleClick = (idx: number) => setIndex(idx);
const handleSelect = (_idx: number, asset: IAsset) => {
const handleSelect = (_idx: number, asset: IAsset, event: MouseEvent<HTMLElement>) => {
event.stopPropagation();
const isPresent = selectedIds.includes(asset.id);
if (isPresent) {
updateContext({
selectedIds: selectedIds.filter((id) => id !== asset.id),
});
} else {
updateContext({ selectedIds: [...selectedIds, asset.id] });
const clickedIndex = images.findIndex((image) => {
return image.id === asset.id;
});
if (event.shiftKey) {
const startIndex = Math.min(clickedIndex, lastSelectedIndex);
const endIndex = Math.max(clickedIndex, lastSelectedIndex);
const newSelectedIds = images.slice(startIndex, endIndex + 1).map((image) => image.id);
const allSelectedIds = [...selectedIds, ...newSelectedIds];
const uniqueSelectedIds = [...new Set(allSelectedIds)];
updateContext({ selectedIds: uniqueSelectedIds });
} else {
updateContext({ selectedIds: [...selectedIds, asset.id] });
}
setLastSelectedIndex(clickedIndex);
}
};
useEffect(() => {
if (startDate) fetchAssets();
}, [startDate]);
if (startDate || albumId) fetchAssets();
}, [startDate, albumId]);
if (loading)
return (
@@ -99,7 +120,7 @@ export default function MissingLocationAssets() {
</div>
);
if (!startDate)
if (!startDate && !albumId)
return (
<div className="flex flex-col gap-2 h-full justify-center items-center w-full">
<CalendarArrowUp />
@@ -8,12 +8,13 @@ import React, { useEffect, useMemo, useRef } from "react";
interface IProps {
record: IMissingLocationDatesResponse;
onSelect: (date: string) => void;
groupBy: "date" | "album";
}
export default function MissingLocationDateItem({ record, onSelect }: IProps) {
export default function MissingLocationDateItem({ record, onSelect, groupBy }: IProps) {
// Effect to handle scrolling after rendering
useEffect(() => {
if (startDate === record.date) {
if (startDate === record.label) {
itemsRef.current?.scrollIntoView({
behavior: "smooth", // Smooth scrolling
block: "center", // Center the item in the view
@@ -23,22 +24,31 @@ export default function MissingLocationDateItem({ record, onSelect }: IProps) {
const itemsRef = useRef<HTMLDivElement | null>(null);
const { startDate } = useMissingLocationContext()
const dateLabel = useMemo(() => {
if (!record.date) return "Unknown"
return formatDate(parseDate(record.date, "yyyy-MM-dd").toISOString(), "do MMM yyyy")
}, [record.date])
if (groupBy === "album") {
return record.label
}
if (!record.label) return "Unknown"
try {
return formatDate(parseDate(record.label, "yyyy-MM-dd").toISOString(), "do MMM yyyy")
} catch (e) {
return record.label
}
}, [record.label, groupBy])
return (
<div
role="button"
onClick={() => onSelect(record.date)}
key={record.date}
onClick={() => onSelect(record.value)}
key={record.label}
className={
cn("flex gap-1 flex-col p-2 py-1 rounded-lg hover:dark:bg-zinc-800 border border-transparent hover:bg-zinc-100 px-4",
startDate === record.date ? "bg-zinc-100 dark:bg-zinc-800 border-gray-300 dark:border-zinc-700" : "")
cn("flex gap-1 flex-col p-1 rounded-lg hover:dark:bg-zinc-800 border border-transparent hover:bg-zinc-100",
startDate === record.label ? "bg-zinc-100 dark:bg-zinc-800 border-gray-300 dark:border-zinc-700" : "")
}
ref={itemsRef}
>
<p className="font-mono text-sm">{dateLabel}</p>
<p className="text-sm truncate">{dateLabel}</p>
<p className="text-xs text-foreground/50">{record.asset_count} Orphan Assets</p>
</div>
);
@@ -1,6 +1,6 @@
import React, { use, useEffect, useState } from "react";
import { usePotentialAlbumContext } from "@/contexts/PotentialAlbumContext";
import { IMissingLocationDatesResponse, listMissingLocationDates } from "@/handlers/api/asset.handler";
import { IMissingLocationDatesResponse, listMissingLocationAlbums, listMissingLocationDates } from "@/handlers/api/asset.handler";
import MissingLocationDateItem from "./MissingLocationDateItem";
import { useMissingLocationContext } from "@/contexts/MissingLocationContext";
import { useRouter } from "next/router";
@@ -8,7 +8,11 @@ import { Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectTrig
import { Button } from "@/components/ui/button";
import { SortAsc, SortDesc } from "lucide-react";
export default function MissingLocationDates() {
interface IMissingLocationDatesProps {
groupBy: string;
}
export default function MissingLocationDates({ groupBy }: IMissingLocationDatesProps) {
const { updateContext } = useMissingLocationContext();
const router = useRouter();
const [dateRecords, setDateRecords] = React.useState<
@@ -20,7 +24,9 @@ export default function MissingLocationDates() {
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const fetchData = async () => {
return listMissingLocationDates({
const func = groupBy === "album" ? listMissingLocationAlbums : listMissingLocationDates
setDateRecords([])
return func({
sortBy: filters.sortBy,
sortOrder: filters.sortOrder,
})
@@ -30,23 +36,41 @@ export default function MissingLocationDates() {
};
const handleSelect = (date: string) => {
updateContext({ startDate: date });
router.push({
pathname: router.pathname,
query: { startDate: date },
});
if (groupBy === "album") {
updateContext({ albumId: date });
router.push({
pathname: router.pathname,
query: {
...router.query,
albumId: date,
groupBy: "album",
startDate: undefined
},
});
} else {
updateContext({ startDate: date });
router.push({
pathname: router.pathname,
query: {
...router.query,
startDate: date,
groupBy: "date",
albumId: undefined
},
});
}
};
useEffect(() => {
fetchData();
}, [filters]);
}, [filters, groupBy]);
return (
<div className="overflow-y-auto min-w-[200px] py-4 max-h-[calc(100vh-60px)] min-h-[calc(100vh-60px)] dark:bg-zinc-900 bg-gray-200 flex flex-col gap-2 px-2">
<div className="min-w-[200px] max-w-[200px] sticky top-0 py-4 max-h-[calc(100vh-60px)] min-h-[calc(100vh-60px)] border-r border-gray-200 dark:border-zinc-800 flex flex-col gap-2 px-2">
<div className="flex justify-between items-center gap-2">
<Select
{groupBy === "album" ? (
<p className="text-sm text-gray-500 dark:text-zinc-400">Asset Count</p>
) : (<Select
defaultValue={filters.sortBy}
onValueChange={(value) => setFilters({ ...filters, sortBy: value })}
>
@@ -60,21 +84,27 @@ export default function MissingLocationDates() {
<SelectItem value="asset_count">Asset Count</SelectItem>
</SelectGroup>
</SelectContent>
</Select>
</Select>)}
<div>
<Button variant="default" size="sm" onClick={() => setFilters({ ...filters, sortOrder: filters.sortOrder === "asc" ? "desc" : "asc" })}>
<Button variant="ghost" size="sm" onClick={() =>
setFilters({
...filters,
sortOrder: filters.sortOrder === "asc" ? "desc" : "asc"
})}>
{filters.sortOrder === "asc" ? <SortAsc size={16} /> : <SortDesc size={16} />}
</Button>
</div>
</div>
{dateRecords.map((record) => (
<MissingLocationDateItem
key={record.date}
record={record}
onSelect={handleSelect}
/>
))}
<div className="overflow-y-auto flex flex-col gap-2">
{dateRecords.map((record) => (
<MissingLocationDateItem
key={record.value}
record={record}
groupBy={groupBy as "date" | "album"}
onSelect={handleSelect}
/>
))}
</div>
</div>
);
}
@@ -12,8 +12,8 @@ import { IPlace } from "@/types/common";
import React, { useState } from "react";
import TagMissingLocationSearchAndAdd from "./TagMissingLocationSearchAndAdd";
import TagMissingLocationSearchLatLong from "./TagMissingLocationSearchLatLong";
import { MapPinCheck } from "lucide-react";
import dynamic from "next/dynamic";
import { useMissingLocationContext } from "@/contexts/MissingLocationContext";
const LazyMap = dynamic(() => import("./Map"), {
ssr: false
@@ -25,19 +25,19 @@ interface ITagMissingLocationDialogProps {
export default function TagMissingLocationDialog({
onSubmit,
}: ITagMissingLocationDialogProps) {
const {selectedIds} = useMissingLocationContext();
const [open, setOpen] = useState(false);
const [mapPosition,setMapPosition] = useState<IPlace>({
latitude: 48.0,
longitude: 16.0,
name: "home1"
name: "home"
});
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button>Tag Missing Location</Button>
<DialogTrigger asChild >
<Button size={"sm"} disabled={selectedIds.length === 0}>Tag Location</Button>
</DialogTrigger>
<DialogContent className="!w-[600px] !max-w-[600px]">
<DialogHeader>
@@ -46,12 +46,11 @@ export default function TagMissingLocationDialog({
Tagging a location will add the location to the selected assets.
</DialogDescription>
</DialogHeader>
<Tabs defaultValue="search" className="border rounded-lg">
<TabsList className="flex justify-between">
<Tabs defaultValue="search">
<TabsList className="flex justify-center">
<TabsTrigger value="search">Search and Pick</TabsTrigger>
<TabsTrigger value="latlong">
Latitude and Longitude
Lat & Long
</TabsTrigger>
<TabsTrigger value="maps">Map</TabsTrigger>
</TabsList>
@@ -63,7 +62,7 @@ export default function TagMissingLocationDialog({
onOpenChange={setOpen} location={mapPosition} onLocationChange={setMapPosition} />
</TabsContent>
<TabsContent value="maps">
<div className="py-10 flex flex-col gap-6 items-center ">
<div className="flex flex-col gap-6 items-center ">
<LazyMap location={mapPosition} onLocationChange={setMapPosition} />
</div>
</TabsContent>
@@ -110,7 +110,7 @@ export default function TagMissingLocationSearchLatLong(
return (
<div className="flex flex-col gap-4 py-4 px-2">
<div className="flex items-start gap-2">
<div className="flex flex-col gap-2">
<div className="flex flex-col gap-2 flex-1">
<Label>Latitude</Label>
<Input
placeholder="Latitude"
@@ -121,7 +121,7 @@ export default function TagMissingLocationSearchLatLong(
onBlur={(e) => handleBlur()}
/>
</div>
<div className="flex flex-col gap-2">
<div className="flex flex-col gap-2 flex-1">
<Label>
Longitude
</Label>
+52
View File
@@ -0,0 +1,52 @@
import React, { useState } from 'react'
import inputStyle from './findInputStyle'
import { MentionsInput, Mention } from 'react-mentions'
import { searchPeople } from '@/handlers/api/people.handler';
import mentionStyle from './findMentionStyle';
import classNames from './FindInput.module.css';
interface FindInputProps {
onSearch: (query: string) => void;
}
export default function FindInput({ onSearch }: FindInputProps) {
const [query, setQuery] = useState("");
const handleSearchPeople = async (e: any, callback: any) => {
if (!e.length) return [];
return searchPeople(e).then((people) => people.map((person: any) => ({
id: person.id,
display: person.name,
}))).then((people) => callback(people));
}
return (
<MentionsInput
value={query}
singleLine={true}
placeholder='Search for photos, use @ to search for people'
style={inputStyle}
onKeyDown={(e) => {
if (e.key === 'Enter') {
onSearch(query);
}
}}
onChange={(e) => setQuery(e.target.value)}>
<Mention
trigger="@"
style={mentionStyle}
data={handleSearchPeople}
renderSuggestion={(
highlightedDisplay,
focused
) => (
<div className={`user ${focused ? 'focused' : ''} `}>
{highlightedDisplay.display}
</div>
)}
/>
</MentionsInput>
)
}
+45
View File
@@ -0,0 +1,45 @@
const findInputStyle = {
control: {
backgroundColor: 'hsl(var(--input))',
fontSize: 20,
fontWeight: 'normal',
outline: 'none',
borderRadius: '15px',
},
'&singleLine': {
// display: 'inline-block',
width: '100%',
highlighter: {
padding: '10px 15px',
border: 'none',
outline: 'none',
},
input: {
padding: '10px 15px',
border: 'none',
outline: 'none',
},
},
suggestions: {
list: {
backgroundColor: 'hsl(var(--background))',
fontSize: 14,
border: '1px solid hsl(var(--border))',
overflow: 'hidden',
},
item: {
padding: '5px 15px',
border: 'none',
'&focused': {
backgroundColor: 'hsl(var(--chart-2))',
},
},
},
}
export default findInputStyle;
+6
View File
@@ -0,0 +1,6 @@
const mentionStyle: React.CSSProperties = {
backgroundColor: 'hsla(var(--chart-2) / 0.3)',
position: 'relative',
}
export default mentionStyle;
+2 -2
View File
@@ -23,11 +23,11 @@ export default function PageLayout({ children, className, title }: IProps) {
: children;
return (
<div>
<div className="flex flex-col w-full h-full">
{header}
<main
className={cn(
"flex flex-1 max-h-[calc(100vh-60px)] flex-col gap-4 overflow-y-auto mx-auto",
"flex flex-1 max-h-[calc(100vh-60px)] flex-col gap-4 overflow-y-auto mx-auto w-full",
{
"mb-14": !!header,
},
+14 -5
View File
@@ -1,6 +1,5 @@
import { IUser } from "@/types/user";
import Sidebar from "../shared/Sidebar";
import { Toaster } from "../ui/toaster";
import { ReactNode, useEffect, useState } from "react";
import { getMe } from "@/handlers/api/user.handler";
import UserContext from "@/contexts/CurrentUserContext";
@@ -10,8 +9,9 @@ import { ArrowRight, TriangleAlert } from "lucide-react";
import Link from "next/link";
import { LoginForm } from "../auth/LoginForm";
import { useConfig } from "@/contexts/ConfigContext";
import { queryClient } from "@/config/rQuery";
import { QueryClientProvider } from "react-query";
import { Toaster } from "react-hot-toast";
import { useRouter } from "next/router";
import PageLayout from "./PageLayout";
type RootLayoutProps = {
children: ReactNode;
@@ -20,6 +20,8 @@ type RootLayoutProps = {
export default function RootLayout({ children }: RootLayoutProps) {
const { immichURL, exImmichUrl } = useConfig();
const router = useRouter();
const { pathname } = router;
const [user, setUser] = useState<IUser | null>(null);
const [loading, setLoading] = useState(true);
const [errorMessage, setErrorMessage] = useState<{
@@ -84,10 +86,18 @@ export default function RootLayout({ children }: RootLayoutProps) {
</div>
);
if (pathname.startsWith("/s/")) {
return (
<div className="grid max-h-screen min-h-screen w-full">
<div className="flex flex-col">{children}</div>
<Toaster />
</div>
)
}
if (!user) return <LoginForm onLogin={handleLoginCompletion} />;
return (
<QueryClientProvider client={queryClient}>
<UserContext.Provider value={{
...user,
updateContext: setUser,
@@ -98,6 +108,5 @@ export default function RootLayout({ children }: RootLayoutProps) {
<Toaster />
</div>
</UserContext.Provider>
</QueryClientProvider>
);
}
+10 -2
View File
@@ -14,12 +14,11 @@ import {
} from "../ui/dropdown-menu";
import { Input } from "../ui/input";
import { IPersonListFilters } from "@/handlers/api/people.handler";
import AssetFilter from "../shared/common/AssetFilter";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../ui/select";
export function PeopleFilters() {
const router = useRouter();
const { updateContext, page, maximumAssetCount, type = "all" } = usePeopleFilterContext();
const { updateContext, page, maximumAssetCount, type = "all", query ="" } = usePeopleFilterContext();
const handleChange = (data: Partial<IPersonListFilters>) => {
updateContext(data);
@@ -40,6 +39,15 @@ export function PeopleFilters() {
return (
<div className="flex gap-2">
<Input
type="text"
placeholder="Search by name"
className="w-max"
defaultValue={query}
onChange={(e) => {
handleChange({ query: e.target.value });
}}
/>
<Input
type="number"
placeholder="Max Asset Count"
+2
View File
@@ -11,6 +11,7 @@ import { useConfig } from "@/contexts/ConfigContext";
import { useToast } from "../ui/use-toast";
import { Badge } from "../ui/badge";
import { Button } from "@/components/ui/button";
import ShareAssetsTrigger from "../shared/ShareAssetsTrigger";
interface IProps {
person: IPerson;
onRemove: (person: IPerson) => void;
@@ -108,6 +109,7 @@ export default function PersonItem({ person, onRemove }: IProps) {
}}>
Hide
</Button>
<ShareAssetsTrigger filters={{ personIds: [person.id] }} buttonProps={{ variant: "outline", className: "!py-0.5 !px-2 text-xs h-7" }} />
</div>
</div>
{!editMode ? (
+114
View File
@@ -0,0 +1,114 @@
import "yet-another-react-lightbox/styles.css";
import { IAsset } from '@/types/asset';
import React, { useEffect, useMemo, useState } from 'react'
import Lightbox from 'yet-another-react-lightbox';
import { Gallery } from "react-grid-gallery";
import LazyGridImage from "../ui/lazy-grid-image";
import Download from "yet-another-react-lightbox/plugins/download";
interface AssetGridProps {
assets: IAsset[];
isInternal?: boolean;
selectable?: boolean;
onSelectionChange?: (ids: string[]) => void;
}
export default function AssetGrid({ assets, isInternal = true, selectable = false, onSelectionChange }: AssetGridProps) {
const [index, setIndex] = useState(-1);
const [selectedIds, setSelectedIds] = useState<string[]>([]);
const [lastSelectedIndex, setLastSelectedIndex] = useState(-1);
const handleSelect = (_idx: number, asset: IAsset, event: React.MouseEvent<HTMLElement>) => {
event.stopPropagation();
const isPresent = selectedIds.includes(asset.id);
if (isPresent) {
setSelectedIds(selectedIds.filter((id) => id !== asset.id));
onSelectionChange?.(selectedIds.filter((id) => id !== asset.id));
} else {
const clickedIndex = images.findIndex((image) => {
return image.id === asset.id;
});
if (event.shiftKey) {
const startIndex = Math.min(clickedIndex, lastSelectedIndex);
const endIndex = Math.max(clickedIndex, lastSelectedIndex);
const newSelectedIds = images.slice(startIndex, endIndex + 1).map((image) => image.id);
const allSelectedIds = [...selectedIds, ...newSelectedIds];
const uniqueSelectedIds = [...new Set(allSelectedIds)];
setSelectedIds(uniqueSelectedIds);
onSelectionChange?.(uniqueSelectedIds);
} else {
setSelectedIds([...selectedIds, asset.id]);
onSelectionChange?.([...selectedIds, asset.id]);
}
setLastSelectedIndex(clickedIndex);
}
};
const slides = useMemo(() => {
return assets.map((asset) => ({
...asset,
orientation: 1,
src: asset.previewUrl as string,
type: (asset.type === "VIDEO" ? "video" : "image") as any,
sources:
asset.type === "VIDEO"
? [
{
src: asset.downloadUrl as string,
type: "video/mp4",
},
]
: undefined,
height: asset.exifImageHeight as number,
width: asset.exifImageWidth as number,
downloadUrl: asset.downloadUrl as string,
}));
}, [assets]);
const images = useMemo(() => {
return assets.map((p) => ({
...p,
src: p.url as string,
original: p.previewUrl as string,
width: p.exifImageWidth / 10 as number,
height: p.exifImageHeight / 10 as number,
orientation: 1,
isSelected: selectedIds.includes(p.id),
}));
}, [assets, selectedIds]);
const handleEsc = (event: KeyboardEvent) => {
if (event.key === "Escape") {
setSelectedIds([]);
onSelectionChange?.([]);
}
};
useEffect(() => {
// Listen for esc key press and unselect all images
window.addEventListener("keydown", handleEsc);
return () => window.removeEventListener("keydown", handleEsc);
}, [images]);
return (
<div>
<Lightbox
slides={slides}
plugins={[Download]}
open={index >= 0}
index={index}
close={() => setIndex(-1)}
/>
<Gallery
images={images}
onClick={setIndex}
enableImageSelection={selectable}
thumbnailImageComponent={LazyGridImage}
onSelect={handleSelect}
/>
</div>
);
}
@@ -0,0 +1,36 @@
import React, { useMemo } from 'react'
import { Button } from '../ui/button';
import { AlertDialog } from '../ui/alert-dialog';
import { deleteAssets } from '@/handlers/api/asset.handler';
interface AssetsBulkDeleteButtonProps {
selectedIds: string[];
onDelete: (ids: string[]) => void;
}
export default function AssetsBulkDeleteButton({ selectedIds, onDelete }: AssetsBulkDeleteButtonProps) {
const ids = useMemo(() => {
return selectedIds
}, [selectedIds]);
const handleDelete = () => {
return deleteAssets(ids).then(() => {
onDelete(ids);
})
}
return (
<AlertDialog
title="Delete the selected assets?"
description="This action will delete the selected assets and cannot be undone."
onConfirm={handleDelete}
disabled={ids.length === 0}
>
<Button variant={"destructive"} size={"sm"} disabled={ids.length === 0}>
Delete
</Button>
</AlertDialog>
)
}
+16
View File
@@ -0,0 +1,16 @@
import { Button } from '@/components/ui/button'
import React from 'react'
interface FloatingBarProps {
children: React.ReactNode;
}
export default function FloatingBar({ children }: FloatingBarProps) {
return (
<div className='absolute bottom-10 left-0 right-0'>
<div className='max-w-2xl mx-auto py-2 px-2 rounded-lg flex justify-between items-center bg-white dark:bg-zinc-900 border-t border-zinc-200 dark:border-zinc-800 border'>
{children}
</div>
</div>
)
}
+4 -1
View File
@@ -23,6 +23,7 @@ import Head from "next/head";
import { sidebarNavs } from "@/config/constants/sidebarNavs";
import { cn } from "@/lib/utils";
import { useRouter } from "next/router";
import clsx from "clsx";
interface IProps {
leftComponent?: React.ReactNode | string;
@@ -62,7 +63,9 @@ export default function Header({ leftComponent, rightComponent, title }: IProps)
<title>{pageTitle} - Immich Power Tools</title>
</Head>
)}
<header key="header" className="sticky z-10 top-0 w-full flex h-14 items-center gap-4 border-b bg-white dark:bg-black px-4 lg:h-[60px] lg:px-6">
<header key="header" className={
clsx("sticky z-10 top-0 w-full flex h-14 items-center gap-4 border-b bg-white dark:bg-black px-4 lg:h-[60px] lg:px-6")
}>
<Sheet>
<SheetTrigger asChild>
<Button variant="outline" size="icon" className="shrink-0 md:hidden">
+48
View File
@@ -0,0 +1,48 @@
import React, { useCallback } from 'react'
import { IPerson } from '@/types/person';
import { cn } from '@/lib/utils';
import LazyImage from '../ui/lazy-image';
import { PERSON_THUBNAIL_PATH } from '@/config/routes';
interface PeopleListProps {
people: IPerson[];
onSelect: (person: IPerson) => void;
selectedIds?: string[];
}
export default function PeopleList({ people, onSelect, selectedIds }: PeopleListProps) {
const isSelected = useCallback((person: IPerson) => {
return selectedIds?.includes(person.id)
}, [selectedIds])
return (
<div className="flex flex-col overflow-x-hidden gap-2">
{people.map((person) => (
<div
className={cn(
'flex items-center gap-2 cursor-pointer hover:bg-gray-300 dark:hover:bg-gray-700 rounded-md p-1',
isSelected(person) ? "bg-gray-300 dark:bg-gray-700" : ""
)}
key={person.id}
onClick={() => onSelect(person)}
>
<LazyImage
role="button"
className={
cn("cursor-pointer h-10 w-10 min-w-10 rounded-full border-2",
!!person.name ? "border-green-500" : "border-gray-500",
)
}
src={person.thumbnailPath} alt={person.name} />
<div className='flex flex-col text-sm'>
<p>{person.name || "No Name"}</p>
<p className={
cn("text-xs text-gray-500 dark:text-gray-400")
}>{person.assetCount} photos</p>
</div>
</div>
))}
</div>
)
}
+1 -1
View File
@@ -44,7 +44,7 @@ export default function ProfileInfo() {
</>
)}
</div>
<div className="border text-muted-foreground text-xs py-2 flex justify-between items-center px-2">
<div className="border-t text-muted-foreground text-xs py-2 flex justify-between items-center px-2">
<p>
Made with <span className="text-red-500">&hearts;</span> by{" "}
<Link
@@ -0,0 +1,116 @@
import React, { useState } from 'react'
import { Dialog, DialogTitle, DialogContent, DialogHeader, DialogTrigger, DialogDescription } from '../ui/dialog';
import { Button, ButtonProps } from '../ui/button';
import { ShareLinkFilters } from '@/types/shareLink';
import { generateShareLink } from '@/handlers/api/shareLink.handler';
import { Input } from '../ui/input';
import { Label } from '@radix-ui/react-label';
import { Switch } from '../ui/switch';
import { Select, SelectValue, SelectContent, SelectItem, SelectTrigger } from '../ui/select';
interface ShareAssetsTriggerProps {
filters: ShareLinkFilters
buttonProps?: ButtonProps
}
export default function ShareAssetsTrigger({ filters, buttonProps }: ShareAssetsTriggerProps) {
const [generatedLink, setGeneratedLink] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [copied, setCopied] = useState(false);
const [config, setConfig] = useState<Partial<ShareLinkFilters>>({
expiresIn: "never"
});
const handleReset = () => {
setConfig({ expiresIn: "never" });
setGeneratedLink(null);
}
const handleGenerate = async () => {
setLoading(true);
setErrorMessage(null);
return generateShareLink({ ...filters, ...config }).then(({ link }) => {
setGeneratedLink(link);
}).catch((err) => {
setErrorMessage(err.message);
}).finally(() => {
setLoading(false);
});
}
const handleCopy = () => {
if (generatedLink) {
navigator.clipboard.writeText(generatedLink);
setCopied(true);
setTimeout(() => {
setCopied(false);
}, 2000);
}
}
return (
<Dialog>
<DialogTrigger asChild>
<Button {...buttonProps}>Share</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Share Assets</DialogTitle>
</DialogHeader>
<DialogDescription>
Generate a share link for the selected assets (either bunch of albums or bunch of people) and share it with your friends and family.
</DialogDescription>
{errorMessage && <div className="text-red-500">{errorMessage}</div>}
{generatedLink ? <div className="flex flex-col gap-2">
<Label className='text-sm'>Share Link</Label>
<Input readOnly type="text" value={generatedLink} />
<p className='text-xs text-muted-foreground'>
This is a stateless link, it will not work if you leave the page. Which means it cannot be expired.
</p>
<div className="flex gap-2">
<Button className="w-full" onClick={handleCopy}>{copied ? 'Copied' : 'Copy'}</Button>
<Button className="w-full" variant="outline" onClick={handleReset}>Generate New Link</Button>
</div>
</div> : (
<div className="flex flex-col gap-4">
<div className="flex items-center justify-between gap-1">
<div className="flex flex-col gap-1">
<Label className="text-sm m-0">Show People</Label>
<p className="text-xs text-muted-foreground m-0">
Show the list of people in the shared photos
</p>
</div>
<Switch checked={config.p} onCheckedChange={(checked) => setConfig({ ...config, p: !!checked })} />
</div>
<div className="flex items-center justify-between gap-1">
<div className="flex flex-col gap-1">
<Label className="text-sm m-0">Link Expires In</Label>
<p className="text-xs text-muted-foreground m-0">
Should the link expire after the selected time
</p>
</div>
<Select onValueChange={(value) => setConfig({ ...config, expiresIn: value })}>
<SelectTrigger className='w-fit'>
<SelectValue placeholder="Select duration" />
</SelectTrigger>
<SelectContent>
<SelectItem value="1h">1 Hour</SelectItem>
<SelectItem value="1d">1 Day (24 Hours)</SelectItem>
<SelectItem value="7d">7 Days</SelectItem>
<SelectItem value="30d">30 Days</SelectItem>
<SelectItem value="90d">90 Days</SelectItem>
<SelectItem value="never">Never Expires</SelectItem>
</SelectContent>
</Select>
</div>
<Button onClick={handleGenerate} disabled={loading}>Generate Share Link</Button>
</div>
)}
</DialogContent>
</Dialog>
)
}
-1
View File
@@ -5,7 +5,6 @@ import { cn } from "@/lib/utils";
import { useRouter } from "next/router";
import dynamic from "next/dynamic";
import Image from "next/image";
import ProfileInfo from "./ProfileInfo";
const ThemeSwitcher = dynamic(() => import("@/components/shared/ThemeSwitcher"), {
@@ -1,57 +0,0 @@
import { Combobox } from '@/components/ui/combobox';
import { getFilters } from '@/handlers/api/common.handler';
import React, { useMemo, useState } from 'react'
import { useQuery } from 'react-query';
const fields = [
"make",
"model",
"lensModel",
"city",
"state",
"country",
"projectionType",
"colorspace",
"bitsPerSample",
"rating",
];
const formattedFields = fields.map(field => ({
label: field.replace(/([A-Z])/g, ' $1').replace(/^./, str => str.toUpperCase()),
value: field
}));
export default function AssetFilter() {
const [selectedField, setSelectedField] = useState<string | null>(null);
const { data } = useQuery('filters', getFilters)
const options = useMemo(() => {
if (!selectedField) return formattedFields;
const { filters } = data;
if (!filters) return formattedFields;
const field = filters[selectedField];
if (!field) return [];
return field.map((value: string) => ({
label: value,
value
}));
}, [selectedField, data]);
return (
<Combobox
options={options}
closeOnSelect={!!selectedField}
onSelect={(value) => {
if (!selectedField) setSelectedField(value);
}}
onOpenChange={(open) => {
if (!open) setSelectedField(null);
}}
/>
)
}
+209
View File
@@ -0,0 +1,209 @@
import * as AlertDialogPrimitive from '@radix-ui/react-alert-dialog'
import * as React from 'react'
import { ButtonProps, buttonVariants } from '@/components/ui/button'
import { cn } from '@/lib/utils'
import { useImperativeHandle, useState } from 'react'
const AlertDialogRoot = AlertDialogPrimitive.Root
const AlertDialogTrigger = AlertDialogPrimitive.Trigger
const AlertDialogPortal = AlertDialogPrimitive.Portal
const AlertDialogOverlay = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Overlay
className={cn(
'fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
className
)}
{...props}
ref={ref}
/>
))
AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName
const AlertDialogContent = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content>
>(({ className, ...props }, ref) => (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
ref={ref}
className={cn(
'fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border border-gray10 bg-white dark:bg-black p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] dark:border-gray7 sm:rounded-lg',
className
)}
{...props}
/>
</AlertDialogPortal>
))
AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName
const AlertDialogHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
'flex flex-col space-y-2 text-center sm:text-left',
className
)}
{...props}
/>
)
AlertDialogHeader.displayName = 'AlertDialogHeader'
const AlertDialogFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
'flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2',
className
)}
{...props}
/>
)
AlertDialogFooter.displayName = 'AlertDialogFooter'
const AlertDialogTitle = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Title
ref={ref}
className={cn('text-lg font-semibold', className)}
{...props}
/>
))
AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName
const AlertDialogDescription = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Description
ref={ref}
className={cn('text-sm text-slate-500 dark:text-slate-400', className)}
{...props}
/>
))
AlertDialogDescription.displayName =
AlertDialogPrimitive.Description.displayName
const AlertDialogAction = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Action>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Action> & {
variant?: ButtonProps['variant']
}
>(({ className, variant, ...props }, ref) => (
<AlertDialogPrimitive.Action
ref={ref}
className={cn(buttonVariants({ variant }), className)}
{...props}
/>
))
AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName
const AlertDialogCancel = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Cancel>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Cancel>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Cancel
ref={ref}
className={cn(
buttonVariants({ variant: 'outline' }),
'mt-2 sm:mt-0',
className
)}
{...props}
/>
))
AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName
export interface INewChangelogButtonActions {
open: () => void
}
interface AlertDialogProps extends AlertDialogPrimitive.AlertDialogProps {
children: React.ReactNode
title: string
description: string
onConfirm: () => void | Promise<void>
onCancel: () => void | Promise<void>
variant?: ButtonProps['variant']
asChild?: boolean
disabled?: boolean
}
const AlertDialog = React.forwardRef<INewChangelogButtonActions, Partial<AlertDialogProps>>(({
children,
title,
description,
onConfirm,
onCancel,
variant,
asChild,
disabled,
...props
}, ref) => {
const [loading, setLoading] = useState(false)
const [open, setOpen] = useState(false)
useImperativeHandle(ref, () => ({
open: () => setOpen(true)
}))
const handleConfirm = async () => {
setLoading(true)
if (onConfirm) {
await onConfirm()
}
setLoading(false)
setOpen(false)
}
return (
<AlertDialogRoot {...props} open={open} onOpenChange={setOpen}>
<AlertDialogTrigger disabled={disabled} asChild={asChild}>{children}</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{title}</AlertDialogTitle>
<AlertDialogDescription>{description}</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel onClick={onCancel}>Cancel</AlertDialogCancel>
<AlertDialogAction
disabled={loading || disabled}
onClick={handleConfirm}
variant={variant}
>
Confirm
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialogRoot>
)
})
AlertDialog.displayName = 'AlertDialog'
export {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogOverlay,
AlertDialogPortal,
AlertDialogTitle,
AlertDialogTrigger
}
-33
View File
@@ -1,33 +0,0 @@
import {
Toast,
ToastClose,
ToastDescription,
ToastProvider,
ToastTitle,
ToastViewport,
} from "@/components/ui/toast"
import { useToast } from "@/components/ui/use-toast"
export function Toaster() {
const { toasts } = useToast()
return (
<ToastProvider>
{toasts.map(function ({ id, title, description, action, ...props }) {
return (
<Toast key={id} {...props}>
<div className="grid gap-1">
{title && <ToastTitle>{title}</ToastTitle>}
{description && (
<ToastDescription>{description}</ToastDescription>
)}
</div>
{action}
<ToastClose />
</Toast>
)
})}
<ToastViewport />
</ToastProvider>
)
}
+19 -2
View File
@@ -1,6 +1,16 @@
import { Album, GalleryHorizontal, GalleryVerticalEnd, Home, Image, LocateOff, MapPinX, User } from "lucide-react";
import { GalleryHorizontal, GalleryVerticalEnd, Image as ImageIcon, MapPin, MapPinX, Rewind, Search, User } from "lucide-react";
export const sidebarNavs = [
{
title: "Rewind 2024",
link: "/rewind",
icon: <Rewind className="h-4 w-4" />,
},
{
title: "Find",
link: "/find",
icon: <Search className="h-4 w-4" />,
},
{
title: "Manage People",
link: "/",
@@ -9,7 +19,7 @@ export const sidebarNavs = [
{
title: "Analytics",
link: "/analytics/exif",
icon: <Image className="h-4 w-4" />,
icon: <ImageIcon className="h-4 w-4" />,
},
{
title: "Potential Albums",
@@ -26,4 +36,11 @@ export const sidebarNavs = [
link: "/albums",
icon: <GalleryHorizontal className="h-4 w-4" />,
},
{
title: "Geo Heatmap",
link: "/assets/geo-heatmap",
icon: <MapPin className="h-4 w-4" />,
}
];
+18 -2
View File
@@ -4,10 +4,18 @@ import { Client, Pool } from "pg";
import { ENV } from "./environment";
import * as schema from "@/schema";
import { sql } from 'drizzle-orm';
import { findMissingKeys } from '@/helpers/data.helper';
import { APIError } from '@/lib/api';
const pool = new Pool({
const pool = ENV.DATABASE_URL ? new Pool({
connectionString: ENV.DATABASE_URL,
keepAlive: true,
}) : new Pool({
user: ENV.DB_USERNAME,
password: ENV.DB_PASSWORD,
host: ENV.DB_HOST,
port: parseInt(ENV.DB_PORT),
database: ENV.DB_DATABASE_NAME,
});
class DatabaseConnectionError extends Error {
@@ -20,7 +28,15 @@ class DatabaseConnectionError extends Error {
}
export const connectDB = async (db: NodePgDatabase<typeof schema>) => {
try {
await db.execute(sql`SELECT 1`); // Execute a simple query
const missingKeys = findMissingKeys(ENV, ['DB_USERNAME', 'DB_PASSWORD', 'DB_HOST', 'DB_PORT', 'DB_DATABASE_NAME']);
if (!ENV.DATABASE_URL && missingKeys.length > 0) {
throw new APIError({
message: `Some database credentials are missing: ${missingKeys.join(', ')}. Please add them to the .env file`,
status: 500,
});
} else {
return await db.execute(sql`SELECT 1`); // Execute a simple query
}
} catch (error: any) {
throw new DatabaseConnectionError(error.message, "Database connection failed");
}
+11 -2
View File
@@ -2,10 +2,19 @@ export const ENV = {
IMMICH_URL: (process.env.IMMICH_URL || 'http://immich_server:2283') as string,
EXTERNAL_IMMICH_URL: (process.env.EXTERNAL_IMMICH_URL || process.env.IMMICH_URL) as string,
IMMICH_API_KEY: process.env.IMMICH_API_KEY as string,
DATABASE_URL: (process.env.DATABASE_URL || `postgresql://${process.env.DB_USERNAME}:${process.env.DB_PASSWORD}@${(process.env.DB_HOST || 'immich_postgres')}:${(process.env.DB_PORT || '5432')}/${process.env.DB_DATABASE_NAME}`),
DATABASE_URL: process.env.DATABASE_URL as string,
DB_USERNAME: process.env.DB_USERNAME as string,
DB_PASSWORD: process.env.DB_PASSWORD as string,
DB_HOST: process.env.DB_HOST as string,
DB_PORT: process.env.DB_PORT as string,
DB_DATABASE_NAME: process.env.DB_DATABASE_NAME as string,
JWT_SECRET: process.env.JWT_SECRET as string,
SECURE_COOKIE: process.env.SECURE_COOKIE === 'true',
VERSION: process.env.VERSION
VERSION: process.env.VERSION,
GEMINI_API_KEY: process.env.GEMINI_API_KEY as string,
GOOGLE_MAPS_API_KEY: process.env.GOOGLE_MAPS_API_KEY as string,
IMMICH_SHARE_LINK_KEY: process.env.IMMICH_SHARE_LINK_KEY as string,
POWER_TOOLS_ENDPOINT_URL: process.env.POWER_TOOLS_ENDPOINT_URL as string,
};
-5
View File
@@ -1,5 +0,0 @@
import {
QueryClient,
} from 'react-query'
export const queryClient = new QueryClient()
+23 -3
View File
@@ -21,19 +21,27 @@ export const LIST_POTENTIAL_ALBUMS_DATES_PATH = BASE_API_ENDPOINT + "/albums/pot
export const LIST_POTENTIAL_ALBUMS_ASSETS_PATH = BASE_API_ENDPOINT + "/albums/potential-albums-assets";
export const LIST_ALBUMS_PATH = BASE_API_ENDPOINT + "/albums/list";
export const ALBUM_INFO_PATH = (id: string) => BASE_API_ENDPOINT + "/albums/" + id + "/info";
export const ALBUM_PEOPLE_PATH = (id: string) => BASE_API_ENDPOINT + "/albums/" + id + "/people";
export const ALBUM_ASSETS_PATH = (id: string) => BASE_API_ENDPOINT + "/albums/" + id + "/assets";
export const ALBUM_ASSETS_PATH_PUBLIC = (id: string) => BASE_API_ENDPOINT + "/albums/" + id + "/public-assets";
export const CREATE_ALBUM_PATH = BASE_PROXY_ENDPOINT + "/albums";
export const ADD_ASSETS_ALBUMS_PATH = (id: string) => BASE_PROXY_ENDPOINT + "/albums/" + id + "/assets";
export const SHARE_ALBUMS_PATH = BASE_API_ENDPOINT + "/albums/share";
export const DELETE_ALBUMS_PATH = BASE_API_ENDPOINT + "/albums/delete";
// Assets
export const LIST_MISSING_LOCATION_DATES_PATH = BASE_API_ENDPOINT + "/assets/missing-location-dates";
export const LIST_MISSING_LOCATION_ALBUMS_PATH = BASE_API_ENDPOINT + "/assets/missing-location-albums";
export const LIST_MISSING_LOCATION_ASSETS_PATH = BASE_API_ENDPOINT + "/assets/missing-location-assets";
export const UPDATE_ASSETS_PATH = BASE_PROXY_ENDPOINT + "/assets";
export const ASSET_THUMBNAIL_PATH = (id: string) => BASE_PROXY_ENDPOINT + "/asset/thumbnail/" + id;
export const ASSET_PREVIEW_PATH = (id: string) => BASE_PROXY_ENDPOINT + "/asset/thumbnail/" + id + "?size=preview";
export const ASSET_VIDEO_PATH = (id: string) => BASE_PROXY_ENDPOINT + "/asset/video/" + id;
export const ASSET_GEO_HEATMAP_PATH = BASE_API_ENDPOINT + "/assets/geo-heatmap";
export const ASSET_SHARE_THUMBNAIL_PATH = (
{ id, size, token, isPeople }: { id: string, size: string, token: string, isPeople: boolean }
) => BASE_PROXY_ENDPOINT + "/asset/share-thumbnail/" + id + "?size=" + size + "&token=" + token + "&p=" + isPeople;
// Location
@@ -48,4 +56,16 @@ export const HEATMAP_DATA = BASE_API_ENDPOINT + "/analytics/statistics/heatmap";
export const GET_FILTERS = BASE_API_ENDPOINT + "/filters/asset-filters";
// Person
export const GET_PERSON_INFO = (personId: string) => BASE_API_ENDPOINT + "/people/" + personId + "/info";
export const GET_PERSON_INFO = (personId: string) => BASE_API_ENDPOINT + "/people/" + personId + "/info";
// Rewind
export const REWIND_STATS = BASE_API_ENDPOINT + "/rewind/stats";
// Find
export const FIND_ASSETS = BASE_API_ENDPOINT + "/find/search";
// Share Link
export const SHARE_LINK_PATH = (token: string) => BASE_API_ENDPOINT + "/share-link/" + token;
export const SHARE_LINK_GENERATE_PATH = BASE_API_ENDPOINT + "/share-link/generate";
export const SHARE_LINK_ASSETS_PATH = (token: string) => BASE_API_ENDPOINT + "/share-link/" + token + "/assets";
export const SHARE_LINK_PEOPLE_PATH = (token: string) => BASE_API_ENDPOINT + "/share-link/" + token + "/people";
+5 -1
View File
@@ -1,15 +1,19 @@
import { createContext, useContext } from "react";
interface ConfigContextType {
export interface ConfigContextType {
immichURL: string;
exImmichUrl: string;
version?: string;
geminiEnabled: boolean;
googleMapsApiKey: string;
}
const ConfigContext = createContext<ConfigContextType>({
immichURL: "",
exImmichUrl: "",
version: "",
geminiEnabled: false,
googleMapsApiKey: "",
});
export default ConfigContext;
+6
View File
@@ -3,8 +3,11 @@ import { createContext, useContext } from "react";
export interface IMissingLocationConfig {
startDate?: string;
albumId?: string;
selectedIds: string[];
assets: IAsset[];
sort: "fileOriginalDate";
sortOrder: "asc"|"desc";
}
export interface MissingLocationContext extends IMissingLocationConfig {
@@ -12,9 +15,12 @@ export interface MissingLocationContext extends IMissingLocationConfig {
}
const MissingLocationContext = createContext<MissingLocationContext>({
startDate: undefined,
albumId: undefined,
selectedIds: [],
assets: [],
updateContext: () => { },
sort:"fileOriginalDate",
sortOrder: "asc"
});
export default MissingLocationContext;
+9 -1
View File
@@ -1,4 +1,4 @@
import { ADD_ASSETS_ALBUMS_PATH, ALBUM_ASSETS_PATH, ALBUM_INFO_PATH, ALBUM_PEOPLE_PATH, CREATE_ALBUM_PATH, LIST_ALBUMS_PATH, LIST_POTENTIAL_ALBUMS_ASSETS_PATH, LIST_POTENTIAL_ALBUMS_DATES_PATH } from "@/config/routes";
import { ADD_ASSETS_ALBUMS_PATH, ALBUM_ASSETS_PATH, ALBUM_INFO_PATH, ALBUM_PEOPLE_PATH, CREATE_ALBUM_PATH, DELETE_ALBUMS_PATH, LIST_ALBUMS_PATH, LIST_POTENTIAL_ALBUMS_ASSETS_PATH, LIST_POTENTIAL_ALBUMS_DATES_PATH, SHARE_ALBUMS_PATH } from "@/config/routes";
import { cleanUpAsset } from "@/helpers/asset.helper";
import API from "@/lib/api";
import { IAlbumCreate } from "@/types/album";
@@ -45,3 +45,11 @@ export const addAssetToAlbum = async (albumId: string, assetIds: string[]) => {
export const createAlbum = async (albumData: IAlbumCreate) => {
return API.post(CREATE_ALBUM_PATH, albumData);
}
export const shareAlbums = async (albums: { albumId: string, allowDownload: boolean, allowUpload: boolean, showMetadata: boolean }[]) => {
return API.post(SHARE_ALBUMS_PATH, { albums });
}
export const deleteAlbums = async (albumIds: string[]) => {
return API.delete(DELETE_ALBUMS_PATH, { albumIds });
}
+26 -4
View File
@@ -1,6 +1,7 @@
import {
ADD_ASSETS_ALBUMS_PATH,
LIST_ALBUMS_PATH,
ASSET_GEO_HEATMAP_PATH,
FIND_ASSETS,
LIST_MISSING_LOCATION_ALBUMS_PATH,
LIST_MISSING_LOCATION_ASSETS_PATH,
LIST_MISSING_LOCATION_DATES_PATH,
UPDATE_ASSETS_PATH,
@@ -16,16 +17,25 @@ interface IMissingAssetAlbumsFilters {
sortOrder?: string;
}
export interface IMissingLocationDatesResponse {
date: string;
label: string;
asset_count: number;
value: string;
createdAt?: string;
}
export const listMissingLocationDates = async (
filters: IMissingAssetAlbumsFilters
): Promise<IMissingLocationDatesResponse[]> => {
return API.get(LIST_MISSING_LOCATION_DATES_PATH, filters);
};
export const listMissingLocationAlbums = async (
filters: IMissingAssetAlbumsFilters
): Promise<IMissingLocationDatesResponse[]> => {
return API.get(LIST_MISSING_LOCATION_ALBUMS_PATH, filters);
};
export const listMissingLocationAssets = async (
filters: IMissingAssetAlbumsFilters
): Promise<IAsset[]> => {
@@ -45,4 +55,16 @@ export interface IUpdateAssetsParams {
export const updateAssets = async (params: IUpdateAssetsParams) => {
return API.put(UPDATE_ASSETS_PATH, params);
}
export const findAssets = async (query: string) => {
return API.post(FIND_ASSETS, { query });
}
export const getAssetGeoHeatmap = async () => {
return API.get(ASSET_GEO_HEATMAP_PATH);
}
export const deleteAssets = async (ids: string[]) => {
return API.delete(UPDATE_ASSETS_PATH, { ids });
}
+6 -2
View File
@@ -1,4 +1,4 @@
import { GET_FILTERS, SEARCH_PLACES_PATH } from "@/config/routes";
import { GET_FILTERS, REWIND_STATS, SEARCH_PLACES_PATH } from "@/config/routes";
import API from "@/lib/api";
import { IPlace } from "@/types/common";
@@ -9,4 +9,8 @@ export const searchPlaces = async (name: string): Promise<IPlace[]> => {
export const getFilters = async () => {
return API.get(GET_FILTERS);
}
}
export const getRewindStats = async () => {
return API.get(REWIND_STATS);
}
+1
View File
@@ -13,6 +13,7 @@ export interface IPersonListFilters {
sort?: ISortField;
sortOrder?: "asc" | "desc";
type?: string;
query?: string;
}
export const listPeople = (filters: IPersonListFilters): Promise<IPeopleListResponse> => {
return API.get(LIST_PEOPLE_PATH, filters).then((response) => {
+25
View File
@@ -0,0 +1,25 @@
import {
SHARE_LINK_ASSETS_PATH,
SHARE_LINK_GENERATE_PATH,
SHARE_LINK_PATH,
SHARE_LINK_PEOPLE_PATH
} from "@/config/routes";
import API from "@/lib/api";
import { ShareLinkFilters } from "@/types/shareLink";
export const getShareLinkInfo = async (token: string) => {
return API.get(SHARE_LINK_PATH(token));
}
export const getShareLinkAssets = async (token: string, filters: ShareLinkFilters) => {
return API.get(SHARE_LINK_ASSETS_PATH(token), filters);
}
export const generateShareLink = async (filters: ShareLinkFilters) => {
return API.post(SHARE_LINK_GENERATE_PATH, filters);
}
export const getShareLinkPeople = async (token: string) => {
return API.get(SHARE_LINK_PEOPLE_PATH(token));
}
+19 -1
View File
@@ -1,6 +1,7 @@
import { appConfig } from "@/config/app.config"
import { connectDB, db } from "@/config/db"
import { ENV } from "@/config/environment"
import { APIError } from "@/lib/api"
import { getCookie } from "@/lib/cookie"
import { NextApiRequest } from "next"
@@ -22,7 +23,19 @@ export const getCurrentUserFromAPIKey = () => {
}
})
}
return null
throw new APIError({
message: "Invalid API key. Please check your API key variable `IMMICH_API_KEY` in the .env file",
status: 403,
});
})
.catch((error) => {
if (error instanceof APIError) {
throw error;
}
throw new APIError({
message: "Failed to connect to Immich API: " + ENV.IMMICH_URL,
status: 500,
});
})
}
@@ -37,6 +50,11 @@ export const getCurrentUserFromAccessToken = (token: string) => {
return res.json()
}
return null
}).catch((error) => {
throw new APIError({
message: "Failed to connect to Immich API: " + ENV.IMMICH_URL,
status: 500,
});
})
}
+30 -4
View File
@@ -1,6 +1,4 @@
import { ASSET_PREVIEW_PATH, ASSET_THUMBNAIL_PATH, ASSET_VIDEO_PATH, PERSON_THUBNAIL_PATH } from "@/config/routes"
import { IPerson } from "@/types/person"
import { parseDate } from "./date.helper"
import { ASSET_PREVIEW_PATH, ASSET_SHARE_THUMBNAIL_PATH, ASSET_THUMBNAIL_PATH, ASSET_VIDEO_PATH, PERSON_THUBNAIL_PATH } from "@/config/routes"
import { IAsset } from "@/types/asset"
@@ -11,4 +9,32 @@ export const cleanUpAsset = (asset: IAsset): IAsset => {
previewUrl: ASSET_PREVIEW_PATH(asset.id),
videoURL: ASSET_VIDEO_PATH(asset.id),
}
}
}
export const cleanUpShareAsset = (asset: IAsset, token: string): IAsset => {
return {
...asset,
url: ASSET_SHARE_THUMBNAIL_PATH({ id: asset.id, size: "thumbnail", token, isPeople: false }),
downloadUrl: ASSET_SHARE_THUMBNAIL_PATH({ id: asset.id, size: "original", token, isPeople: false }),
previewUrl: ASSET_SHARE_THUMBNAIL_PATH({ id: asset.id, size: "preview", token, isPeople: false }),
videoURL: ASSET_SHARE_THUMBNAIL_PATH({ id: asset.id, size: "video", token, isPeople: false }),
}
}
export const cleanUpAssets = (assets: IAsset[]): IAsset[] => {
return assets.map(cleanUpAsset);
}
function isRotated90CW(orientation: number) {
return orientation === 5 || orientation === 6 || orientation === 90;
}
function isRotated270CW(orientation: number) {
return orientation === 7 || orientation === 8 || orientation === -90;
}
export function isFlipped(orientation?: string | null) {
const value = Number(orientation);
return value && (isRotated270CW(value) || isRotated90CW(value));
}
+19
View File
@@ -3,4 +3,23 @@ export const stringToBoolean = (value: string | boolean): boolean => {
return value;
}
return value === 'true';
}
export const removeNullOrUndefinedProperties = (obj: any) => {
return Object.fromEntries(Object.entries(obj).filter(([_, v]) => {
if (Array.isArray(v)) {
return v.length > 0;
}
if (typeof v === 'number') {
return v !== null && v !== undefined && v !== 0;
}
return v !== null && v !== undefined && v !== '' && v !== 'null' && v !== 'undefined' && v !== 'null' && v !== 'undefined'
}));
}
export const findMissingKeys = (obj: any, keys: string[]) => {
return keys.filter((key) => !(key in obj) || obj[key] === '' || obj[key] === null || obj[key] === undefined);
}
+88
View File
@@ -0,0 +1,88 @@
import { ENV } from "@/config/environment";
import { GoogleGenerativeAI, SchemaType } from "@google/generative-ai";
import { z } from "zod";
import { removeNullOrUndefinedProperties } from "./data.helper";
const gemini = new GoogleGenerativeAI(ENV.GEMINI_API_KEY);
const model = gemini.getGenerativeModel({ model: "gemini-1.5-flash" });
interface FindQuery {
query: string;
personIds?: string[];
city?: string;
size?: number;
model?: string;
createdAfter?: string;
state?: string;
}
const responseSchema = {
type: SchemaType.OBJECT,
properties: {
query: { type: SchemaType.STRING, description: "Gist of the query. Remove the details of tags" },
personIds: { type: SchemaType.ARRAY,
description: "List of person ids that match the query which starts with @",
items: { type: SchemaType.STRING }
},
city: { type: SchemaType.STRING,
description: "City of the query"
},
size: {
type: SchemaType.INTEGER,
description: "Size of the file in bytes"
},
country: {
type: SchemaType.STRING,
description: "Any reference to a country (United States, Canada, etc) in the query, return full country name"
},
state: {
type: SchemaType.STRING,
description: "Any reference to a state (California, New York, etc) in the query"
},
takenAfter: {
type: SchemaType.STRING,
description: "Extract the date from the query and return it in the format YYYY-MM-DD but only if it is a valid date"
},
takenBefore: {
type: SchemaType.STRING,
description: "Extract the date from the query and return it in the format YYYY-MM-DD but only if it is a valid date"
},
model: {
type: SchemaType.STRING,
description: "Name of the device that the query is about"
},
},
required: ["query"],
};
export const parseFindQuery = async (query: string): Promise<FindQuery> => {
const prompt = `
Parse the following query and return the query and tags: ${query}.
Dont include any information that are not intentionally provided in the query.
Additional Information For Parsing:
today's date is ${new Date().toISOString().split('T')[0]}
`;
const { response } = await model.generateContent({
contents: [
{
role: "user",
parts: [
{
text: prompt,
},
],
},
],
generationConfig: {
responseMimeType: "application/json",
responseSchema,
}
});
const parsedResponse = JSON.parse(response.text()) as FindQuery;
const cleanedResponse = {
...parsedResponse
};
return removeNullOrUndefinedProperties(cleanedResponse) as any as FindQuery;
}
+10 -4
View File
@@ -1,7 +1,11 @@
import { ENV } from "@/config/environment"
import { IUser } from "@/types/user"
export const getUserHeaders = (user: IUser, otherHeaders?: {
export const getUserHeaders = (user: {
isUsingAPIKey?: boolean,
isUsingShareKey?: boolean,
accessToken?: string
}, otherHeaders?: {
'Content-Type': string
}) => {
let headers: {
@@ -11,11 +15,13 @@ export const getUserHeaders = (user: IUser, otherHeaders?: {
} = {
'Content-Type': 'application/json',
}
if (user.isUsingAPIKey) {
if (user.isUsingShareKey) {
headers['x-api-key'] = ENV.IMMICH_SHARE_LINK_KEY
} else if (user.isUsingAPIKey) {
headers['x-api-key'] = ENV.IMMICH_API_KEY
}
else {
} else {
headers['Authorization'] = `Bearer ${user.accessToken}`
}
return {...headers, ...otherHeaders}
}
+15 -2
View File
@@ -2,6 +2,21 @@ import type { AxiosError, AxiosRequestConfig, Method } from 'axios'
import axios from 'axios'
import qs from 'qs'
export class APIError extends Error {
status: number;
constructor({
message,
status,
}: {
message: string;
status: number;
}) {
super(message);
this.name = 'APIError';
this.message = message;
this.status = status;
}
}
const handleErrors = (error: AxiosError | any) => {
@@ -26,8 +41,6 @@ const handleErrors = (error: AxiosError | any) => {
}
export default class API {
static setBaseURL(url: string) {
if (url) {
axios.defaults.baseURL = url
+10
View File
@@ -0,0 +1,10 @@
import React from 'react'
export default function FourOFour() {
return (
<div className="flex flex-col items-center justify-center h-screen">
<h1 className="text-4xl font-bold">404</h1>
<p className="text-lg text-muted-foreground">Page not found</p>
</div>
)
}
+5 -7
View File
@@ -3,14 +3,10 @@ import "@/styles/globals.scss";
import type { AppProps } from "next/app";
import { ThemeProvider } from "next-themes";
import { ENV } from "@/config/environment";
import ConfigContext from "@/contexts/ConfigContext";
import ConfigContext, { ConfigContextType } from "@/contexts/ConfigContext";
import { useRef } from "react";
interface AppPropsWithProps extends AppProps {
props: {
immichURL: string;
exImmichUrl: string;
version?: string;
};
props: ConfigContextType;
}
const App = ({ Component, pageProps, ...props }: AppPropsWithProps) => {
const intialData = useRef(props.props);
@@ -32,7 +28,9 @@ App.getInitialProps = async () => {
props: {
exImmichUrl: ENV.EXTERNAL_IMMICH_URL,
immichURL: ENV.IMMICH_URL,
version: ENV.VERSION
version: ENV.VERSION,
geminiEnabled: !!ENV.GEMINI_API_KEY?.length,
googleMapsApiKey: ENV.GOOGLE_MAPS_API_KEY,
},
};
};
+3 -7
View File
@@ -1,20 +1,16 @@
import { ASSET_THUMBNAIL_PATH } from '@/config/routes'
import PageLayout from '@/components/layouts/PageLayout'
import Header from '@/components/shared/Header'
import Loader from '@/components/ui/loader'
import { useConfig } from '@/contexts/ConfigContext'
import { getAlbumInfo, listAlbums } from '@/handlers/api/album.handler'
import { getAlbumInfo } from '@/handlers/api/album.handler'
import { IAlbum } from '@/types/album'
import Image from 'next/image'
import Link from 'next/link'
import React, { useEffect, useState } from 'react'
import AlbumThumbnail from '@/components/albums/list/AlbumThumbnail'
import { Button } from '@/components/ui/button'
import { useRouter } from 'next/router'
import AlbumPeople from '@/components/albums/info/AlbumPeople'
import AlbumImages from '@/components/albums/info/AlbumImages'
import { Camera, ExternalLink, LinkIcon, Users } from 'lucide-react'
import { humanizeNumber, pluralize } from '@/helpers/string.helper'
import { Camera, ExternalLink, Users } from 'lucide-react'
import { humanizeNumber } from '@/helpers/string.helper'
export default function AlbumListPage() {
const { exImmichUrl } = useConfig()
+71 -19
View File
@@ -1,20 +1,19 @@
import { ASSET_THUMBNAIL_PATH } from '@/config/routes'
import PageLayout from '@/components/layouts/PageLayout'
import Header from '@/components/shared/Header'
import Loader from '@/components/ui/loader'
import { useConfig } from '@/contexts/ConfigContext'
import { listAlbums } from '@/handlers/api/album.handler'
import { deleteAlbums, listAlbums } from '@/handlers/api/album.handler'
import { IAlbum } from '@/types/album'
import Image from 'next/image'
import Link from 'next/link'
import React, { useEffect, useMemo, useState } from 'react'
import React, { useEffect, useMemo, useRef, useState } from 'react'
import AlbumThumbnail from '@/components/albums/list/AlbumThumbnail'
import { Button } from '@/components/ui/button'
import { Select, SelectItem, SelectContent, SelectTrigger, SelectValue } from '@/components/ui/select'
import { useRouter } from 'next/router'
import { ChevronDownIcon, ChevronUpIcon } from '@radix-ui/react-icons'
import { SortAsc, SortDesc } from 'lucide-react'
import { Share, SortAsc, SortDesc, Trash } from 'lucide-react'
import { Input } from '@/components/ui/input'
import AlbumShareDialog, { IAlbumShareDialogRef } from '@/components/albums/share/AlbumShareDialog'
import { AlertDialog } from '@/components/ui/alert-dialog'
import toast from 'react-hot-toast'
const SORT_BY_OPTIONS = [
{ value: 'lastPhotoDate', label: 'Last Photo Date' },
@@ -27,7 +26,6 @@ const SORT_BY_OPTIONS = [
{ value: 'faceCount', label: 'Number of People' },
]
export default function AlbumListPage() {
const { exImmichUrl } = useConfig()
const router = useRouter()
const [search, setSearch] = useState('')
const { query, pathname } = router
@@ -35,11 +33,14 @@ export default function AlbumListPage() {
const [albums, setAlbums] = useState<IAlbum[]>([])
const [loading, setLoading] = useState(false)
const [errorMessage, setErrorMessage] = useState('')
const [selectedAlbums, setSelectedAlbums] = useState<string[]>([])
const [selectedAlbumsIds, setSelectedAlbumsIds] = useState<string[]>([])
const albumShareDialogRef = useRef<IAlbumShareDialogRef>(null);
const [deleting, setDeleting] = useState(false)
const selectedSortBy = useMemo(() => SORT_BY_OPTIONS.find((option) => option.value === sortBy), [sortBy])
const searchedAlbums = useMemo(() => albums.filter((album) => album.albumName.toLowerCase().includes(search.toLowerCase())), [albums, search])
const searchedAlbums = useMemo(() => albums.filter((album) => album.albumName.toLowerCase().includes(search.toLowerCase())), [albums, search])
const fetchAlbums = async () => {
setLoading(true)
listAlbums({
@@ -55,18 +56,33 @@ export default function AlbumListPage() {
})
}
const selectedAlbums = useMemo(() => albums.filter((album) => selectedAlbumsIds.includes(album.id)), [albums, selectedAlbumsIds])
useEffect(() => {
fetchAlbums()
}, [sortBy, sortOrder])
const handleSelect = (checked: boolean, albumId: string) => {
if (checked) {
setSelectedAlbums([...selectedAlbums, albumId])
setSelectedAlbumsIds([...selectedAlbumsIds, albumId])
} else {
setSelectedAlbums(selectedAlbums.filter((id) => id !== albumId))
setSelectedAlbumsIds(selectedAlbumsIds.filter((id) => id !== albumId))
}
}
const handleDeleteAlbums = async () => {
setDeleting(true)
return deleteAlbums(selectedAlbumsIds).then(() => {
setSelectedAlbumsIds([])
setAlbums(albums.filter((album) => !selectedAlbumsIds.includes(album.id)))
toast.success(`Deleted ${selectedAlbumsIds.length} albums`)
}).catch((error) => {
toast.error(error.message)
}).finally(() => {
setDeleting(false)
})
}
const renderContent = () => {
if (loading) {
@@ -78,7 +94,12 @@ export default function AlbumListPage() {
return (
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4 p-4">
{searchedAlbums.map((album) => (
<AlbumThumbnail album={album} key={album.id} onSelect={(checked) => handleSelect(checked, album.id)} />
<AlbumThumbnail
album={album}
key={album.id}
selected={selectedAlbumsIds.includes(album.id)}
onSelect={(checked) => handleSelect(checked, album.id)}
/>
))}
</div>
)
@@ -89,17 +110,45 @@ export default function AlbumListPage() {
leftComponent="Manage Albums"
rightComponent={
<div className="flex items-center gap-2">
{!!selectedAlbumsIds.length && (
<>
<Button
variant={"secondary"}
size={"sm"}
className="flex items-center gap-2"
onClick={() => {
albumShareDialogRef.current?.open(selectedAlbums)
}}>
<Share size={16} /> Share {selectedAlbumsIds.length} albums
</Button>
<AlertDialog
title='Delete Albums'
description='Are you sure you want to delete these albums?'
onConfirm={handleDeleteAlbums}
>
<Button
variant={"destructive"}
size={"sm"}
className="flex items-center gap-2"
disabled={deleting}
>
<Trash size={16} /> {deleting ? "Deleting..." : `Delete ${selectedAlbumsIds.length} albums`}
</Button>
</AlertDialog>
</>
)}
<Input type="text" placeholder="Search" className="w-48" onChange={(e) => setSearch(e.target.value)} />
<Select
defaultValue={selectedSortBy?.value}
onValueChange={(value) => router.push({
pathname,
query: {
...query,
sortBy: value,
}
})}>
query: {
...query,
sortBy: value,
}
})}>
<SelectTrigger className="px-2">
<SelectValue placeholder="Sort by">{selectedSortBy?.label || 'Sort by'}</SelectValue>
</SelectTrigger>
@@ -122,6 +171,9 @@ export default function AlbumListPage() {
}
/>
{renderContent()}
<AlbumShareDialog
ref={albumShareDialogRef}
/>
</PageLayout>
)
}
+90 -39
View File
@@ -1,10 +1,11 @@
import AlbumCreateDialog from "@/components/albums/AlbumCreateDialog";
import AlbumSelectorDialog from "@/components/albums/AlbumSelectorDialog";
import PotentialAlbumsAssets from "@/components/albums/potential-albums/PotentialAlbumsAssets";
import PotentialAlbumsDates from "@/components/albums/potential-albums/PotentialAlbumsDates";
import AssetsOptions from "@/components/assets/assets-options/AssetsOptions";
import AssetOffsetDialog from "@/components/assets/assets-options/AssetOffsetDialog";
import PageLayout from "@/components/layouts/PageLayout";
import FloatingBar from "@/components/shared/FloatingBar";
import Header from "@/components/shared/Header";
import { AlertDialog } from "@/components/ui/alert-dialog";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { useToast } from "@/components/ui/use-toast";
@@ -13,6 +14,7 @@ import PotentialAlbumContext, {
IPotentialAlbumConfig,
} from "@/contexts/PotentialAlbumContext";
import { addAssetToAlbum, createAlbum } from "@/handlers/api/album.handler";
import { deleteAssets } from "@/handlers/api/asset.handler";
import { IAlbum, IAlbumCreate } from "@/types/album";
import { useRouter } from "next/router";
import React, { useMemo } from "react";
@@ -29,7 +31,7 @@ export default function PotentialAlbums() {
assets: [],
});
const selectedAssets = useMemo(() => config.assets.filter((a) => config.selectedIds.includes(a.id)), [config.assets, config.selectedIds]) ;
const selectedAssets = useMemo(() => config.assets.filter((a) => config.selectedIds.includes(a.id)), [config.assets, config.selectedIds]);
const handleSelect = (album: IAlbum) => {
return addAssetToAlbum(album.id, config.selectedIds)
@@ -66,48 +68,46 @@ export default function PotentialAlbums() {
role: "editor",
userId: id,
}]
}).then(() => {
toast({
title: "Album created",
description: "Album created successfully",
});
setConfig({ ...config, selectedIds: [], assets: config.assets.filter(a => !config.selectedIds.includes(a.id)) });
})
}
const handleDelete = () => {
return deleteAssets(config.selectedIds)
.then(() => {
setConfig({ ...config, selectedIds: [], assets: config.assets.filter(a => !config.selectedIds.includes(a.id)) });
})
.then(() => {
toast({
title: "Assets deleted",
description: "Assets deleted successfully",
});
})
.catch(() => {
toast({
title: "Error",
description: "Failed to delete assets",
variant: "destructive",
});
});
}
const handleOffsetComplete = () => {
setConfig({
...config,
selectedIds: [],
});
}
return (
<PageLayout className="!p-0 !mb-0">
<PageLayout className="!p-0 !mb-0 relative">
<Header
leftComponent="Potential Albums"
rightComponent={
<>
<Badge variant={"outline"}>
{config.selectedIds.length} Selected
</Badge>
{config.selectedIds.length && config.selectedIds.length === config.assets.length ? (
<Button
variant={"outline"}
onClick={() =>
setConfig({
...config,
selectedIds: [],
})
}
>
Unselect all
</Button>
) : (
<Button
variant={"outline"}
onClick={() =>
setConfig({
...config,
selectedIds: config.assets.map((a) => a.id),
})
}
>
Select all
</Button>
)}
<AlbumSelectorDialog onSelected={handleSelect} />
<AlbumCreateDialog onSubmit={handleCreate} assetIds={config.assets.map((a) => a.id)} />
<AssetsOptions assets={selectedAssets} onAdd={() => { }} />
</>
}
/>
<PotentialAlbumContext.Provider
value={{
@@ -120,6 +120,57 @@ export default function PotentialAlbums() {
<PotentialAlbumsDates />
<PotentialAlbumsAssets />
</div>
<FloatingBar>
<div className="flex items-center gap-2 justify-between w-full">
<p className="text-sm text-muted-foreground">
{config.selectedIds.length} Selected
</p>
<div className="flex items-center gap-2">
{config.selectedIds.length && config.selectedIds.length > 0 ? (
<Button
variant={"outline"}
size={"sm"}
onClick={() =>
setConfig({
...config,
selectedIds: [],
})
}
>
Unselect all
</Button>
) : (
<Button
variant={"outline"}
size={"sm"}
onClick={() =>
setConfig({
...config,
selectedIds: config.assets.map((a) => a.id),
})
}
>
Select all
</Button>
)}
<AlbumSelectorDialog onSelected={handleSelect} onSubmit={handleCreate}/>
<AssetOffsetDialog assets={selectedAssets} onComplete={handleOffsetComplete} />
<div className="h-[10px] w-[1px] bg-zinc-500 dark:bg-zinc-600"></div>
<AlertDialog
title="Delete the selected assets?"
description="This action will delete the selected assets and cannot be undone."
onConfirm={handleDelete}
disabled={config.selectedIds.length === 0}
>
<Button variant={"destructive"} size={"sm"} disabled={config.selectedIds.length === 0}>
Delete
</Button>
</AlertDialog>
</div>
</div>
</FloatingBar>
</PotentialAlbumContext.Provider>
</PageLayout>
);
+29 -27
View File
@@ -106,40 +106,42 @@ export default function ExifDataAnalytics() {
}, []);
return (
<PageLayout className="p-4">
<PageLayout className="!p-0 !mb-0 relative">
<Header leftComponent="Exif Data" />
<div className="grid grid-cols-4 gap-4">
{["Total", "Images", "Videos"].map((type, i) => (
<Card key={i}>
<div className="p-4">
<div className="grid grid-cols-4 gap-4">
{["Total", "Images", "Videos"].map((type, i) => (
<Card key={i}>
<CardHeader>
<CardTitle className="text-center text-lg font-mono">{type}</CardTitle>
</CardHeader>
<CardContent className="text-center text-3xl font-mono">
{loading ? "Loading..." : statistics[type.toLowerCase() as keyof typeof statistics].toLocaleString()}
</CardContent>
</Card>
))}
<Card>
<CardHeader>
<CardTitle className="text-center text-lg font-mono">{type}</CardTitle>
<CardTitle className="text-center text-lg font-mono">Live Photos</CardTitle>
</CardHeader>
<CardContent className="text-center text-3xl font-mono">
{loading ? "Loading..." : statistics[type.toLowerCase() as keyof typeof statistics].toLocaleString()}
{loading ? "Loading..." : livePhotoStatistics.total.toLocaleString()}
</CardContent>
</Card>
))}
<Card>
<CardHeader>
<CardTitle className="text-center text-lg font-mono">Live Photos</CardTitle>
</CardHeader>
<CardContent className="text-center text-3xl font-mono">
{loading ? "Loading..." : livePhotoStatistics.total.toLocaleString()}
</CardContent>
</Card>
</div>
<AssetHeatMap />
<div className="grid grid-cols-3 gap-4">
{exifCharts.map((chart) => (
<EXIFDistribution
key={chart.column}
column={chart.column}
title={chart.title}
description={chart.description}
tooltipValueFormatter={chart.tooltipValueFormatter}
/>
))}
</div>
<AssetHeatMap />
<div className="grid grid-cols-3 gap-4">
{exifCharts.map((chart) => (
<EXIFDistribution
key={chart.column}
column={chart.column}
title={chart.title}
description={chart.description}
tooltipValueFormatter={chart.tooltipValueFormatter}
/>
))}
</div>
</div>
</PageLayout>
);
+1 -3
View File
@@ -4,12 +4,10 @@ import { db } from "@/config/db";
import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
import { NextApiResponse } from "next";
import { albums } from "@/schema/albums.schema";
import { count, desc, eq, min, max, sql, and } from "drizzle-orm";
import { count, eq, min, max, sql, and } from "drizzle-orm";
import { assets } from "@/schema/assets.schema";
import { albumsAssetsAssets } from "@/schema/albumAssetsAssets.schema";
import { users } from "@/schema/users.schema";
import { assetFaces, exif, person } from "@/schema";
import { IAlbum } from "@/types/album";
export default async function handler(
req: NextApiRequest,
+44
View File
@@ -0,0 +1,44 @@
import { NextApiRequest } from "next";
import { db } from "@/config/db";
import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
import { NextApiResponse } from "next";
import { albums } from "@/schema/albums.schema";
import { count, eq, min, max, sql, and } from "drizzle-orm";
import { assets } from "@/schema/assets.schema";
import { albumsAssetsAssets } from "@/schema/albumAssetsAssets.schema";
import { assetFaces, exif, person } from "@/schema";
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const { id } = req.query as { id: string };
const dbAlbums = await db.selectDistinctOn([albums.id], {
id: albums.id,
albumName: albums.albumName,
createdAt: albums.createdAt,
updatedAt: albums.updatedAt,
albumThumbnailAssetId: albums.albumThumbnailAssetId,
assetCount: count(assets.id),
firstPhotoDate: min(exif.dateTimeOriginal),
lastPhotoDate: max(exif.dateTimeOriginal),
faceCount: count(sql<string>`DISTINCT ${person.id}`), // Ensure unique personId
})
.from(albums)
.leftJoin(albumsAssetsAssets, eq(albums.id, albumsAssetsAssets.albumsId))
.leftJoin(assets, eq(albumsAssetsAssets.assetsId, assets.id))
.leftJoin(exif, and(eq(assets.id, exif.assetId), eq(assets.isVisible, true)))
.leftJoin(assetFaces, eq(assets.id, assetFaces.assetId))
.leftJoin(person, and(eq(assetFaces.personId, person.id), eq(person.isHidden, false)))
.where(and(eq(albums.id, id)))
.groupBy(albums.id)
.limit(1);
if (dbAlbums.length === 0) {
return res.status(404).json({ error: "Album not found" });
}
res.status(200).json(dbAlbums[0]);
}
+50
View File
@@ -0,0 +1,50 @@
import { ENV } from "@/config/environment";
import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
import { NextApiResponse } from "next";
import { NextApiRequest } from "next";
interface IAlbumShare {
albumId: string;
allowDownload: boolean;
allowUpload: boolean;
showMetadata: boolean;
}
const deleteSingleAlbum = async (albumId: string, token: string) => {
const url = ENV.IMMICH_URL + "/api/albums/" + albumId;
return fetch(url, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${token}`
}
}).then(async (response) => {
if (response.status >= 400) {
return {
error: "Failed to fetch assets",
errorData: await response.json()
};
}
return {
success: true
};
});
}
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const currentUser = await getCurrentUser(req);
if (!currentUser) {
return res.status(401).json({ error: 'Unauthorized' });
}
const { albumIds } = req.body as { albumIds: string[] };
if (!albumIds) {
return res.status(400).json({ error: 'albumIds is required' });
}
const deleteResults = await Promise.all(albumIds.map(async (albumId) => {
return deleteSingleAlbum(albumId, currentUser.accessToken);
}));
return res.status(200).json(deleteResults);
}
+11 -8
View File
@@ -11,31 +11,34 @@ import { users } from "@/schema/users.schema";
import { assetFaces, exif, person } from "@/schema";
import { IAlbum } from "@/types/album";
const getTime = (date: Date) => {
return date ? date.getTime() : 0;
}
const sortAlbums = (albums: IAlbum[], sortBy: string, sortOrder: string) => {
if (sortBy === 'createdAt') {
return albums.sort((a, b) => sortOrder === 'asc' ? a.createdAt.getTime() - b.createdAt.getTime() : b.createdAt.getTime() - a.createdAt.getTime());
return albums.sort((a, b) => sortOrder === 'asc' ? getTime(a?.createdAt) - getTime(b?.createdAt) : getTime(b?.createdAt) - getTime(a?.createdAt));
}
if (sortBy === 'updatedAt') {
return albums.sort((a, b) => sortOrder === 'asc' ? a.updatedAt.getTime() - b.updatedAt.getTime() : b.updatedAt.getTime() - a.updatedAt.getTime());
return albums.sort((a, b) => sortOrder === 'asc' ? getTime(a?.updatedAt) - getTime(b?.updatedAt) : getTime(b?.updatedAt) - getTime(a?.updatedAt));
}
if (sortBy === 'firstPhotoDate') {
return albums.sort((a, b) => sortOrder === 'asc' ? a.firstPhotoDate.getTime() - b.firstPhotoDate.getTime() : b.firstPhotoDate.getTime() - a.firstPhotoDate.getTime());
return albums.sort((a, b) => sortOrder === 'asc' ? getTime(a?.firstPhotoDate) - getTime(b?.firstPhotoDate) : getTime(b?.firstPhotoDate) - getTime(a?.firstPhotoDate));
}
if (sortBy === 'lastPhotoDate') {
return albums.sort((a, b) => sortOrder === 'asc' ? a.lastPhotoDate.getTime() - b.lastPhotoDate.getTime() : b.lastPhotoDate.getTime() - a.lastPhotoDate.getTime());
return albums.sort((a, b) => sortOrder === 'asc' ? getTime(a?.lastPhotoDate) - getTime(b?.lastPhotoDate) : getTime(b?.lastPhotoDate) - getTime(a?.lastPhotoDate));
}
if (sortBy === 'assetCount') {
return albums.sort((a, b) => sortOrder === 'asc' ? a.assetCount - b.assetCount : b.assetCount - a.assetCount);
return albums.sort((a, b) => sortOrder === 'asc' ? a?.assetCount - b?.assetCount : b?.assetCount - a?.assetCount);
}
if (sortBy === 'albumName') {
return albums.sort((a, b) => sortOrder === 'asc' ? a.albumName.localeCompare(b.albumName) : b.albumName.localeCompare(a.albumName));
return albums.sort((a, b) => sortOrder === 'asc' ? a?.albumName?.localeCompare(b?.albumName) : b?.albumName?.localeCompare(a?.albumName));
}
if (sortBy === 'albumSize') {
return albums.sort((a, b) => sortOrder === 'asc' ? parseInt(a.size) - parseInt(b.size) : parseInt(b.size) - parseInt(a.size));
return albums.sort((a, b) => sortOrder === 'asc' ? parseInt(a?.size) - parseInt(b?.size) : parseInt(b?.size) - parseInt(a?.size));
}
if (sortBy === 'faceCount') {
return albums.sort((a, b) => sortOrder === 'asc' ? a.faceCount - b.faceCount : b.faceCount - a.faceCount);
return albums.sort((a, b) => sortOrder === 'asc' ? a?.faceCount - b?.faceCount : b?.faceCount - a?.faceCount);
}
return albums;
}
@@ -2,6 +2,7 @@
import { CHART_COLORS } from "@/config/constants/chart.constant";
import { db } from "@/config/db";
import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
import { isFlipped } from "@/helpers/asset.helper";
import { exif } from "@/schema";
import { count, desc, isNotNull, ne, sql } from "drizzle-orm";
import type { NextApiRequest, NextApiResponse } from "next";
@@ -23,7 +24,8 @@ const SELECT_ORPHAN_PHOTOS = (date: string, ownerId: string) =>
a."deletedAt",
e."exifImageWidth",
e."exifImageHeight",
e."dateTimeOriginal"
e."dateTimeOriginal",
e."orientation"
FROM
assets a
LEFT JOIN
@@ -47,7 +49,15 @@ export default async function handler(
const currentUser = await getCurrentUser(req)
const { startDate } = req.query as { startDate: string };
const { rows } = await db.execute(SELECT_ORPHAN_PHOTOS(startDate, currentUser.id));
return res.status(200).json(rows);
const cleanedRows = rows.map((row: any) => {
return {
...row,
exifImageWidth: isFlipped(row.orientation || 0) ? row.exifImageHeight : row.exifImageWidth,
exifImageHeight: isFlipped(row.orientation || 0) ? row.exifImageWidth : row.exifImageHeight,
};
});
return res.status(200).json(cleanedRows);
} catch (error: any) {
res.status(500).json({
error: error?.message,
+61
View File
@@ -0,0 +1,61 @@
import { ENV } from "@/config/environment";
import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
import { NextApiResponse } from "next";
import { NextApiRequest } from "next";
interface IAlbumShare {
albumId: string;
allowDownload: boolean;
allowUpload: boolean;
showMetadata: boolean;
}
const generateShareLink = async (album: IAlbumShare, token: string) => {
const url = ENV.IMMICH_URL + "/api/shared-links";
return fetch(url, {
method: 'POST',
body: JSON.stringify({
type: "ALBUM",
albumId: album.albumId,
allowDownload: album.allowDownload,
allowUpload: album.allowUpload,
showMetadata: album.showMetadata,
}),
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
}
}).then(async (response) => {
if (response.status >= 400) {
return {
error: "Failed to fetch assets",
errorData: await response.json()
};
}
const data = await response.json();
return {
...album,
...data,
shareLink: ENV.EXTERNAL_IMMICH_URL + "/share/" + data.key
};
});
}
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const currentUser = await getCurrentUser(req);
if (!currentUser) {
return res.status(401).json({ error: 'Unauthorized' });
}
const { albums } = req.body as { albums: IAlbumShare[] };
if (!albums) {
return res.status(400).json({ error: 'albums is required' });
}
const shareLinks = await Promise.all(albums.map(async (album) => {
return generateShareLink(album, currentUser.accessToken);
}));
return res.status(200).json(shareLinks);
}
+33
View File
@@ -0,0 +1,33 @@
import { NextApiResponse } from "next";
import { db } from "@/config/db";
import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
import { NextApiRequest } from "next";
import { assets, exif } from "@/schema";
import { and, eq, isNotNull } from "drizzle-orm";
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const currentUser = await getCurrentUser(req);
if (!currentUser) {
return res.status(401).json({ message: 'Unauthorized' });
}
const dbAssets = await db.select({
assetId: assets.id,
latitude: exif.latitude,
longitude: exif.longitude,
}).from(assets)
.innerJoin(exif, eq(assets.id, exif.assetId))
.where(
and(
eq(assets.ownerId, currentUser.id),
isNotNull(exif.latitude),
isNotNull(exif.longitude)
)
);
const heatmapData = dbAssets.map((asset) => [
asset.longitude,
asset.latitude,
]);
res.status(200).json(heatmapData);
}
@@ -0,0 +1,55 @@
import { db } from "@/config/db";
import { IMissingLocationDatesResponse } from "@/handlers/api/asset.handler";
import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
import { parseDate } from "@/helpers/date.helper";
import { assets, exif } from "@/schema";
import { albumsAssetsAssets } from "@/schema/albumAssetsAssets.schema";
import { albums } from "@/schema/albums.schema";
import { and, count, desc, eq, isNotNull, isNull, ne, sql } from "drizzle-orm";
import type { NextApiRequest, NextApiResponse } from "next";
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
try {
const { sortBy = "date", sortOrder = "desc" } = req.query;
const currentUser = await getCurrentUser(req);
if (!currentUser) {
return res.status(401).json({
error: "Unauthorized",
});
}
const rows = await db
.select({
asset_count: desc(count(assets.id)),
label: albums.albumName,
value: albums.id,
})
.from(assets)
.leftJoin(exif, eq(exif.assetId, assets.id))
.leftJoin(albumsAssetsAssets, eq(albumsAssetsAssets.assetsId, assets.id))
.leftJoin(albums, eq(albums.id, albumsAssetsAssets.albumsId))
.where(
and(
isNull(exif.latitude),
isNotNull(assets.createdAt),
isNotNull(exif.dateTimeOriginal),
eq(assets.ownerId, currentUser.id),
eq(assets.isVisible, true),
isNotNull(albums.id)
))
.groupBy(albums.id)
.orderBy(desc(count(assets.id))) as IMissingLocationDatesResponse[];
rows.sort((a, b) => {
return sortOrder === "asc" ? a.asset_count - b.asset_count : b.asset_count - a.asset_count;
});
return res.status(200).json(rows);
} catch (error: any) {
res.status(500).json({
error: error?.message,
});
}
}
+115 -40
View File
@@ -1,64 +1,139 @@
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import { db } from "@/config/db";
import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
import { isFlipped } from "@/helpers/asset.helper";
import { parseDate } from "@/helpers/date.helper";
import { assets, exif } from "@/schema";
import { albumsAssetsAssets } from "@/schema/albumAssetsAssets.schema";
import { albums } from "@/schema/albums.schema";
import { IUser } from "@/types/user";
import { addDays } from "date-fns";
import { and, eq, gte, isNotNull, isNull, lte, ne, sql } from "drizzle-orm";
import type { NextApiRequest, NextApiResponse } from "next";
const getRowsByDates = async (startDateDate: Date, endDateDate: Date, currentUser: IUser) => {
return db
.select({
id: assets.id,
deviceId: assets.deviceId,
type: assets.type,
originalPath: assets.originalPath,
isFavorite: assets.isFavorite,
duration: assets.duration,
encodedVideoPath: assets.encodedVideoPath,
originalFileName: assets.originalFileName,
sidecarPath: assets.sidecarPath,
deletedAt: assets.deletedAt,
localDateTime: assets.localDateTime,
exifImageWidth: exif.exifImageWidth,
exifImageHeight: exif.exifImageHeight,
ownerId: assets.ownerId,
dateTimeOriginal: exif.dateTimeOriginal,
orientation: exif.orientation,
})
.from(assets)
.leftJoin(exif, eq(exif.assetId, assets.id))
.where(and(
isNull(exif.latitude),
isNotNull(assets.createdAt),
gte(exif.dateTimeOriginal, startDateDate),
lte(exif.dateTimeOriginal, endDateDate),
eq(assets.ownerId, currentUser.id),
eq(assets.isVisible, true),
eq(assets.isArchived, false),
isNull(assets.deletedAt),
));
}
const getRowsByAlbums = async (currentUser: IUser, albumId: string) => {
return db.select({
id: assets.id,
deviceId: assets.deviceId,
type: assets.type,
originalPath: assets.originalPath,
isFavorite: assets.isFavorite,
duration: assets.duration,
encodedVideoPath: assets.encodedVideoPath,
originalFileName: assets.originalFileName,
sidecarPath: assets.sidecarPath,
deletedAt: assets.deletedAt,
localDateTime: assets.localDateTime,
exifImageWidth: exif.exifImageWidth,
exifImageHeight: exif.exifImageHeight,
ownerId: assets.ownerId,
dateTimeOriginal: exif.dateTimeOriginal,
orientation: exif.orientation,
})
.from(assets)
.leftJoin(exif, eq(exif.assetId, assets.id))
.leftJoin(albumsAssetsAssets, eq(albumsAssetsAssets.assetsId, assets.id))
.leftJoin(albums, eq(albums.id, albumsAssetsAssets.albumsId))
.where(and(
isNull(exif.latitude),
isNotNull(assets.createdAt),
eq(assets.ownerId, currentUser.id),
eq(albums.id, albumId),
eq(assets.isVisible, true),
eq(assets.isArchived, false),
isNull(assets.deletedAt),
));
}
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const { startDate } = req.query as {
const { startDate, groupBy, albumId } = req.query as {
startDate: string;
groupBy: "date" | "album";
albumId?: string;
};
const currentUser = await getCurrentUser(req);
if (!startDate) {
if (!currentUser) {
return res.status(401).json({
error: "Unauthorized",
});
}
if (!startDate && !albumId) {
return res.status(400).json({
error: "startDate and endDate are required",
error: "startDate or albumId is required",
});
}
const startDateDate = parseDate(startDate, "yyyy-MM-dd");
const endDateDate = addDays(parseDate(startDate, "yyyy-MM-dd"), 1);
if (startDate) {
const startDateDate = parseDate(startDate, "yyyy-MM-dd");
const endDateDate = addDays(parseDate(startDate, "yyyy-MM-dd"), 1);
try {
const rows = await db
.select({
id: assets.id,
deviceId: assets.deviceId,
type: assets.type,
originalPath: assets.originalPath,
isFavorite: assets.isFavorite,
duration: assets.duration,
encodedVideoPath: assets.encodedVideoPath,
originalFileName: assets.originalFileName,
sidecarPath: assets.sidecarPath,
deletedAt: assets.deletedAt,
localDateTime: assets.localDateTime,
exifImageWidth: exif.exifImageWidth,
exifImageHeight: exif.exifImageHeight,
ownerId: assets.ownerId,
dateTimeOriginal: exif.dateTimeOriginal,
})
.from(assets)
.leftJoin(exif, eq(exif.assetId, assets.id))
.where(and(
isNull(exif.latitude),
isNotNull(assets.createdAt),
gte(exif.dateTimeOriginal, startDateDate),
lte(exif.dateTimeOriginal, endDateDate),
eq(assets.ownerId, currentUser.id),
));
return res.status(200).json(rows);
} catch (error: any) {
res.status(500).json({
error: error?.message,
});
try {
const rows = await getRowsByDates(startDateDate, endDateDate, currentUser);
const cleanedRows = rows.map((row) => ({
...row,
exifImageWidth: isFlipped(row.orientation) ? row.exifImageHeight : row.exifImageWidth,
exifImageHeight: isFlipped(row.orientation) ? row.exifImageWidth : row.exifImageHeight,
orientation: row.orientation,
}));
return res.status(200).json(cleanedRows);
} catch (error: any) {
return res.status(500).json({
error: error?.message,
});
}
} else if (albumId) {
if (!albumId) {
return res.status(400).json({
error: "albumId is required",
});
}
const rows = await getRowsByAlbums(currentUser, albumId);
const cleanedRows = rows.map((row) => ({
...row,
exifImageWidth: isFlipped(row.orientation) ? row.exifImageHeight : row.exifImageWidth,
exifImageHeight: isFlipped(row.orientation) ? row.exifImageWidth : row.exifImageHeight,
orientation: row.orientation,
}));
return res.status(200).json(cleanedRows);
}
}
}
@@ -23,7 +23,8 @@ export default async function handler(
const rows = await db
.select({
asset_count: desc(count(assets.id)),
date: sql`DATE(${exif.dateTimeOriginal})`,
label: sql`DATE(${exif.dateTimeOriginal})`,
value: sql`DATE(${exif.dateTimeOriginal})`,
})
.from(assets)
.leftJoin(exif, eq(exif.assetId, assets.id))
@@ -33,14 +34,16 @@ export default async function handler(
isNotNull(exif.dateTimeOriginal),
eq(assets.ownerId, currentUser.id),
eq(assets.isVisible, true),
eq(assets.isArchived, false),
isNull(assets.deletedAt),
))
.groupBy(sql`DATE(${exif.dateTimeOriginal})`)
.orderBy(desc(count(assets.id))) as IMissingLocationDatesResponse[];
if (sortBy === "date") {
rows.sort((a, b) => {
const aDate = parseDate(a.date, "yyyy-MM-dd");
const bDate = parseDate(b.date, "yyyy-MM-dd");
const aDate = parseDate(a.label, "yyyy-MM-dd");
const bDate = parseDate(b.label, "yyyy-MM-dd");
return sortOrder === "asc" ? aDate.getTime() - bDate.getTime() : bDate.getTime() - aDate.getTime();
});
} else if (sortBy === "asset_count") {
+63
View File
@@ -0,0 +1,63 @@
import { db } from '@/config/db';
import { ENV } from '@/config/environment';
import { getCurrentUser } from '@/handlers/serverUtils/user.utils';
import { cleanUpAsset, cleanUpAssets, isFlipped } from '@/helpers/asset.helper';
import { parseFindQuery } from '@/helpers/gemini.helper';
import { assetFaces, assets, person } from '@/schema';
import { Person } from '@/schema/person.schema';
import { and, eq, inArray } from 'drizzle-orm';
import { NextApiRequest, NextApiResponse } from 'next';
export default async function search(req: NextApiRequest, res: NextApiResponse) {
const { query } = req.body;
const currentUser = await getCurrentUser(req);
const parsedQuery = await parseFindQuery(query as string);
const { personIds } = parsedQuery;
const url = ENV.IMMICH_URL + "/api/search/smart";
let dbPeople: Person[] = [];
if (personIds) {
dbPeople = await db.select().from(person).where(
inArray(person.id, personIds)
);
}
return fetch(url, {
method: 'POST',
body: JSON.stringify({...parsedQuery, withExif: true }),
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${currentUser?.accessToken}`
}
}).then(response => {
if (response.status !== 200) {
return res.json({
assets: [],
filters: parsedQuery,
error: "Failed to fetch assets",
errorData: response.json()
});
}
return response.json();
})
.then(data => {
const items = data.assets.items.map((item: any) => {
return {
...item,
exifImageHeight: isFlipped(item?.exifInfo?.orientation) ? item?.exifInfo?.exifImageWidth : item?.exifInfo?.exifImageHeight,
exifImageWidth: isFlipped(item?.exifInfo?.orientation) ? item?.exifInfo?.exifImageHeight : item?.exifInfo?.exifImageWidth,
orientation: item?.exifInfo?.orientation,
}
}).map(cleanUpAsset)
res.status(200).json({
assets: items,
filters: {
...parsedQuery,
personIds: dbPeople.map((person) => person.name)
},
});
}).catch(err => {
res.status(500).json({ error: err.message });
});
}
@@ -0,0 +1,63 @@
// pages/api/proxy.js
import { ENV } from '@/config/environment';
import { getUserHeaders } from '@/helpers/user.helper';
import { verify } from 'jsonwebtoken';
import { NextApiRequest, NextApiResponse } from 'next'
export const config = {
api: {
bodyParser: false,
},
}
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== 'GET') {
return res.status(405).json({ message: 'Method Not Allowed' })
}
const { id, size, token, p } = req.query;
if (!token) {
return res.status(401).json({ message: 'Unauthorized' })
}
try {
verify(token as string, ENV.JWT_SECRET);
} catch (error) {
return res.status(401).json({ message: 'Token is invalid' })
}
const resource = p === "true" ? "people" : "assets";
const baseURL = `${ENV.IMMICH_URL}/api/${resource}/${id}`;
const version = size === "original" ? "original" : "thumbnail";
let targetUrl = `${baseURL}/${version}?size=${size}`;
try {
// Forward the request to the target API
const response = await fetch(targetUrl, {
method: 'GET',
headers: getUserHeaders({ isUsingShareKey: true }, {
'Content-Type': 'application/octet-stream',
}),
})
if (!response.ok) {
const error = await response.json()
throw new Error("Error fetching thumbnail " + error.message)
}
// Get the image data from the response
const imageBuffer = await response.arrayBuffer()
// Set the appropriate headers for the image response
res.setHeader('Content-Type', response.headers.get('Content-Type') || 'image/png')
res.setHeader('Content-Length', imageBuffer.byteLength)
// Send the image data
res.send(Buffer.from(imageBuffer))
} catch (error: any) {
res.redirect("https://placehold.co/400")
console.error('Error:', error)
}
}
@@ -20,7 +20,6 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
const targetUrl = `${ENV.IMMICH_URL}/api/assets/${id}/thumbnail?size=${size || 'thumbnail'}`;
const user = await getCurrentUser(req);
if (!user) {
return res.status(403).json({ message: 'Unauthorized' })
}
+9 -7
View File
@@ -1,8 +1,6 @@
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import { CHART_COLORS } from "@/config/constants/chart.constant";
import { db } from "@/config/db";
import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
import { stringToBoolean } from "@/helpers/data.helper";
import { assetFaces, assets, exif, person } from "@/schema";
import {
and,
@@ -11,6 +9,7 @@ import {
desc,
eq,
gte,
ilike,
isNotNull,
isNull,
lte,
@@ -29,6 +28,7 @@ interface IQuery {
maximumAssetCount: number;
sort: ISortField;
sortOrder: "asc" | "desc";
query: string;
}
export default async function handler(
req: NextApiRequest,
@@ -42,6 +42,7 @@ export default async function handler(
sort = "assetCount",
sortOrder = "desc",
type = "all",
query = "",
} = req.query as any as IQuery;
const currentUser = await getCurrentUser(req);
@@ -53,10 +54,11 @@ export default async function handler(
eq(assets.isVisible, true),
eq(assets.isArchived, false),
eq(assets.ownerId, currentUser.id),
type === "all" ? undefined : (type === "nameless" ? eq(person.name, "") : ne(person.name, ""))
type === "all" ? undefined : (type === "nameless" ? eq(person.name, "") : ne(person.name, "")),
query && query.length > 0 ? ilike(person.name, `%${query}%`) : undefined
);
let query = db
let dbQuery = db
.select({
id: person.id,
name: person.name,
@@ -74,17 +76,17 @@ export default async function handler(
let sortedQuery;
if (sort === "assetCount") {
sortedQuery = query.orderBy(
sortedQuery = dbQuery.orderBy(
sortOrder === "asc"
? asc(count(assetFaces.id))
: desc(count(assetFaces.id))
);
} else if (sort === "updatedAt") {
sortedQuery = query.orderBy(
sortedQuery = dbQuery.orderBy(
sortOrder === "asc" ? asc(person.updatedAt) : desc(person.updatedAt)
);
}
const people = await query.limit(perPage).offset((page - 1) * perPage);
const people = await dbQuery.limit(perPage).offset((page - 1) * perPage);
return res.status(200).json({
people,
+126
View File
@@ -0,0 +1,126 @@
import { NextApiRequest, NextApiResponse } from "next";
import { and, desc, gt, isNotNull, isNull, ne, sql } from "drizzle-orm";
import { eq } from "drizzle-orm";
import { db } from "@/config/db";
import { count } from "drizzle-orm";
import { assets } from "@/schema/assets.schema";
import { assetFaces } from "@/schema/assetFaces.schema";
import { exif, person, users } from "@/schema";
import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
import { albums } from "@/schema/albums.schema";
import { albumsAssetsAssets } from "@/schema/albumAssetsAssets.schema";
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== "GET") {
return res.status(405).json({ message: "Method Not Allowed" });
}
const { year = "2024" } = req.query as { year: string };
const user = await getCurrentUser(req);
if (!user) {
return res.status(403).json({ message: "Forbidden" });
}
const numberOfPhotos = await db.select({ count: count(assets.id) }).from(assets).where(and(
eq(assets.ownerId, user.id),
eq(assets.isVisible, true),
eq(assets.isArchived, false),
));
// Get list of countries visited in the year
const countriesInYear = await db
.select({ name: exif.country, count: count(assets.id) })
.from(exif)
.leftJoin(assets, eq(assets.id, exif.assetId))
.where(and(
eq(sql`EXTRACT(YEAR FROM ${exif.dateTimeOriginal})`, year),
eq(assets.ownerId, user.id),
eq(assets.isVisible, true),
eq(assets.isArchived, false),
))
.groupBy(exif.country);
const countries = countriesInYear.filter(country => !!country.name).map(country => country.name);
const countOfCities = await db
.select({ name: exif.city, count: count(assets.id) })
.from(exif)
.leftJoin(assets, eq(assets.id, exif.assetId))
.where(and(
eq(sql`EXTRACT(YEAR FROM ${exif.dateTimeOriginal})`, year),
eq(assets.ownerId, user.id),
eq(assets.isVisible, true),
eq(assets.isArchived, false),
))
.groupBy(exif.city);
const cities = countOfCities.filter(city => !!city.name).map(city => city.name);
const albumsWithMostPhotos = await db
.select({
name: albums.albumName,
count: count(assets.id),
cover: albums.albumThumbnailAssetId
})
.from(albumsAssetsAssets)
.leftJoin(albums, eq(albums.id, albumsAssetsAssets.albumsId))
.leftJoin(assets, eq(assets.id, albumsAssetsAssets.assetsId))
.leftJoin(exif, eq(exif.assetId, assets.id))
.where(and(
eq(sql`EXTRACT(YEAR FROM ${exif.dateTimeOriginal})`, year),
eq(assets.ownerId, user.id),
eq(assets.isVisible, true),
eq(assets.isArchived, false),
))
.orderBy(desc(count(assets.id)))
.limit(4)
.groupBy(albums.id);
const peopleWithMostPhotos = await db
.select({
name: person.name,
count: count(assets.id),
id: person.id,
cover: person.faceAssetId
})
.from(assetFaces)
.leftJoin(assets, eq(assets.id, assetFaces.assetId))
.leftJoin(person, eq(person.id, assetFaces.personId))
.leftJoin(exif, eq(exif.assetId, assets.id))
.where(and(
eq(sql`EXTRACT(YEAR FROM ${exif.dateTimeOriginal})`, year),
eq(assets.ownerId, user.id),
eq(assets.isVisible, true),
eq(assets.isArchived, false),
isNotNull(person.name),
))
.orderBy(desc(count(assets.id)))
.limit(2)
.groupBy(person.id);
const favoritedAssets = await db
.select({ id: assets.id })
.from(assets)
.leftJoin(exif, eq(exif.assetId, assets.id))
.where(and(
eq(assets.isVisible, true),
eq(assets.isFavorite, true),
eq(assets.isArchived, false),
eq(assets.ownerId, user.id),
eq(sql`EXTRACT(YEAR FROM ${exif.dateTimeOriginal})`, year),
))
.limit(4);
return res.status(200).json({
name: user.name,
numberOfPhotos: numberOfPhotos[0].count,
countriesInYear: countries,
countOfCities: cities.length,
albumsWithMostPhotos,
peopleWithMostPhotos: peopleWithMostPhotos,
favoritedAssets: favoritedAssets.map(asset => asset.id)
});
}
+114
View File
@@ -0,0 +1,114 @@
import { db } from "@/config/db";
import { ENV } from "@/config/environment";
import { desc, gte, lte } from "drizzle-orm";
import { eq, inArray } from "drizzle-orm";
import { assetFaces, assets, exif, person } from "@/schema";
import { and } from "drizzle-orm";
import { JsonWebTokenError, sign, verify } from "jsonwebtoken";
import { NextApiResponse } from "next";
import { NextApiRequest } from "next";
import { albums } from "@/schema/albums.schema";
import { albumsAssetsAssets } from "@/schema/albumAssetsAssets.schema";
import { cleanUpShareAsset, isFlipped } from "@/helpers/asset.helper";
import { ShareLinkFilters } from "@/types/shareLink";
interface IQuery extends ShareLinkFilters {
token: string
['personIds[]']?: string[]
}
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
try {
const { token, ...rest } = req.query as any as IQuery
const filters = {
personIds: rest['personIds[]'] ?? rest.personIds ?? [],
}
if (!token) {
return res.status(404).json({ message: "Token not found" });
}
const decoded = verify(token as string, ENV.JWT_SECRET);
if (!decoded) {
return res.status(401).json({ message: "Unauthorized" });
}
const newPreviewToken = sign({ token: token }, ENV.JWT_SECRET, {
expiresIn: "2m"
});
const { personIds = [], albumIds = [], startDate, endDate } = decoded as ShareLinkFilters;
let filteredPersonIds: string[] = personIds ?? [];
const queryPersonIds = filters.personIds ? (Array.isArray(filters.personIds) ? filters.personIds : [filters.personIds]) : [];
if (queryPersonIds.length > 0) {
if (personIds.length === 0) {
filteredPersonIds = queryPersonIds;
} else {
filteredPersonIds = queryPersonIds.filter((id) => personIds.includes(id));
}
}
const dbAssets = await db.select({
id: assets.id,
deviceId: assets.deviceId,
type: assets.type,
originalPath: assets.originalPath,
isFavorite: assets.isFavorite,
duration: assets.duration,
encodedVideoPath: assets.encodedVideoPath,
originalFileName: assets.originalFileName,
sidecarPath: assets.sidecarPath,
deletedAt: assets.deletedAt,
localDateTime: assets.localDateTime,
exifImageWidth: exif.exifImageWidth,
exifImageHeight: exif.exifImageHeight,
ownerId: assets.ownerId,
dateTimeOriginal: exif.dateTimeOriginal,
url: assets.id,
previewUrl: assets.id,
videoURL: assets.id,
orientation: exif.orientation,
}).from(assets)
.innerJoin(assetFaces, eq(assets.id, assetFaces.assetId))
.innerJoin(albumsAssetsAssets, eq(assets.id, albumsAssetsAssets.assetsId))
.innerJoin(albums, eq(albumsAssetsAssets.albumsId, albums.id))
.innerJoin(exif, eq(exif.assetId, assets.id))
.where(and(
filteredPersonIds?.length > 0 ? inArray(assetFaces.personId, filteredPersonIds) : undefined,
albumIds?.length > 0 ? inArray(albums.id, albumIds) : undefined,
startDate ? gte(assets.createdAt, new Date(startDate)) : undefined,
endDate ? lte(assets.createdAt, new Date(endDate)) : undefined,
eq(assets.isArchived, false),
eq(assets.isVisible, true),
eq(assets.isOffline, false),
))
.orderBy(desc(assets.createdAt));
const cleanedAssets = dbAssets.map((asset) => {
return {
...asset,
localDateTime: new Date(asset.localDateTime),
duration: asset.duration ? parseInt(asset.duration) : 0,
exifImageWidth: (isFlipped(asset.orientation) ? asset.exifImageHeight : asset.exifImageWidth) ?? 0,
exifImageHeight: (isFlipped(asset.orientation) ? asset.exifImageWidth : asset.exifImageHeight) ?? 0,
dateTimeOriginal: new Date(asset.dateTimeOriginal || new Date()).toISOString(),
}
}).map((asset) => cleanUpShareAsset(asset, newPreviewToken as string));
return res.status(200).json({
assets: cleanedAssets,
filters: decoded as ShareLinkFilters
});
} catch (error) {
if (error instanceof JsonWebTokenError) {
return res.status(401).json({ message: "Please check your link and try again. Looks like it's expired." });
}
return res.status(500).json({ message: (error as Error).message });
}
}
+35
View File
@@ -0,0 +1,35 @@
import { NextApiResponse } from "next";
import { ENV } from "@/config/environment";
import { ShareLinkFilters } from "@/types/shareLink";
import { JsonWebTokenError, verify } from "jsonwebtoken";
import { NextApiRequest } from "next";
export default async function GET(req: NextApiRequest, res: NextApiResponse) {
const { token } = req.query;
try {
if (!token) {
return res.status(404).json({ message: "Token not found" });
}
if (!ENV.IMMICH_SHARE_LINK_KEY) {
return res.status(401).json({ message: "Please check your link and try again. If you're the admin, check if you've enabled all the configurations in the Immich Power Tools in your environment variables" });
}
const decoded = verify(token as string, ENV.JWT_SECRET);
if (!decoded) {
return res.status(401).json({ message: "Link is invalid. Please check your link and try again" });
}
return res.status(200).json(decoded);
} catch (error) {
if (error instanceof JsonWebTokenError) {
return res.status(401).json({ message: "Please check your link and try again. Looks like it's expired." });
}
return res.status(500).json({ message: (error as Error).message });
}
}
@@ -0,0 +1,79 @@
import { db } from "@/config/db";
import { ENV } from "@/config/environment";
import { count, desc, gte, isNotNull, lte, ne } from "drizzle-orm";
import { eq, inArray } from "drizzle-orm";
import { assetFaces, assets, exif, person } from "@/schema";
import { and } from "drizzle-orm";
import { JsonWebTokenError, sign, verify } from "jsonwebtoken";
import { NextApiResponse } from "next";
import { NextApiRequest } from "next";
import { albums } from "@/schema/albums.schema";
import { albumsAssetsAssets } from "@/schema/albumAssetsAssets.schema";
import { ASSET_SHARE_THUMBNAIL_PATH } from "@/config/routes";
interface ShareLinkFilters {
personIds: string[];
albumIds: string[];
startDate: string;
endDate: string;
}
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const { token } = req.query;
try {
if (!token) {
return res.status(404).json({ message: "Token not found" });
}
const decoded = verify(token as string, ENV.JWT_SECRET);
if (!decoded) {
return res.status(401).json({ message: "Unauthorized" });
}
const newPreviewToken = sign({ token: token }, ENV.JWT_SECRET, {
expiresIn: "2m"
});
const { personIds, albumIds, startDate, endDate } = decoded as ShareLinkFilters;
const dbPeople = await db.select({
id: person.id,
name: person.name,
thumbnailAssetId: person.faceAssetId,
assetCount: count(assets.id),
}).from(assets)
.innerJoin(assetFaces, eq(assets.id, assetFaces.assetId))
.innerJoin(albumsAssetsAssets, eq(assets.id, albumsAssetsAssets.assetsId))
.innerJoin(person, eq(assetFaces.personId, person.id))
.innerJoin(albums, eq(albumsAssetsAssets.albumsId, albums.id))
.innerJoin(exif, eq(exif.assetId, assets.id))
.where(and(
personIds?.length > 0 ? inArray(assetFaces.personId, personIds) : undefined,
albumIds?.length > 0 ? inArray(albums.id, albumIds) : undefined,
startDate ? gte(assets.createdAt, new Date(startDate)) : undefined,
endDate ? lte(assets.createdAt, new Date(endDate)) : undefined,
eq(assets.isArchived, false),
eq(assets.isVisible, true),
eq(assets.isOffline, false),
isNotNull(person.id),
ne(person.name, "")
))
.groupBy(person.id)
.orderBy(desc(count(assets.id)));
const cleanedPeople = dbPeople.map((person) => {
return {
...person,
thumbnailPath: person.thumbnailAssetId ? ASSET_SHARE_THUMBNAIL_PATH({ id: person.id, size: "thumbnail", token: newPreviewToken, isPeople: true }) : null
}
})
return res.status(200).json(cleanedPeople);
} catch (error) {
if (error instanceof JsonWebTokenError) {
return res.status(401).json({ message: "Please check your link and try again. Looks like it's expired." });
}
return res.status(500).json({ message: (error as Error).message });
}
}
+38
View File
@@ -0,0 +1,38 @@
import { ENV } from "@/config/environment";
import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
import { sign } from "jsonwebtoken";
import { NextApiRequest, NextApiResponse } from "next";
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const currentUser = await getCurrentUser(req);
const allFilters = req.body;
const { expiresIn, ...filters } = allFilters;
try {
if (!currentUser) {
return res.status(401).json({ message: "Unauthorized" });
}
if (!ENV.JWT_SECRET) {
return res.status(401).json({ message: "The JWT_SECRET is missing in the .env file. Please add it to the .env file for generating share links" });
}
if (!ENV.IMMICH_SHARE_LINK_KEY) {
return res.status(401).json({ message: "The IMMICH_SHARE_LINK_KEY is missing in the .env file. Please add it to the .env file for generating share links" });
}
if (!ENV.POWER_TOOLS_ENDPOINT_URL) {
return res.status(401).json({ message: "The POWER_TOOLS_ENDPOINT_URL is missing in the .env file. Please add it to the .env file for generating share links" });
}
const token = sign(filters, ENV.JWT_SECRET, expiresIn !== "never" ? {
expiresIn: expiresIn
} : {});
return res.status(200).json({ link: `${ENV.POWER_TOOLS_ENDPOINT_URL}/s/${token}` });
} catch (error) {
return res.status(500).json({ message: (error as Error).message });
}
}
+95
View File
@@ -0,0 +1,95 @@
import Header from '@/components/shared/Header'
import { useConfig } from '@/contexts/ConfigContext';
import React, { useEffect, useMemo, useState } from 'react'
import { useMap, useMapsLibrary } from '@vis.gl/react-google-maps';
import { APIProvider, Map } from '@vis.gl/react-google-maps';
import PageLayout from '@/components/layouts/PageLayout';
import { getAssetGeoHeatmap } from '@/handlers/api/asset.handler';
import { useTheme } from 'next-themes';
import { MapPinX } from 'lucide-react';
const HeatMap = () => {
const map = useMap();
const visualization = useMapsLibrary('visualization');
const heatmap = useMemo(() => {
if (!visualization) return null;
return new google.maps.visualization.HeatmapLayer({
radius: 20,
opacity: 0.5
});
}, [visualization]);
useEffect(() => {
if (!heatmap) return;
getAssetGeoHeatmap().then((data) => {
heatmap.setData(data.map(([lng, lat]: [number, number]) => ({
location: new google.maps.LatLng(lat, lng),
weight: 10
})));
});
}, [heatmap]);
useEffect(() => {
if (!heatmap) return;
heatmap.setMap(map);
return () => {
heatmap.setMap(null);
};
}, [heatmap, map]);
return null;
}
export default function GeoHeatmap() {
const { googleMapsApiKey } = useConfig();
const { theme } = useTheme();
const [mapId, setMapId] = useState('7a9e2ebecd32a903');
useEffect(() => {
if (theme === 'light') {
setMapId("");
} else {
setMapId('7a9e2ebecd32a903');
}
}, [theme]);
return (
<PageLayout className="!p-0 !mb-0">
<Header leftComponent="Geo Heatmap" />
<div className='h-full w-full'>
{googleMapsApiKey ? (
<APIProvider apiKey={googleMapsApiKey}>
<Map
defaultCenter={{ lat: 0, lng: 0 }}
mapId={mapId}
defaultZoom={2}
gestureHandling={'greedy'}
disableDefaultUI={true}
className='h-full w-full'
/>
<HeatMap />
</APIProvider>
) : (
<div className='h-full w-full flex items-center justify-center flex-col gap-2'>
<MapPinX className='w-10 h-10 text-muted-foreground' />
<p className='text-muted-foreground'>No Google Maps API key found</p>
<p className='text-muted-foreground'>
Please create and add your Google Maps API key in the env file under <kbd className='bg-zinc-200 text-black dark:text-white px-1 py-0.5 rounded-md dark:bg-zinc-500'>GOOGLE_MAPS_API_KEY</kbd>.
</p>
</div>
)}
</div>
</PageLayout>
)
}
+110 -41
View File
@@ -1,4 +1,3 @@
import AssetsOptions from "@/components/assets/assets-options/AssetsOptions";
import MissingLocationAssets from "@/components/assets/missing-location/MissingLocationAssets";
import MissingLocationDates from "@/components/assets/missing-location/MissingLocationDates";
import TagMissingLocationDialog from "@/components/assets/missing-location/TagMissingLocationDialog/TagMissingLocationDialog";
@@ -10,24 +9,29 @@ import { useToast } from "@/components/ui/use-toast";
import MissingLocationContext, {
IMissingLocationConfig,
} from "@/contexts/MissingLocationContext";
import { updateAssets } from "@/handlers/api/asset.handler";
import { deleteAssets, updateAssets } from "@/handlers/api/asset.handler";
import { IPlace } from "@/types/common";
import { SortDesc, SortAsc } from "lucide-react";
import { useRouter } from "next/router";
import React, { useMemo } from "react";
import FloatingBar from "@/components/shared/FloatingBar";
import { Select, SelectValue, SelectTrigger, SelectContent, SelectItem } from "@/components/ui/select";
import { AlertDialog } from "@/components/ui/alert-dialog";
import AssetOffsetDialog from "@/components/assets/assets-options/AssetOffsetDialog";
export default function MissingLocations() {
const { toast } = useToast();
const { query } = useRouter();
const { startDate } = query as { startDate: string };
const { query, push } = useRouter();
const { startDate, groupBy = "date" } = query as { startDate: string, groupBy: string };
const [config, setConfig] = React.useState<IMissingLocationConfig>({
startDate: startDate || undefined,
selectedIds: [],
assets: [],
sort: "fileOriginalDate",
sortOrder: "asc",
});
const selectedAssets = useMemo(() => config.assets.filter((a) => config.selectedIds.includes(a.id)), [config.assets, config.selectedIds]) ;
const selectedAssets = useMemo(() => config.assets.filter((a) => config.selectedIds.includes(a.id)), [config.assets, config.selectedIds]);
const handleSubmit = (place: IPlace) => {
return updateAssets({
@@ -42,43 +46,57 @@ export default function MissingLocations() {
})
};
const handleDelete = () => {
return deleteAssets(config.selectedIds).then(() => {
setConfig({
...config,
selectedIds: [],
assets: config.assets.filter((a) => !config.selectedIds.includes(a.id)),
});
})
}
const handleOffsetComplete = () => {
setConfig({
...config,
selectedIds: [],
});
}
const handleChange = (e: { sortOrder: "asc" | "desc" }) => {
setConfig({ ...config, sortOrder: e.sortOrder });
}
return (
<PageLayout className="!p-0 !mb-0">
<PageLayout className="!p-0 !mb-0 relative">
<Header
leftComponent="Missing Location"
rightComponent={
<>
<Badge variant={"outline"}>
{config.selectedIds.length} Selected
</Badge>
{config.selectedIds.length === config.assets.length ? (
<Button
variant={"outline"}
onClick={() =>
setConfig({
...config,
selectedIds: [],
})
}
>
Unselect all
<div className="flex items-center gap-2">
<Select value={groupBy} onValueChange={(value) => {
push({
pathname: "/assets/missing-locations",
query: {
...query,
groupBy: value,
startDate: undefined,
albumId: undefined,
},
});
}}>
<SelectTrigger>
<SelectValue placeholder="Group by" />
</SelectTrigger>
<SelectContent>
<SelectItem value="album">Album</SelectItem>
<SelectItem value="date">Date</SelectItem>
</SelectContent>
</Select>
<div>
<Button variant="default" size="sm" onClick={() => handleChange({ sortOrder: config.sortOrder === "asc" ? "desc" : "asc" })}>
{config.sortOrder === "asc" ? <SortAsc size={16} /> : <SortDesc size={16} />}
</Button>
) : (
<Button
variant={"outline"}
onClick={() =>
setConfig({
...config,
selectedIds: config.assets.map((a) => a.id),
})
}
>
Select all
</Button>
)}
<TagMissingLocationDialog onSubmit={handleSubmit} />
<AssetsOptions assets={selectedAssets} onAdd={() => { }} />
</>
</div>
</div>
}
/>
<MissingLocationContext.Provider
@@ -89,9 +107,60 @@ export default function MissingLocations() {
}}
>
<div className="flex divide-y">
<MissingLocationDates />
<MissingLocationAssets />
<MissingLocationDates groupBy={groupBy as "date" | "album"} />
<MissingLocationAssets groupBy={groupBy as "date" | "album"} />
</div>
<FloatingBar>
<div className="flex items-center gap-2 justify-between w-full">
<p className="text-sm text-muted-foreground">
{config.selectedIds.length} Selected
</p>
<div className="flex items-center gap-2">
{config.selectedIds.length === config.assets.length ? (
<Button
variant={"outline"}
size={"sm"}
onClick={() =>
setConfig({
...config,
selectedIds: [],
})
}
>
Unselect all
</Button>
) : (
<Button
variant={"outline"}
size={"sm"}
onClick={() =>
setConfig({
...config,
selectedIds: config.assets.map((a) => a.id),
})
}
>
Select all
</Button>
)}
{/* Seperator */}
<TagMissingLocationDialog onSubmit={handleSubmit} />
<AssetOffsetDialog assets={selectedAssets} onComplete={handleOffsetComplete} />
<div className="h-[10px] w-[1px] bg-zinc-500 dark:bg-zinc-600"></div>
<AlertDialog
title="Delete the selected assets?"
description="This action will delete the selected assets and cannot be undone."
onConfirm={handleDelete}
disabled={config.selectedIds.length === 0}
>
<Button variant={"destructive"} size={"sm"} disabled={config.selectedIds.length === 0}>
Delete
</Button>
</AlertDialog>
</div>
</div>
</FloatingBar>
</MissingLocationContext.Provider>
</PageLayout>
);
+186
View File
@@ -0,0 +1,186 @@
import "yet-another-react-lightbox/styles.css";
import FindInput from '@/components/find/FindInput';
import PageLayout from '@/components/layouts/PageLayout';
import Header from '@/components/shared/Header';
import Loader from '@/components/ui/loader';
import { ASSET_PREVIEW_PATH, ASSET_THUMBNAIL_PATH } from '@/config/routes';
import { useConfig } from '@/contexts/ConfigContext';
import { findAssets } from '@/handlers/api/asset.handler';
import { IAsset } from '@/types/asset';
import { ArrowUpRight, Captions, Megaphone, Search, Speaker, TriangleAlert, WandSparkles } from 'lucide-react';
import Image from 'next/image';
import React, { useMemo, useState } from 'react'
import Lightbox from 'yet-another-react-lightbox';
import { Button } from "@/components/ui/button";
import Link from "next/link";
import AssetGrid from "@/components/shared/AssetGrid";
import FloatingBar from "@/components/shared/FloatingBar";
import AssetsBulkDeleteButton from "@/components/shared/AssetsBulkDeleteButton";
interface IFindFilters {
[key: string]: string;
}
const FILTER_KEY_MAP = {
"city": "City",
"state": "State",
"country": "Country",
"takenAfter": "Taken After",
"takenBefore": "Taken Before",
"size": "Size",
"model": "Model",
"personIds": "People",
}
export default function FindPage() {
const [selectedIds, setSelectedIds] = useState<string[]>([]);
const { geminiEnabled, exImmichUrl } = useConfig();
const [query, setQuery] = useState('');
const [assets, setAssets] = useState<IAsset[]>([]);
const [loading, setLoading] = useState(false);
const [filters, setFilters] = useState<IFindFilters>({});
const slides = useMemo(
() =>
assets.map((asset) => ({
src: ASSET_PREVIEW_PATH(asset.id),
width: 1000,
height: 1000,
})),
[assets]
);
const appliedFilters: {
label: string;
value: string;
}[] = useMemo(() => {
return Object.entries(filters)
.filter(([_key, value]) => {
if (Array.isArray(value)) {
return value.length > 0;
}
return value !== undefined && value !== null && value !== '';
})
.map(([key, value]) => ({
label: key,
value: Array.isArray(value) ? value.join(', ') : value,
}))
.filter((filter) => filter.label !== "query");
}, [filters]);
const handleSearch = (query: string) => {
setQuery(query);
setLoading(true);
findAssets(query)
.then(({ assets, filters: _filters }) => {
setAssets(assets);
setFilters(_filters);
})
.finally(() => {
setLoading(false);
});
}
const handleSelectionChange = (ids: string[]) => {
setSelectedIds(ids);
}
const handleDelete = (ids: string[]) => {
setSelectedIds([]);
setAssets(assets.filter((asset) => !ids.includes(asset.id)));
}
const renderFilters = () => {
if (appliedFilters.length === 0) return null;
return (
<div className="flex gap-2 flex-wrap px-2">
{appliedFilters.map((filter) => (
<div key={filter.label} className="flex gap-2 items-center divide-x divide-gray-400 dark:divide-zinc-800 bg-zinc-100 dark:bg-zinc-800 border border-gray-400 dark:border-zinc-800 rounded-md px-2">
<p className="text-sm text-gray-500 dark:text-zinc-400">{FILTER_KEY_MAP[filter.label as keyof typeof FILTER_KEY_MAP] || filter.label}</p>
<p className="text-sm text-gray-500 dark:text-zinc-400 pl-1.5">{filter.value}</p>
</div>
))}
</div>
)
}
const renderContent = () => {
if (loading) {
return <div className="flex justify-center items-center h-full">
<Loader />
</div>
}
else if (query.length === 0) {
return (
<div className="flex justify-center flex-col gap-2 items-center h-full">
<Search className='w-10 h-10 text-muted-foreground' />
<p className='text-lg font-bold'>Search for photos in natural language</p>
<p className='text-sm text-muted-foreground'>
Example: Sunset photos from last week. Use <kbd className='bg-zinc-200 text-black dark:text-white px-1 py-0.5 rounded-md dark:bg-zinc-500'>@</kbd> to search for photos of a specific person.
</p>
<p className='text-xs text-muted-foreground text-center flex gap-1 items-center'>
<span>Power tools uses Google Gemini only for parsing your query. None of your data is sent to Gemini.</span>
</p>
</div>
)
}
else if (assets.length === 0) {
return <div className="flex justify-center items-center h-full flex-col gap-2">
<TriangleAlert className='w-10 h-10 text-muted-foreground' />
<p className='text-lg font-bold'>No results found for the below filters</p>
<p className='text-sm text-muted-foreground'>
{renderFilters()}
</p>
</div>
}
return (
<>
{renderFilters()}
<div className="w-full">
<AssetGrid assets={assets} selectable onSelectionChange={handleSelectionChange} />
{selectedIds.length > 0 && (
<FloatingBar>
<p className="text-sm text-muted-foreground">
{selectedIds.length} Selected
</p>
<AssetsBulkDeleteButton
selectedIds={selectedIds}
onDelete={handleDelete}
/>
</FloatingBar>
)}
</div>
</>
)
}
return (
<PageLayout>
<Header leftComponent="Find" />
{geminiEnabled ? (
<>
<div className="flex flex-col gap-4 p-2">
<FindInput onSearch={handleSearch} />
</div>
{renderContent()}
</>
) : (
<div className="flex justify-center py-10 items-center h-full flex-col gap-2">
<WandSparkles className='w-10 h-10 text-muted-foreground' />
<p className='text-lg font-semibold'>Google Gemini is not enabled</p>
<p className='text-sm text-muted-foreground max-w-md text-center'>
Currently, the Power Tools Find is relying on Google Gemini for parsing the query.
Please enable Gemini by adding <kbd className='bg-zinc-200 text-black dark:text-white px-1 py-0.5 rounded-md dark:bg-zinc-500'>GEMINI_API_KEY</kbd> in the <kbd className='bg-zinc-200 text-black dark:text-white px-1 py-0.5 rounded-md dark:bg-zinc-500'>.env</kbd> file.
</p>
<div className="border border-l-4 border-zinc-200 dark:border-zinc-500 rounded-md p-2">
<p className='text-xs text-muted-foreground text-center flex gap-1 items-center'>
<span>Power tools uses Google Gemini only for parsing your query. None of your data is sent to Gemini.</span>
</p>
</div>
</div>
)}
</PageLayout>
)
}
+132
View File
@@ -0,0 +1,132 @@
import React, { useEffect, useMemo, useState } from 'react'
import { Player } from '@remotion/player';
import { IntroComposition } from '../../remotion/Composition';
import PageLayout from '@/components/layouts/PageLayout';
import { getRewindStats } from '@/handlers/api/common.handler';
import { ASSET_THUMBNAIL_PATH, PERSON_THUBNAIL_PATH } from '@/config/routes';
import Loader from '@/components/ui/loader';
interface IStats {
name: string;
numberOfPhotos: number;
countriesInYear: any[];
countOfCities: number;
albumsWithMostPhotos: any[];
peopleWithMostPhotos: any[];
favoritedAssets: string[];
}
const getScenes = (stats: IStats) => [
{
message: `Welcome ${stats.name}!`,
type: "WELCOME",
emoji: "👋",
data: {},
},
{
message: "2024! So much memories!",
type: "TITLE",
emoji: "📅",
data: {
photos: stats.numberOfPhotos,
},
},
{
message: `You've been to ${stats.countriesInYear.length} new countries!`, type: "COUNTRY", emoji: "🌍", data: {
countries: stats.countriesInYear,
},
},
{
message: `And ${stats.countOfCities} new cities!`, type: "CITY", emoji: "🏙️", data: {
cities: stats.countOfCities,
},
},
{
message: "Here are some of my favorite memories from this year!", type: "MEMORY", emoji: "🎉", data: {
photos: stats.albumsWithMostPhotos,
images: stats.favoritedAssets.map((assetId) => ASSET_THUMBNAIL_PATH(assetId)),
},
},
{
message: "The most memory filled album of all time!", type: "ALBUM", emoji: "📸", data: {
photos: stats.albumsWithMostPhotos,
albums: stats.albumsWithMostPhotos.map((album) => ({
name: album.name,
cover: ASSET_THUMBNAIL_PATH(album.cover),
})),
},
},
{
message: "You made so much memory with", type: "FRIEND", emoji: "👯", data: {
friends: stats.peopleWithMostPhotos.map((person) => ({
name: person.name,
cover: PERSON_THUBNAIL_PATH(person.id),
})),
},
},
{
message: "Lets see what 2025 has in store!", type: "END", emoji: "🚀", data: {
},
},
]
export default function RewindPage() {
const [stats, setStats] = useState<any>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const fetchStats = async () => {
getRewindStats().then((stats) => {
setStats(stats);
setLoading(false);
}).catch((error) => {
setError(error);
setLoading(false);
});
}
const scenes = useMemo(() => {
if (!stats) return [];
return getScenes(stats);
}, [stats]);
useEffect(() => {
fetchStats();
}, []);
if (loading) return <Loader />
if (error) return <div>Error: {error}</div>;
return (
<PageLayout>
<div className="flex justify-center flex-col items-center w-full h-full gap-2">
<p className='text-2xl font-bold'>
Your 2024 Rewind 🚀
</p>
<Player
className="rounded-lg"
component={IntroComposition}
inputProps={{ scenes: scenes }}
durationInFrames={scenes.length * 120}
compositionWidth={720}
compositionHeight={1280}
fps={30}
style={{
width: 720 / 2,
height: 1280 / 2,
}}
controls
/>
</div>
</PageLayout>
)
}
Loaded 100 of 106 files, more files were not shown because too many files have changed in this diff. Show more