Compare commits

...

16 Commits

Author SHA1 Message Date
Alex Tran
e84c705e31 Added changelog to Fdroid 2022-07-03 10:49:37 -05:00
Alex Tran
36162509e0 Up version for release 2022-07-03 10:39:09 -05:00
Alex
76bf1c0379 Remove thumbnail generation on mobile app (#292)
* Remove thumbnail generation on mobile

* Remove tconditions for missing thumbnail on the backend

* Remove console.log

* Refactor queue systems

* Convert queue and processor name to constant

* Added corresponding interface to job queue
2022-07-02 21:06:36 -05:00
Alex
32b847c26e Fixed event propagation trigger navigating twice (#293) 2022-07-01 20:49:41 -05:00
Alex
a45d6fdf57 Fix server crash on bad file operation and other optimizations (#291)
* Fixed issue with generating thumbnail for video with 0 length cause undefined file and crash the server
* Added all file error handling operation
* Temporarily disabled WebSocket on the web because receiving a new upload event doesn't put the new file in the correct place. 
* Cosmetic fixed on the info panel
2022-07-01 12:00:12 -05:00
Zack Pollard
c071e64a7e infra: switch port to 3003 for machine learning container (#290)
* infra: switch port to 3003 for machine learning container

fixes #289

* Changed port of machine-learning-endpoint to match with new port

Co-authored-by: Alex Tran <alex.tran1502@gmail.com>
2022-07-01 10:20:04 -05:00
Alex
663f12851e Fixed filename duplication when upload from web (#288)
* Fixed filename duplication when upload from web

* Fixed cosmetic of detail panel view
2022-06-30 20:43:33 -05:00
xpwmaosldk
c4ef523564 Optimize mobile - Avoid creating unnecessary widgets (#268)
* Avoid creating unnecessary widgets

* more flexible null handling and runtime errors prevention
2022-06-30 20:08:49 -05:00
Alex
992f792c0a Fixed admin is forced to change password on mobile app (#287)
* Fixed issues

* Upversion and add changed log
2022-06-30 13:59:02 -05:00
Alex Tran
97611fa057 Fixed issue with unexposed Nginx port on release image 2022-06-30 00:26:54 -05:00
Alex Tran
32240777c3 fixed release build directory for Github action 2022-06-30 00:10:01 -05:00
Alex Tran
6065ff8caa Update readme with new discord invitation link 2022-06-29 23:50:24 -05:00
Alex Tran
8db073941d Up server version for release 2022-06-29 21:54:57 -05:00
Alex
5e281b44e9 Add Podman Support (#278) 2022-06-29 21:49:35 -05:00
Zack Pollard
142ede350e feat: create immich-nginx container to remove default nginx config setup (#280)
* feat: create immich-proxy container to remove default nginx config setup

* infra: make production docker-compose point at release builds for stability

* Fixed nginx config file was overriden by default.conf in nginx container; Fixed docker-compose.dev; Added additional tag 'release' for tagging after release build in Github Action

Co-authored-by: Alex Tran <alex.tran1502@gmail.com>
2022-06-29 21:24:55 -05:00
Alex
a2e1d4caa2 Update server dependencies and fixed Typeorm API changes in new version (#276)
* Fixed dependencies

* Adapt typeorm API to be compatible with new version

* Fixed typeorm API in tests

* Remove console.log
2022-06-29 13:39:58 -05:00
87 changed files with 2124 additions and 1985 deletions

View File

@@ -91,3 +91,30 @@ jobs:
push: true push: true
tags: | tags: |
altran1502/immich-web:latest altran1502/immich-web:latest
build_and_push_nginx_latest:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Set up QEMU
uses: docker/setup-qemu-action@v2.0.0
- name: Set up Docker Buildx
id: buildx
uses: docker/setup-buildx-action@v2.0.0
- name: Login to Docker Hub
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Build and Push Proxy
uses: docker/build-push-action@v3.0.0
with:
context: ./nginx
file: ./nginx/Dockerfile
platforms: linux/arm/v7,linux/amd64,linux/arm64
push: true
tags: |
altran1502/immich-proxy:latest

View File

@@ -93,3 +93,30 @@ jobs:
push: ${{ github.event_name == 'pull_request' }} push: ${{ github.event_name == 'pull_request' }}
tags: | tags: |
altran1502/immich-web:staging altran1502/immich-web:staging
build_and_push_nginx_staging:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Set up QEMU
uses: docker/setup-qemu-action@v2.0.0
- name: Set up Docker Buildx
id: buildx
uses: docker/setup-buildx-action@v2.0.0
- name: Login to Docker Hub
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Build and Push Proxy
uses: docker/build-push-action@v3.0.0
with:
context: ./nginx
file: ./nginx/Dockerfile
platforms: linux/arm/v7,linux/amd64,linux/arm64
push: ${{ github.event_name == 'pull_request' }}
tags: |
altran1502/immich-proxy:staging

View File

@@ -43,6 +43,7 @@ jobs:
push: ${{ github.event_name != 'pull_request' }} push: ${{ github.event_name != 'pull_request' }}
tags: | tags: |
altran1502/immich-server:${{ steps.previoustag.outputs.tag }} altran1502/immich-server:${{ steps.previoustag.outputs.tag }}
altran1502/immich-server:release
build_and_push_machine_learning_release: build_and_push_machine_learning_release:
runs-on: ubuntu-latest runs-on: ubuntu-latest
@@ -75,6 +76,7 @@ jobs:
push: true push: true
tags: | tags: |
altran1502/immich-machine-learning:${{ steps.previoustag.outputs.tag }} altran1502/immich-machine-learning:${{ steps.previoustag.outputs.tag }}
altran1502/immich-machine-learning:release
build_and_push_web_release: build_and_push_web_release:
runs-on: ubuntu-latest runs-on: ubuntu-latest
@@ -114,3 +116,43 @@ jobs:
target: prod target: prod
tags: | tags: |
altran1502/immich-web:${{ steps.previoustag.outputs.tag }} altran1502/immich-web:${{ steps.previoustag.outputs.tag }}
altran1502/immich-web:release
build_and_push_nginx_release:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
with:
ref: "main"
fetch-depth: 0
- name: "Get Previous tag"
id: previoustag
uses: "WyriHaximus/github-action-get-previous-tag@v1"
with:
fallback: latest
- name: Set up QEMU
uses: docker/setup-qemu-action@v2.0.0
- name: Set up Docker Buildx
id: buildx
uses: docker/setup-buildx-action@v2.0.0
- name: Login to Docker Hub
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Build and push immich-proxy release
uses: docker/build-push-action@v3.0.0
with:
context: ./nginx
file: ./nginx/Dockerfile
platforms: linux/arm/v7,linux/amd64,linux/arm64
push: ${{ github.event_name != 'pull_request' }}
tags: |
altran1502/immich-proxy:release
altran1502/immich-proxy:${{ steps.previoustag.outputs.tag }}

View File

@@ -10,7 +10,7 @@
<a href="https://actions-badge.atrox.dev/alextran1502/immich/goto?ref=main"> <a href="https://actions-badge.atrox.dev/alextran1502/immich/goto?ref=main">
<img alt="Build Status" src="https://img.shields.io/endpoint.svg?url=https%3A%2F%2Factions-badge.atrox.dev%2Falextran1502%2Fimmich%2Fbadge%3Fref%3Dmain&style=for-the-badge&label=Github Action&logo=github&labelColor=ececec&logoColor=000000" /> <img alt="Build Status" src="https://img.shields.io/endpoint.svg?url=https%3A%2F%2Factions-badge.atrox.dev%2Falextran1502%2Fimmich%2Fbadge%3Fref%3Dmain&style=for-the-badge&label=Github Action&logo=github&labelColor=ececec&logoColor=000000" />
</a> </a>
<a href="https://discord.gg/rxnyVTXGbM"> <a href="https://discord.gg/D8JsnBEuKb">
<img src="https://img.shields.io/discord/979116623879368755.svg?label=Immich%20Discord&logo=Discord&style=for-the-badge&logoColor=000000&labelColor=ececec" atl="Immich Discord"/> <img src="https://img.shields.io/discord/979116623879368755.svg?label=Immich%20Discord&logo=Discord&style=for-the-badge&logoColor=000000&labelColor=ececec" atl="Immich Discord"/>
</a> </a>
<br/> <br/>

View File

@@ -7,8 +7,6 @@ services:
context: ../server context: ../server
dockerfile: Dockerfile dockerfile: Dockerfile
command: npm run start:dev immich command: npm run start:dev immich
expose:
- "3000"
volumes: volumes:
- ../server:/usr/src/app - ../server:/usr/src/app
- ${UPLOAD_LOCATION}:/usr/src/app/upload - ${UPLOAD_LOCATION}:/usr/src/app/upload
@@ -27,8 +25,6 @@ services:
context: ../machine-learning context: ../machine-learning
dockerfile: Dockerfile dockerfile: Dockerfile
command: npm run start:dev command: npm run start:dev
expose:
- "3001"
volumes: volumes:
- ../machine-learning:/usr/src/app - ../machine-learning:/usr/src/app
- ${UPLOAD_LOCATION}:/usr/src/app/upload - ${UPLOAD_LOCATION}:/usr/src/app/upload
@@ -94,11 +90,12 @@ services:
ports: ports:
- 5432:5432 - 5432:5432
nginx: immich-proxy:
container_name: proxy_nginx container_name: immich_proxy
image: nginx:latest image: immich-proxy-dev:latest
volumes: build:
- ./settings/nginx-conf:/etc/nginx/conf.d context: ../nginx
dockerfile: Dockerfile
ports: ports:
- 2283:80 - 2283:80
- 2284:443 - 2284:443
@@ -106,6 +103,7 @@ services:
driver: none driver: none
depends_on: depends_on:
- immich-server - immich-server
restart: always
volumes: volumes:
pgdata: pgdata:

View File

@@ -68,11 +68,9 @@ services:
- pgdata:/var/lib/postgresql/data - pgdata:/var/lib/postgresql/data
restart: always restart: always
nginx: immich-proxy:
container_name: proxy_nginx container_name: immich_proxy
image: nginx:latest image: altran1502/immich-proxy:staging
volumes:
- ./settings/nginx-conf:/etc/nginx/conf.d
ports: ports:
- 2283:80 - 2283:80
- 2284:443 - 2284:443

View File

@@ -2,7 +2,7 @@ version: "3.8"
services: services:
immich-server: immich-server:
image: altran1502/immich-server:latest image: altran1502/immich-server:release
entrypoint: ["/bin/sh", "./start-server.sh"] entrypoint: ["/bin/sh", "./start-server.sh"]
volumes: volumes:
- ${UPLOAD_LOCATION}:/usr/src/app/upload - ${UPLOAD_LOCATION}:/usr/src/app/upload
@@ -16,7 +16,7 @@ services:
restart: always restart: always
immich-microservices: immich-microservices:
image: altran1502/immich-server:latest image: altran1502/immich-server:release
entrypoint: ["/bin/sh", "./start-microservices.sh"] entrypoint: ["/bin/sh", "./start-microservices.sh"]
volumes: volumes:
- ${UPLOAD_LOCATION}:/usr/src/app/upload - ${UPLOAD_LOCATION}:/usr/src/app/upload
@@ -30,7 +30,7 @@ services:
restart: always restart: always
immich-machine-learning: immich-machine-learning:
image: altran1502/immich-machine-learning:latest image: altran1502/immich-machine-learning:release
entrypoint: ["/bin/sh", "./entrypoint.sh"] entrypoint: ["/bin/sh", "./entrypoint.sh"]
volumes: volumes:
- ${UPLOAD_LOCATION}:/usr/src/app/upload - ${UPLOAD_LOCATION}:/usr/src/app/upload
@@ -43,7 +43,7 @@ services:
restart: always restart: always
immich-web: immich-web:
image: altran1502/immich-web:latest image: altran1502/immich-web:release
entrypoint: ["/bin/sh", "./entrypoint.sh"] entrypoint: ["/bin/sh", "./entrypoint.sh"]
env_file: env_file:
- .env - .env
@@ -68,11 +68,9 @@ services:
- pgdata:/var/lib/postgresql/data - pgdata:/var/lib/postgresql/data
restart: always restart: always
nginx: immich-proxy:
container_name: proxy_nginx container_name: immich_proxy
image: nginx:latest image: altran1502/immich-proxy:release
volumes:
- ./settings/nginx-conf:/etc/nginx/conf.d
ports: ports:
- 2283:80 - 2283:80
- 2284:443 - 2284:443

View File

@@ -5,7 +5,7 @@ import { Logger } from '@nestjs/common';
async function bootstrap() { async function bootstrap() {
const app = await NestFactory.create(AppModule); const app = await NestFactory.create(AppModule);
await app.listen(3001, () => { await app.listen(3003, () => {
if (process.env.NODE_ENV == 'development') { if (process.env.NODE_ENV == 'development') {
Logger.log( Logger.log(
'Running Immich Machine Learning in DEVELOPMENT environment', 'Running Immich Machine Learning in DEVELOPMENT environment',

View File

@@ -0,0 +1,2 @@
* Fixed admin is forced to change password upon logging in on mobile app
* Fixed change password form validation

View File

@@ -0,0 +1 @@
* Removed thumbnail generation on mobile - the operation now will be on the server to reduce CPU load and battery usage.

View File

@@ -19,7 +19,7 @@ platform :ios do
desc "iOS Beta" desc "iOS Beta"
lane :beta do lane :beta do
increment_version_number( increment_version_number(
version_number: "1.14.0" version_number: "1.16.0"
) )
increment_build_number( increment_build_number(
build_number: latest_testflight_build_number + 1, build_number: latest_testflight_build_number + 1,

View File

@@ -39,14 +39,10 @@ class ImageViewerService {
entity = await PhotoManager.editor.saveVideo(tempFile, title: fileName); entity = await PhotoManager.editor.saveVideo(tempFile, title: fileName);
} }
if (entity != null) { return entity != null;
return true;
}
} catch (e) { } catch (e) {
debugPrint("Error saving file $e"); debugPrint("Error saving file $e");
return false; return false;
} }
return false;
} }
} }

View File

@@ -15,81 +15,72 @@ class ExifBottomSheet extends ConsumerWidget {
@override @override
Widget build(BuildContext context, WidgetRef ref) { Widget build(BuildContext context, WidgetRef ref) {
_buildMap() { _buildMap() {
return (assetDetail.exifInfo!.latitude != null && return Padding(
assetDetail.exifInfo!.longitude != null) padding: const EdgeInsets.symmetric(vertical: 16.0),
? Padding( child: Container(
padding: const EdgeInsets.symmetric(vertical: 16.0), height: 150,
child: Container( width: MediaQuery.of(context).size.width,
height: 150, decoration: const BoxDecoration(
width: MediaQuery.of(context).size.width, borderRadius: BorderRadius.all(Radius.circular(15)),
decoration: const BoxDecoration( ),
borderRadius: BorderRadius.all(Radius.circular(15)), child: FlutterMap(
), options: MapOptions(
child: FlutterMap( center: LatLng(assetDetail.exifInfo!.latitude!,
options: MapOptions( assetDetail.exifInfo!.longitude!),
center: LatLng(assetDetail.exifInfo!.latitude!, zoom: 16.0,
assetDetail.exifInfo!.longitude!), ),
zoom: 16.0, layers: [
), TileLayerOptions(
layers: [ urlTemplate:
TileLayerOptions( "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
urlTemplate: subdomains: ['a', 'b', 'c'],
"https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", attributionBuilder: (_) {
subdomains: ['a', 'b', 'c'], return const Text(
attributionBuilder: (_) { "© OpenStreetMap",
return const Text( style: TextStyle(fontSize: 10),
"© OpenStreetMap", );
style: TextStyle(fontSize: 10), },
);
},
),
MarkerLayerOptions(
markers: [
Marker(
anchorPos: AnchorPos.align(AnchorAlign.top),
point: LatLng(assetDetail.exifInfo!.latitude!,
assetDetail.exifInfo!.longitude!),
builder: (ctx) => const Image(
image: AssetImage('assets/location-pin.png')),
),
],
),
],
),
), ),
) MarkerLayerOptions(
: Container(); markers: [
Marker(
anchorPos: AnchorPos.align(AnchorAlign.top),
point: LatLng(assetDetail.exifInfo!.latitude!,
assetDetail.exifInfo!.longitude!),
builder: (ctx) => const Image(
image: AssetImage('assets/location-pin.png')),
),
],
),
],
),
),
);
} }
_buildLocationText() { _buildLocationText() {
return (assetDetail.exifInfo!.city != null && return Text(
assetDetail.exifInfo!.state != null) "${assetDetail.exifInfo!.city}, ${assetDetail.exifInfo!.state}",
? Text( style: TextStyle(
"${assetDetail.exifInfo!.city}, ${assetDetail.exifInfo!.state}", fontSize: 12, color: Colors.grey[200], fontWeight: FontWeight.bold),
style: TextStyle( );
fontSize: 12,
color: Colors.grey[200],
fontWeight: FontWeight.bold),
)
: Container();
} }
return Padding( return Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 8), padding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 8),
child: ListView( child: ListView(
children: [ children: [
assetDetail.exifInfo?.dateTimeOriginal != null if (assetDetail.exifInfo?.dateTimeOriginal != null)
? Text( Text(
DateFormat('E, LLL d, y • h:mm a').format( DateFormat('E, LLL d, y • h:mm a').format(
DateTime.parse(assetDetail.exifInfo!.dateTimeOriginal!), DateTime.parse(assetDetail.exifInfo!.dateTimeOriginal!),
), ),
style: TextStyle( style: TextStyle(
color: Colors.grey[400], color: Colors.grey[400],
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
fontSize: 14, fontSize: 14,
), ),
) ),
: Container(),
Padding( Padding(
padding: const EdgeInsets.only(top: 16.0), padding: const EdgeInsets.only(top: 16.0),
child: Text( child: Text(
@@ -102,84 +93,83 @@ class ExifBottomSheet extends ConsumerWidget {
), ),
// Location // Location
assetDetail.exifInfo?.latitude != null if (assetDetail.exifInfo?.latitude != null)
? Padding( Padding(
padding: const EdgeInsets.only(top: 32.0), padding: const EdgeInsets.only(top: 32.0),
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Divider( Divider(
thickness: 1, thickness: 1,
color: Colors.grey[600], color: Colors.grey[600],
),
Text(
"LOCATION",
style: TextStyle(fontSize: 11, color: Colors.grey[400]),
),
_buildMap(),
_buildLocationText(),
Text(
"${assetDetail.exifInfo!.latitude!.toStringAsFixed(4)}, ${assetDetail.exifInfo!.longitude!.toStringAsFixed(4)}",
style: TextStyle(fontSize: 12, color: Colors.grey[400]),
)
],
), ),
) Text(
: Container(), "LOCATION",
style: TextStyle(fontSize: 11, color: Colors.grey[400]),
),
if (assetDetail.exifInfo?.latitude != null &&
assetDetail.exifInfo?.longitude != null)
_buildMap(),
if (assetDetail.exifInfo?.city != null &&
assetDetail.exifInfo?.state != null)
_buildLocationText(),
Text(
"${assetDetail.exifInfo?.latitude?.toStringAsFixed(4)}, ${assetDetail.exifInfo?.longitude?.toStringAsFixed(4)}",
style: TextStyle(fontSize: 12, color: Colors.grey[400]),
)
],
),
),
// Detail // Detail
assetDetail.exifInfo != null if (assetDetail.exifInfo != null)
? Padding( Padding(
padding: const EdgeInsets.only(top: 32.0), padding: const EdgeInsets.only(top: 32.0),
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Divider( Divider(
thickness: 1, thickness: 1,
color: Colors.grey[600], color: Colors.grey[600],
),
Padding(
padding: const EdgeInsets.only(bottom: 8.0),
child: Text(
"DETAILS",
style:
TextStyle(fontSize: 11, color: Colors.grey[400]),
),
),
ListTile(
contentPadding: const EdgeInsets.all(0),
dense: true,
textColor: Colors.grey[300],
iconColor: Colors.grey[300],
leading: const Icon(Icons.image),
title: Text(
"${assetDetail.exifInfo?.imageName!}${p.extension(assetDetail.originalPath)}",
style: const TextStyle(fontWeight: FontWeight.bold),
),
subtitle: assetDetail.exifInfo?.exifImageHeight != null
? Text(
"${assetDetail.exifInfo?.exifImageHeight} x ${assetDetail.exifInfo?.exifImageWidth} ${assetDetail.exifInfo?.fileSizeInByte!}B ")
: Container(),
),
assetDetail.exifInfo?.make != null
? ListTile(
contentPadding: const EdgeInsets.all(0),
dense: true,
textColor: Colors.grey[300],
iconColor: Colors.grey[300],
leading: const Icon(Icons.camera),
title: Text(
"${assetDetail.exifInfo?.make} ${assetDetail.exifInfo?.model}",
style: const TextStyle(
fontWeight: FontWeight.bold),
),
subtitle: Text(
"ƒ/${assetDetail.exifInfo?.fNumber} 1/${(1 / assetDetail.exifInfo!.exposureTime!).toStringAsFixed(0)} ${assetDetail.exifInfo?.focalLength}mm ISO${assetDetail.exifInfo?.iso} "),
)
: Container()
],
), ),
) Padding(
: Container() padding: const EdgeInsets.only(bottom: 8.0),
child: Text(
"DETAILS",
style: TextStyle(fontSize: 11, color: Colors.grey[400]),
),
),
ListTile(
contentPadding: const EdgeInsets.all(0),
dense: true,
textColor: Colors.grey[300],
iconColor: Colors.grey[300],
leading: const Icon(Icons.image),
title: Text(
"${assetDetail.exifInfo?.imageName!}${p.extension(assetDetail.originalPath)}",
style: const TextStyle(fontWeight: FontWeight.bold),
),
subtitle: assetDetail.exifInfo?.exifImageHeight != null
? Text(
"${assetDetail.exifInfo?.exifImageHeight} x ${assetDetail.exifInfo?.exifImageWidth} ${assetDetail.exifInfo?.fileSizeInByte!}B ")
: null,
),
if (assetDetail.exifInfo?.make != null)
ListTile(
contentPadding: const EdgeInsets.all(0),
dense: true,
textColor: Colors.grey[300],
iconColor: Colors.grey[300],
leading: const Icon(Icons.camera),
title: Text(
"${assetDetail.exifInfo?.make} ${assetDetail.exifInfo?.model}",
style: const TextStyle(fontWeight: FontWeight.bold),
),
subtitle: Text(
"ƒ/${assetDetail.exifInfo?.fNumber} 1/${(1 / (assetDetail.exifInfo?.exposureTime ?? 1)).toStringAsFixed(0)} ${assetDetail.exifInfo?.focalLength}mm ISO${assetDetail.exifInfo?.iso} "),
),
],
),
),
], ],
), ),
); );

View File

@@ -147,8 +147,7 @@ class _VideoThumbnailPlayerState extends State<VideoThumbnailPlayer> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return chewieController != null && return chewieController?.videoPlayerController.value.isInitialized == true
chewieController!.videoPlayerController.value.isInitialized
? SizedBox( ? SizedBox(
child: Chewie( child: Chewie(
controller: chewieController!, controller: chewieController!,

View File

@@ -69,21 +69,6 @@ class BackupService {
), ),
); );
// Build thumbnail multipart data
var thumbnailData = await entity
.thumbnailDataWithSize(const ThumbnailSize(1440, 2560));
if (thumbnailData != null) {
thumbnailUploadData = http.MultipartFile.fromBytes(
"thumbnailData",
List.from(thumbnailData),
filename: fileNameWithoutPath,
contentType: MediaType(
"image",
"jpeg",
),
);
}
var box = Hive.box(userInfoBox); var box = Hive.box(userInfoBox);
var req = MultipartRequest( var req = MultipartRequest(
@@ -101,9 +86,6 @@ class BackupService {
req.fields['fileExtension'] = fileExtension; req.fields['fileExtension'] = fileExtension;
req.fields['duration'] = entity.videoDuration.toString(); req.fields['duration'] = entity.videoDuration.toString();
if (thumbnailUploadData != null) {
req.files.add(thumbnailUploadData);
}
req.files.add(assetRawUploadData); req.files.add(assetRawUploadData);
var res = await req.send(cancellationToken: cancelToken); var res = await req.send(cancellationToken: cancelToken);

View File

@@ -56,7 +56,7 @@ class AlbumInfoCard extends HookConsumerWidget {
); );
} }
return Container(); return const SizedBox();
} }
_buildImageFilter() { _buildImageFilter() {
@@ -151,7 +151,11 @@ class AlbumInfoCard extends HookConsumerWidget {
), ),
child: null, child: null,
), ),
Positioned(bottom: 10, left: 25, child: _buildSelectedTextBox()) Positioned(
bottom: 10,
left: 25,
child: _buildSelectedTextBox(),
)
], ],
), ),
Padding( Padding(
@@ -176,8 +180,7 @@ class AlbumInfoCard extends HookConsumerWidget {
Padding( Padding(
padding: const EdgeInsets.only(top: 2.0), padding: const EdgeInsets.only(top: 2.0),
child: Text( child: Text(
albumInfo.assetCount.toString() + '${albumInfo.assetCount} ${(albumInfo.isAll ? " (ALL)" : "")}',
(albumInfo.isAll ? " (ALL)" : ""),
style: TextStyle( style: TextStyle(
fontSize: 12, color: Colors.grey[600]), fontSize: 12, color: Colors.grey[600]),
), ),

View File

@@ -188,11 +188,7 @@ class BackupAlbumSelectionPage extends HookConsumerWidget {
color: Colors.grey[700]), color: Colors.grey[700]),
), ),
trailing: Text( trailing: Text(
ref '${ref.watch(backupProvider).allUniqueAssets.length}',
.watch(backupProvider)
.allUniqueAssets
.length
.toString(),
style: const TextStyle(fontWeight: FontWeight.bold), style: const TextStyle(fontWeight: FontWeight.bold),
), ),
), ),
@@ -203,7 +199,7 @@ class BackupAlbumSelectionPage extends HookConsumerWidget {
ListTile( ListTile(
title: Text( title: Text(
"Albums on device (${availableAlbums.length.toString()})", "Albums on device (${availableAlbums.length})",
style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 14), style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 14),
), ),
subtitle: Padding( subtitle: Padding(

View File

@@ -96,12 +96,11 @@ class BackupControllerPage extends HookConsumerWidget {
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
!isAutoBackup if (!isAutoBackup)
? const Text( const Text(
"Turn on backup to automatically upload new assets to the server.", "Turn on backup to automatically upload new assets to the server.",
style: TextStyle(fontSize: 14), style: TextStyle(fontSize: 14),
) ),
: Container(),
Padding( Padding(
padding: const EdgeInsets.only(top: 8.0), padding: const EdgeInsets.only(top: 8.0),
child: OutlinedButton( child: OutlinedButton(
@@ -189,7 +188,7 @@ class BackupControllerPage extends HookConsumerWidget {
), ),
); );
} else { } else {
return Container(); return const SizedBox();
} }
} }

View File

@@ -34,7 +34,7 @@ class DisableMultiSelectButton extends ConsumerWidget {
}, },
icon: const Icon(Icons.close_rounded), icon: const Icon(Icons.close_rounded),
label: Text( label: Text(
selectedItemCount.toString(), '$selectedItemCount',
style: const TextStyle( style: const TextStyle(
fontWeight: FontWeight.w600, fontSize: 18), fontWeight: FontWeight.w600, fontSize: 18),
)), )),

View File

@@ -615,7 +615,7 @@ class SlideFadeTransition extends StatelessWidget {
return AnimatedBuilder( return AnimatedBuilder(
animation: animation, animation: animation,
builder: (context, child) => builder: (context, child) =>
animation.value == 0.0 ? Container() : child!, animation.value == 0.0 ? const SizedBox() : child!,
child: SlideTransition( child: SlideTransition(
position: Tween( position: Tween(
begin: const Offset(0.3, 0.0), begin: const Offset(0.3, 0.0),

View File

@@ -25,30 +25,26 @@ class ImageGrid extends ConsumerWidget {
child: Stack( child: Stack(
children: [ children: [
ThumbnailImage(asset: assetGroup[index]), ThumbnailImage(asset: assetGroup[index]),
assetType == 'IMAGE' if (assetType != 'IMAGE')
? Container() Positioned(
: Positioned( top: 5,
top: 5, right: 5,
right: 5, child: Row(
child: Row( children: [
children: [ Text(
Text( assetGroup[index].duration.toString().substring(0, 7),
assetGroup[index] style: const TextStyle(
.duration color: Colors.white,
.toString() fontSize: 10,
.substring(0, 7), ),
style: const TextStyle(
color: Colors.white,
fontSize: 10,
),
),
const Icon(
Icons.play_circle_outline_rounded,
color: Colors.white,
),
],
), ),
) const Icon(
Icons.play_circle_outline_rounded,
color: Colors.white,
),
],
),
),
], ],
), ),
); );

View File

@@ -49,30 +49,29 @@ class ImmichSliverAppBar extends ConsumerWidget {
}, },
), ),
), ),
serverInfoState.isVersionMismatch if (serverInfoState.isVersionMismatch)
? Positioned( Positioned(
bottom: 12, bottom: 12,
right: 12, right: 12,
child: GestureDetector( child: GestureDetector(
onTap: () => Scaffold.of(context).openDrawer(), onTap: () => Scaffold.of(context).openDrawer(),
child: Material( child: Material(
color: Colors.grey[200], color: Colors.grey[200],
elevation: 1, elevation: 1,
shape: RoundedRectangleBorder( shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50.0), borderRadius: BorderRadius.circular(50.0),
), ),
child: const Padding( child: const Padding(
padding: EdgeInsets.all(2.0), padding: EdgeInsets.all(2.0),
child: Icon( child: Icon(
Icons.info, Icons.info,
color: Color.fromARGB(255, 243, 188, 106), color: Color.fromARGB(255, 243, 188, 106),
size: 15, size: 15,
),
),
), ),
), ),
) ),
: Container(), ),
),
], ],
); );
}, },
@@ -90,21 +89,20 @@ class ImmichSliverAppBar extends ConsumerWidget {
Stack( Stack(
alignment: AlignmentDirectional.center, alignment: AlignmentDirectional.center,
children: [ children: [
backupState.backupProgress == BackUpProgressEnum.inProgress if (backupState.backupProgress == BackUpProgressEnum.inProgress)
? Positioned( Positioned(
top: 10, top: 10,
right: 12, right: 12,
child: SizedBox( child: SizedBox(
height: 8, height: 8,
width: 8, width: 8,
child: CircularProgressIndicator( child: CircularProgressIndicator(
strokeWidth: 1, strokeWidth: 1,
valueColor: AlwaysStoppedAnimation<Color>( valueColor: AlwaysStoppedAnimation<Color>(
Theme.of(context).primaryColor), Theme.of(context).primaryColor),
), ),
), ),
) ),
: Container(),
IconButton( IconButton(
splashRadius: 25, splashRadius: 25,
iconSize: 30, iconSize: 30,
@@ -129,18 +127,15 @@ class ImmichSliverAppBar extends ConsumerWidget {
} }
}, },
), ),
backupState.backupProgress == BackUpProgressEnum.inProgress if (backupState.backupProgress == BackUpProgressEnum.inProgress)
? Positioned( Positioned(
bottom: 5, bottom: 5,
child: Text( child: Text(
(backupState.allUniqueAssets.length - '${backupState.allUniqueAssets.length - backupState.selectedAlbumsBackupAssetsIds.length}',
backupState.selectedAlbumsBackupAssetsIds.length) style:
.toString(), const TextStyle(fontSize: 9, fontWeight: FontWeight.bold),
style: const TextStyle( ),
fontSize: 9, fontWeight: FontWeight.bold), ),
),
)
: Container()
], ],
), ),
], ],

View File

@@ -87,7 +87,7 @@ class ProfileDrawer extends HookConsumerWidget {
return const ImmichLoadingIndicator(); return const ImmichLoadingIndicator();
} }
return Container(); return const SizedBox();
} }
_pickUserProfileImage() async { _pickUserProfileImage() async {

View File

@@ -122,17 +122,14 @@ class ThumbnailImage extends HookConsumerWidget {
}, },
), ),
), ),
Container( if (isMultiSelectEnable)
child: isMultiSelectEnable Padding(
? Padding( padding: const EdgeInsets.all(3.0),
padding: const EdgeInsets.all(3.0), child: Align(
child: Align( alignment: Alignment.topLeft,
alignment: Alignment.topLeft, child: _buildSelectionIcon(asset),
child: _buildSelectionIcon(asset), ),
), ),
)
: Container(),
),
Positioned( Positioned(
right: 10, right: 10,
bottom: 5, bottom: 5,

View File

@@ -38,17 +38,10 @@ class HomePage extends HookConsumerWidget {
} }
_buildSelectedItemCountIndicator() { _buildSelectedItemCountIndicator() {
return isMultiSelectEnable return DisableMultiSelectButton(
? DisableMultiSelectButton( onPressed: ref.watch(homePageStateProvider.notifier).disableMultiSelect,
onPressed: selectedItemCount: homePageState.selectedItems.length,
ref.watch(homePageStateProvider.notifier).disableMultiSelect, );
selectedItemCount: homePageState.selectedItems.length,
)
: Container();
}
_buildBottomAppBar() {
return isMultiSelectEnable ? const ControlBottomAppBar() : Container();
} }
Widget _buildBody() { Widget _buildBody() {
@@ -121,8 +114,10 @@ class HomePage extends HookConsumerWidget {
), ),
), ),
), ),
_buildSelectedItemCountIndicator(), if (isMultiSelectEnable) ...[
_buildBottomAppBar(), _buildSelectedItemCountIndicator(),
const ControlBottomAppBar(),
],
], ],
), ),
); );

View File

@@ -18,6 +18,7 @@ class ChangePasswordForm extends HookConsumerWidget {
final confirmPasswordController = final confirmPasswordController =
useTextEditingController.fromValue(TextEditingValue.empty); useTextEditingController.fromValue(TextEditingValue.empty);
final authState = ref.watch(authenticationProvider); final authState = ref.watch(authenticationProvider);
final formKey = GlobalKey<FormState>();
return Center( return Center(
child: ConstrainedBox( child: ConstrainedBox(
@@ -47,15 +48,24 @@ class ChangePasswordForm extends HookConsumerWidget {
), ),
), ),
), ),
PasswordInput(controller: passwordController), Form(
ConfirmPasswordInput( key: formKey,
originalController: passwordController, child: Column(
confirmController: confirmPasswordController, children: [
), PasswordInput(controller: passwordController),
Align( Padding(
alignment: Alignment.center, padding: const EdgeInsets.symmetric(vertical: 16.0),
child: ChangePasswordButton( child: ConfirmPasswordInput(
passwordController: passwordController), originalController: passwordController,
confirmController: confirmPasswordController,
),
),
ChangePasswordButton(
passwordController: passwordController,
formKey: formKey,
),
],
),
) )
], ],
), ),
@@ -119,10 +129,12 @@ class ConfirmPasswordInput extends StatelessWidget {
class ChangePasswordButton extends ConsumerWidget { class ChangePasswordButton extends ConsumerWidget {
final TextEditingController passwordController; final TextEditingController passwordController;
final GlobalKey<FormState> formKey;
const ChangePasswordButton({ const ChangePasswordButton({
Key? key, Key? key,
required this.passwordController, required this.passwordController,
required this.formKey,
}) : super(key: key); }) : super(key: key);
@override @override
@@ -136,19 +148,21 @@ class ChangePasswordButton extends ConsumerWidget {
padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 25), padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 25),
), ),
onPressed: () async { onPressed: () async {
var isSuccess = await ref if (formKey.currentState!.validate()) {
.watch(authenticationProvider.notifier) var isSuccess = await ref
.changePassword(passwordController.value.text); .watch(authenticationProvider.notifier)
.changePassword(passwordController.value.text);
if (isSuccess) { if (isSuccess) {
bool res = bool res =
await ref.watch(authenticationProvider.notifier).logout(); await ref.watch(authenticationProvider.notifier).logout();
if (res) { if (res) {
ref.watch(backupProvider.notifier).cancelBackup(); ref.watch(backupProvider.notifier).cancelBackup();
ref.watch(assetProvider.notifier).clearAllAsset(); ref.watch(assetProvider.notifier).clearAllAsset();
ref.watch(websocketProvider.notifier).disconnect(); ref.watch(websocketProvider.notifier).disconnect();
AutoRouter.of(context).replace(const LoginRoute()); AutoRouter.of(context).replace(const LoginRoute());
}
} }
} }
}, },

View File

@@ -107,19 +107,12 @@ class ServerEndpointInput extends StatelessWidget {
: super(key: key); : super(key: key);
String? _validateInput(String? url) { String? _validateInput(String? url) {
if (url == null) {
if (url?.startsWith(RegExp(r'https?://')) == true) {
return null; return null;
} } else {
if (url.isEmpty) {
return 'Server endpoint is required';
}
if (!url.startsWith(RegExp(r'https?://'))) {
return 'Please specify http:// or https://'; return 'Please specify http:// or https://';
} }
return null;
} }
@override @override
@@ -219,7 +212,8 @@ class LoginButton extends ConsumerWidget {
if (isAuthenticated) { if (isAuthenticated) {
// Resume backup (if enable) then navigate // Resume backup (if enable) then navigate
if (ref.watch(authenticationProvider).shouldChangePassword) { if (ref.watch(authenticationProvider).shouldChangePassword &&
!ref.watch(authenticationProvider).isAdmin) {
AutoRouter.of(context).push(const ChangePasswordRoute()); AutoRouter.of(context).push(const ChangePasswordRoute());
} else { } else {
ref.watch(backupProvider.notifier).resumeBackup(); ref.watch(backupProvider.notifier).resumeBackup();

View File

@@ -62,11 +62,7 @@ final getCuratedLocationProvider =
final SearchService searchService = ref.watch(searchServiceProvider); final SearchService searchService = ref.watch(searchServiceProvider);
var curatedLocation = await searchService.getCuratedLocation(); var curatedLocation = await searchService.getCuratedLocation();
if (curatedLocation != null) { return curatedLocation ?? [];
return curatedLocation;
} else {
return [];
}
}); });
final getCuratedObjectProvider = final getCuratedObjectProvider =
@@ -74,9 +70,6 @@ final getCuratedObjectProvider =
final SearchService searchService = ref.watch(searchServiceProvider); final SearchService searchService = ref.watch(searchServiceProvider);
var curatedObject = await searchService.getCuratedObjects(); var curatedObject = await searchService.getCuratedObjects();
if (curatedObject != null) {
return curatedObject; return curatedObject ?? [];
} else {
return [];
}
}); });

View File

@@ -176,9 +176,8 @@ class SearchPage extends HookConsumerWidget {
_buildThings() _buildThings()
], ],
), ),
isSearchEnabled if (isSearchEnabled)
? SearchSuggestionList(onSubmitted: _onSearchSubmitted) SearchSuggestionList(onSubmitted: _onSearchSubmitted),
: Container(),
], ],
), ),
), ),

View File

@@ -166,7 +166,7 @@ class SearchResultPage extends HookConsumerWidget {
} }
} }
return Container(); return const SizedBox();
} }
return Scaffold( return Scaffold(
@@ -198,9 +198,8 @@ class SearchResultPage extends HookConsumerWidget {
child: Stack( child: Stack(
children: [ children: [
_buildSearchResult(), _buildSearchResult(),
isNewSearch.value if (isNewSearch.value)
? SearchSuggestionList(onSubmitted: _onSearchSubmitted) SearchSuggestionList(onSubmitted: _onSearchSubmitted),
: Container(),
], ],
), ),
), ),

View File

@@ -72,10 +72,7 @@ class SharedAlbum {
albumThumbnailAssetId: map['albumThumbnailAssetId'], albumThumbnailAssetId: map['albumThumbnailAssetId'],
sharedUsers: sharedUsers:
List<User>.from(map['sharedUsers']?.map((x) => User.fromMap(x))), List<User>.from(map['sharedUsers']?.map((x) => User.fromMap(x))),
assets: map['assets'] != null assets: map['assets']?.map((x) => ImmichAsset.fromMap(x)).toList(),
? List<ImmichAsset>.from(
map['assets']?.map((x) => ImmichAsset.fromMap(x)))
: null,
); );
} }

View File

@@ -39,11 +39,7 @@ class SharedAlbumService {
"assetIds": assets.map((asset) => asset.id).toList(), "assetIds": assets.map((asset) => asset.id).toList(),
}); });
if (res == null) { return res != null;
return false;
}
return true;
} catch (e) { } catch (e) {
debugPrint("Error createSharedAlbum ${e.toString()}"); debugPrint("Error createSharedAlbum ${e.toString()}");
return false; return false;
@@ -71,11 +67,7 @@ class SharedAlbumService {
"assetIds": assets.map((asset) => asset.id).toList(), "assetIds": assets.map((asset) => asset.id).toList(),
}); });
if (res == null) { return res != null;
return false;
}
return true;
} catch (e) { } catch (e) {
debugPrint("Error addAdditionalAssetToAlbum ${e.toString()}"); debugPrint("Error addAdditionalAssetToAlbum ${e.toString()}");
return false; return false;
@@ -90,11 +82,7 @@ class SharedAlbumService {
"sharedUserIds": sharedUserIds, "sharedUserIds": sharedUserIds,
}); });
if (res == null) { return res != null;
return false;
}
return true;
} catch (e) { } catch (e) {
debugPrint("Error addAdditionalUserToAlbum ${e.toString()}"); debugPrint("Error addAdditionalUserToAlbum ${e.toString()}");
return false; return false;

View File

@@ -114,7 +114,7 @@ class AlbumViewerAppbar extends HookConsumerWidget with PreferredSizeWidget {
onTap: () => _onRemoveFromAlbumPressed(albumId), onTap: () => _onRemoveFromAlbumPressed(albumId),
); );
} else { } else {
return Container(); return const SizedBox();
} }
} else { } else {
if (_albumInfo.asData?.value.ownerId == userId) { if (_albumInfo.asData?.value.ownerId == userId) {
@@ -198,8 +198,8 @@ class AlbumViewerAppbar extends HookConsumerWidget with PreferredSizeWidget {
elevation: 0, elevation: 0,
leading: _buildLeadingButton(), leading: _buildLeadingButton(),
title: isMultiSelectionEnable title: isMultiSelectionEnable
? Text(selectedAssetsInAlbum.length.toString()) ? Text('${selectedAssetsInAlbum.length}')
: Container(), : null,
centerTitle: false, centerTitle: false,
actions: [ actions: [
IconButton( IconButton(

View File

@@ -71,29 +71,25 @@ class AlbumViewerThumbnail extends HookConsumerWidget {
} }
_buildVideoLabel() { _buildVideoLabel() {
if (asset.type == 'IMAGE') { return Positioned(
return Container(); top: 5,
} else { right: 5,
return Positioned( child: Row(
top: 5, children: [
right: 5, Text(
child: Row( asset.duration.toString().substring(0, 7),
children: [ style: const TextStyle(
Text(
asset.duration.toString().substring(0, 7),
style: const TextStyle(
color: Colors.white,
fontSize: 10,
),
),
const Icon(
Icons.play_circle_outline_rounded,
color: Colors.white, color: Colors.white,
fontSize: 10,
), ),
], ),
), const Icon(
); Icons.play_circle_outline_rounded,
} color: Colors.white,
),
],
),
);
} }
_buildAssetStoreLocationIcon() { _buildAssetStoreLocationIcon() {
@@ -112,23 +108,20 @@ class AlbumViewerThumbnail extends HookConsumerWidget {
_buildAssetSelectionIcon() { _buildAssetSelectionIcon() {
bool isSelected = selectedAssetsInAlbumViewer.contains(asset); bool isSelected = selectedAssetsInAlbumViewer.contains(asset);
if (isMultiSelectionEnable) {
return Positioned( return Positioned(
left: 10, left: 10,
top: 5, top: 5,
child: isSelected child: isSelected
? Icon( ? Icon(
Icons.check_circle_rounded, Icons.check_circle_rounded,
color: Theme.of(context).primaryColor, color: Theme.of(context).primaryColor,
) )
: const Icon( : const Icon(
Icons.check_circle_outline_rounded, Icons.check_circle_outline_rounded,
color: Colors.white, color: Colors.white,
), ),
); );
} else {
return Container();
}
} }
_buildThumbnailImage() { _buildThumbnailImage() {
@@ -183,8 +176,8 @@ class AlbumViewerThumbnail extends HookConsumerWidget {
children: [ children: [
_buildThumbnailImage(), _buildThumbnailImage(),
_buildAssetStoreLocationIcon(), _buildAssetStoreLocationIcon(),
_buildVideoLabel(), if (asset.type != 'IMAGE') _buildVideoLabel(),
_buildAssetSelectionIcon(), if (isMultiSelectionEnable) _buildAssetSelectionIcon(),
], ],
), ),
), ),

View File

@@ -131,27 +131,26 @@ class SelectionThumbnailImage extends HookConsumerWidget {
child: _buildSelectionIcon(asset), child: _buildSelectionIcon(asset),
), ),
), ),
asset.type == 'IMAGE' if (asset.type != 'IMAGE')
? Container() Positioned(
: Positioned( bottom: 5,
bottom: 5, right: 5,
right: 5, child: Row(
child: Row( children: [
children: [ Text(
Text( '${asset.duration?.substring(0, 7)}',
asset.duration.toString().substring(0, 7), style: const TextStyle(
style: const TextStyle( color: Colors.white,
color: Colors.white, fontSize: 10,
fontSize: 10, ),
),
),
const Icon(
Icons.play_circle_outline_rounded,
color: Colors.white,
),
],
), ),
) const Icon(
Icons.play_circle_outline_rounded,
color: Colors.white,
),
],
),
),
], ],
), ),
); );

View File

@@ -14,7 +14,8 @@ class SharingSliverAppBar extends StatelessWidget {
floating: false, floating: false,
pinned: true, pinned: true,
snap: false, snap: false,
leading: Container(), automaticallyImplyLeading: false,
// leading: Container(),
// elevation: 0, // elevation: 0,
title: Text( title: Text(
'IMMICH', 'IMMICH',

View File

@@ -37,7 +37,7 @@ class AlbumViewerPage extends HookConsumerWidget {
/// Find out if the assets in album exist on the device /// Find out if the assets in album exist on the device
/// If they exist, add to selected asset state to show they are already selected. /// If they exist, add to selected asset state to show they are already selected.
void _onAddPhotosPressed(SharedAlbum albumInfo) async { void _onAddPhotosPressed(SharedAlbum albumInfo) async {
if (albumInfo.assets != null && albumInfo.assets!.isNotEmpty) { if (albumInfo.assets?.isNotEmpty == true) {
ref ref
.watch(assetSelectionProvider.notifier) .watch(assetSelectionProvider.notifier)
.addNewAssets(albumInfo.assets!.toList()); .addNewAssets(albumInfo.assets!.toList());
@@ -109,32 +109,28 @@ class AlbumViewerPage extends HookConsumerWidget {
} }
Widget _buildAlbumDateRange(SharedAlbum albumInfo) { Widget _buildAlbumDateRange(SharedAlbum albumInfo) {
if (albumInfo.assets != null && albumInfo.assets!.isNotEmpty) { String startDate = "";
String startDate = ""; DateTime parsedStartDate =
DateTime parsedStartDate = DateTime.parse(albumInfo.assets!.first.createdAt);
DateTime.parse(albumInfo.assets!.first.createdAt); DateTime parsedEndDate = DateTime.parse(
DateTime parsedEndDate = albumInfo.assets?.last.createdAt ?? '11111111'); //Need default.
DateTime.parse(albumInfo.assets!.last.createdAt);
if (parsedStartDate.year == parsedEndDate.year) { if (parsedStartDate.year == parsedEndDate.year) {
startDate = DateFormat('LLL d').format(parsedStartDate); startDate = DateFormat('LLL d').format(parsedStartDate);
} else {
startDate = DateFormat('LLL d, y').format(parsedStartDate);
}
String endDate = DateFormat('LLL d, y').format(parsedEndDate);
return Padding(
padding: const EdgeInsets.only(left: 16.0, top: 8),
child: Text(
"$startDate-$endDate",
style: const TextStyle(
fontSize: 14, fontWeight: FontWeight.bold, color: Colors.grey),
),
);
} else { } else {
return Container(); startDate = DateFormat('LLL d, y').format(parsedStartDate);
} }
String endDate = DateFormat('LLL d, y').format(parsedEndDate);
return Padding(
padding: const EdgeInsets.only(left: 16.0, top: 8),
child: Text(
"$startDate-$endDate",
style: const TextStyle(
fontSize: 14, fontWeight: FontWeight.bold, color: Colors.grey),
),
);
} }
Widget _buildHeader(SharedAlbum albumInfo) { Widget _buildHeader(SharedAlbum albumInfo) {
@@ -143,7 +139,8 @@ class AlbumViewerPage extends HookConsumerWidget {
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
_buildTitle(albumInfo), _buildTitle(albumInfo),
_buildAlbumDateRange(albumInfo), if (albumInfo.assets?.isNotEmpty == true)
_buildAlbumDateRange(albumInfo),
SizedBox( SizedBox(
height: 60, height: 60,
child: ListView.builder( child: ListView.builder(
@@ -175,7 +172,7 @@ class AlbumViewerPage extends HookConsumerWidget {
} }
Widget _buildImageGrid(SharedAlbum albumInfo) { Widget _buildImageGrid(SharedAlbum albumInfo) {
if (albumInfo.assets != null && albumInfo.assets!.isNotEmpty) { if (albumInfo.assets?.isNotEmpty == true) {
return SliverPadding( return SliverPadding(
padding: const EdgeInsets.only(top: 10.0), padding: const EdgeInsets.only(top: 10.0),
sliver: SliverGrid( sliver: SliverGrid(
@@ -209,13 +206,12 @@ class AlbumViewerPage extends HookConsumerWidget {
onPressed: () => _onAddPhotosPressed(albumInfo), onPressed: () => _onAddPhotosPressed(albumInfo),
labelText: "Add photos", labelText: "Add photos",
), ),
userId == albumInfo.ownerId if (userId == albumInfo.ownerId)
? AlbumActionOutlinedButton( AlbumActionOutlinedButton(
iconData: Icons.person_add_alt_rounded, iconData: Icons.person_add_alt_rounded,
onPressed: () => _onAddUsersPressed(albumInfo), onPressed: () => _onAddUsersPressed(albumInfo),
labelText: "Add users", labelText: "Add users",
) ),
: Container(),
], ],
), ),
), ),

View File

@@ -74,23 +74,22 @@ class AssetSelectionPage extends HookConsumerWidget {
), ),
centerTitle: false, centerTitle: false,
actions: [ actions: [
(!isAlbumExist && selectedAssets.isNotEmpty) || if ((!isAlbumExist && selectedAssets.isNotEmpty) ||
(isAlbumExist && newAssetsForAlbum.isNotEmpty) (isAlbumExist && newAssetsForAlbum.isNotEmpty))
? TextButton( TextButton(
onPressed: () { onPressed: () {
var payload = AssetSelectionPageResult( var payload = AssetSelectionPageResult(
isAlbumExist: isAlbumExist, isAlbumExist: isAlbumExist,
selectedAdditionalAsset: newAssetsForAlbum, selectedAdditionalAsset: newAssetsForAlbum,
selectedNewAsset: selectedAssets, selectedNewAsset: selectedAssets,
); );
AutoRouter.of(context).pop(payload); AutoRouter.of(context).pop(payload);
}, },
child: const Text( child: const Text(
"Add", "Add",
style: TextStyle(fontWeight: FontWeight.bold), style: TextStyle(fontWeight: FontWeight.bold),
), ),
) ),
: Container()
], ],
), ),
body: _buildBody(), body: _buildBody(),

View File

@@ -113,26 +113,22 @@ class CreateSharedAlbumPage extends HookConsumerWidget {
} }
_buildControlButton() { _buildControlButton() {
if (selectedAssets.isNotEmpty) { return Padding(
return Padding( padding: const EdgeInsets.only(left: 12.0, top: 16, bottom: 16),
padding: const EdgeInsets.only(left: 12.0, top: 16, bottom: 16), child: SizedBox(
child: SizedBox( height: 30,
height: 30, child: ListView(
child: ListView( scrollDirection: Axis.horizontal,
scrollDirection: Axis.horizontal, children: [
children: [ AlbumActionOutlinedButton(
AlbumActionOutlinedButton( iconData: Icons.add_photo_alternate_outlined,
iconData: Icons.add_photo_alternate_outlined, onPressed: _onSelectPhotosButtonPressed,
onPressed: _onSelectPhotosButtonPressed, labelText: "Add photos",
labelText: "Add photos", ),
), ],
],
),
), ),
); ),
} );
return Container();
} }
_buildSelectedImageGrid() { _buildSelectedImageGrid() {
@@ -196,7 +192,8 @@ class CreateSharedAlbumPage extends HookConsumerWidget {
slivers: [ slivers: [
SliverAppBar( SliverAppBar(
elevation: 5, elevation: 5,
leading: Container(), automaticallyImplyLeading: false,
// leading: Container(),
pinned: true, pinned: true,
floating: false, floating: false,
bottom: PreferredSize( bottom: PreferredSize(
@@ -204,7 +201,7 @@ class CreateSharedAlbumPage extends HookConsumerWidget {
child: Column( child: Column(
children: [ children: [
_buildTitleInputField(), _buildTitleInputField(),
_buildControlButton(), if (selectedAssets.isNotEmpty) _buildControlButton(),
], ],
), ),
), ),

View File

@@ -104,10 +104,9 @@ class WebsocketNotifier extends StateNotifier<WebscoketState> {
disconnect() { disconnect() {
debugPrint("[WEBSOCKET] Attempting to disconnect"); debugPrint("[WEBSOCKET] Attempting to disconnect");
var socket = state.socket?.disconnect(); var socket = state.socket?.disconnect();
if (socket != null) {
if (socket.disconnected) { if (socket?.disconnected == true) {
state = WebscoketState(isConnected: false, socket: null); state = WebscoketState(isConnected: false, socket: null);
}
} }
} }

View File

@@ -34,7 +34,7 @@ class SplashScreenPage extends HookConsumerWidget {
} }
useEffect(() { useEffect(() {
if (loginInfo != null && loginInfo.isSaveLogin) { if (loginInfo?.isSaveLogin == true) {
performLoggingIn(); performLoggingIn();
} else { } else {
AutoRouter.of(context).push(const LoginRoute()); AutoRouter.of(context).push(const LoginRoute());

View File

@@ -121,7 +121,7 @@ class VersionAnnouncementOverlay extends HookConsumerWidget {
), ),
); );
} else { } else {
return Container(); return const SizedBox();
} }
}, },
); );

View File

@@ -2,7 +2,7 @@ name: immich_mobile
description: Immich - selfhosted backup media file on mobile phone description: Immich - selfhosted backup media file on mobile phone
publish_to: "none" publish_to: "none"
version: 1.14.0+21 version: 1.16.0+23
environment: environment:
sdk: ">=2.17.0 <3.0.0" sdk: ">=2.17.0 <3.0.0"

6
nginx/Dockerfile Normal file
View File

@@ -0,0 +1,6 @@
FROM nginx:latest
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
EXPOSE 443

View File

@@ -22,9 +22,9 @@ server {
location /api { location /api {
# Compression # Compression
gzip_static on; gzip_static on;
gzip_min_length 1000; gzip_min_length 1000;
gzip_comp_level 2; gzip_comp_level 2;
proxy_buffering off; proxy_buffering off;
proxy_buffer_size 16k; proxy_buffer_size 16k;
@@ -41,17 +41,17 @@ server {
proxy_set_header Connection "upgrade"; proxy_set_header Connection "upgrade";
proxy_set_header Host $host; proxy_set_header Host $host;
rewrite /api/(.*) /$1 break; rewrite /api/(.*) /$1 break;
proxy_pass http://immich-server:3000; proxy_pass http://immich-server:3001;
} }
location / { location / {
# Compression # Compression
gzip_static on; gzip_static on;
gzip_min_length 1000; gzip_min_length 1000;
gzip_comp_level 2; gzip_comp_level 2;
proxy_buffering off; proxy_buffering off;
proxy_buffer_size 16k; proxy_buffer_size 16k;

View File

@@ -3,7 +3,7 @@ import { AssetAlbumEntity } from '@app/database/entities/asset-album.entity';
import { UserAlbumEntity } from '@app/database/entities/user-album.entity'; import { UserAlbumEntity } from '@app/database/entities/user-album.entity';
import { Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm'; import { InjectRepository } from '@nestjs/typeorm';
import { getConnection, Repository, SelectQueryBuilder } from 'typeorm'; import { Repository, SelectQueryBuilder, DataSource } from 'typeorm';
import { AddAssetsDto } from './dto/add-assets.dto'; import { AddAssetsDto } from './dto/add-assets.dto';
import { AddUsersDto } from './dto/add-users.dto'; import { AddUsersDto } from './dto/add-users.dto';
import { CreateAlbumDto } from './dto/create-album.dto'; import { CreateAlbumDto } from './dto/create-album.dto';
@@ -36,10 +36,12 @@ export class AlbumRepository implements IAlbumRepository {
@InjectRepository(UserAlbumEntity) @InjectRepository(UserAlbumEntity)
private userAlbumRepository: Repository<UserAlbumEntity>, private userAlbumRepository: Repository<UserAlbumEntity>,
private dataSource: DataSource,
) {} ) {}
async create(ownerId: string, createAlbumDto: CreateAlbumDto): Promise<AlbumEntity> { async create(ownerId: string, createAlbumDto: CreateAlbumDto): Promise<AlbumEntity> {
return getConnection().transaction(async (transactionalEntityManager) => { return this.dataSource.transaction(async (transactionalEntityManager) => {
// Create album entity // Create album entity
const newAlbum = new AlbumEntity(); const newAlbum = new AlbumEntity();
newAlbum.ownerId = ownerId; newAlbum.ownerId = ownerId;

View File

@@ -31,6 +31,9 @@ import { SearchAssetDto } from './dto/search-asset.dto';
import { CommunicationGateway } from '../communication/communication.gateway'; import { CommunicationGateway } from '../communication/communication.gateway';
import { InjectQueue } from '@nestjs/bull'; import { InjectQueue } from '@nestjs/bull';
import { Queue } from 'bull'; import { Queue } from 'bull';
import { IAssetUploadedJob } from '@app/job/index';
import { assetUploadedQueueName } from '@app/job/constants/queue-name.constant';
import { assetUploadedProcessorName } from '@app/job/constants/job-name.constant';
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
@Controller('asset') @Controller('asset')
@@ -40,8 +43,8 @@ export class AssetController {
private assetService: AssetService, private assetService: AssetService,
private backgroundTaskService: BackgroundTaskService, private backgroundTaskService: BackgroundTaskService,
@InjectQueue('asset-uploaded-queue') @InjectQueue(assetUploadedQueueName)
private assetUploadedQueue: Queue, private assetUploadedQueue: Queue<IAssetUploadedJob>,
) {} ) {}
@Post('upload') @Post('upload')
@@ -56,7 +59,7 @@ export class AssetController {
) )
async uploadFile( async uploadFile(
@GetAuthUser() authUser: AuthUserDto, @GetAuthUser() authUser: AuthUserDto,
@UploadedFiles() uploadFiles: { assetData: Express.Multer.File[]; thumbnailData?: Express.Multer.File[] }, @UploadedFiles() uploadFiles: { assetData: Express.Multer.File[] },
@Body(ValidationPipe) assetInfo: CreateAssetDto, @Body(ValidationPipe) assetInfo: CreateAssetDto,
): Promise<'ok' | undefined> { ): Promise<'ok' | undefined> {
for (const file of uploadFiles.assetData) { for (const file of uploadFiles.assetData) {
@@ -66,28 +69,12 @@ export class AssetController {
if (!savedAsset) { if (!savedAsset) {
return; return;
} }
if (uploadFiles.thumbnailData != null) {
const assetWithThumbnail = await this.assetService.updateThumbnailInfo(
savedAsset,
uploadFiles.thumbnailData[0].path,
);
await this.assetUploadedQueue.add( await this.assetUploadedQueue.add(
'asset-uploaded', assetUploadedProcessorName,
{ asset: assetWithThumbnail, fileName: file.originalname, fileSize: file.size, hasThumbnail: true }, { asset: savedAsset, fileName: file.originalname, fileSize: file.size },
{ jobId: savedAsset.id }, { jobId: savedAsset.id },
); );
this.wsCommunicateionGateway.server
.to(savedAsset.userId)
.emit('on_upload_success', JSON.stringify(assetWithThumbnail));
} else {
await this.assetUploadedQueue.add(
'asset-uploaded',
{ asset: savedAsset, fileName: file.originalname, fileSize: file.size, hasThumbnail: false },
{ jobId: savedAsset.id },
);
}
} catch (e) { } catch (e) {
Logger.error(`Error receiving upload file ${e}`); Logger.error(`Error receiving upload file ${e}`);
} }
@@ -116,7 +103,7 @@ export class AssetController {
} }
@Get('/thumbnail/:assetId') @Get('/thumbnail/:assetId')
async getAssetThumbnail(@Param('assetId') assetId: string): Promise<StreamableFile> { async getAssetThumbnail(@Param('assetId') assetId: string) {
return await this.assetService.getAssetThumbnail(assetId); return await this.assetService.getAssetThumbnail(assetId);
} }

View File

@@ -7,6 +7,7 @@ import { BullModule } from '@nestjs/bull';
import { BackgroundTaskModule } from '../../modules/background-task/background-task.module'; import { BackgroundTaskModule } from '../../modules/background-task/background-task.module';
import { BackgroundTaskService } from '../../modules/background-task/background-task.service'; import { BackgroundTaskService } from '../../modules/background-task/background-task.service';
import { CommunicationModule } from '../communication/communication.module'; import { CommunicationModule } from '../communication/communication.module';
import { assetUploadedQueueName } from '@app/job/constants/queue-name.constant';
@Module({ @Module({
imports: [ imports: [
@@ -14,7 +15,7 @@ import { CommunicationModule } from '../communication/communication.module';
BackgroundTaskModule, BackgroundTaskModule,
TypeOrmModule.forFeature([AssetEntity]), TypeOrmModule.forFeature([AssetEntity]),
BullModule.registerQueue({ BullModule.registerQueue({
name: 'asset-uploaded-queue', name: assetUploadedQueueName,
defaultJobOptions: { defaultJobOptions: {
attempts: 3, attempts: 3,
removeOnComplete: true, removeOnComplete: true,

View File

@@ -11,12 +11,13 @@ import { IsNull, Not, Repository } from 'typeorm';
import { AuthUserDto } from '../../decorators/auth-user.decorator'; import { AuthUserDto } from '../../decorators/auth-user.decorator';
import { CreateAssetDto } from './dto/create-asset.dto'; import { CreateAssetDto } from './dto/create-asset.dto';
import { AssetEntity, AssetType } from '@app/database/entities/asset.entity'; import { AssetEntity, AssetType } from '@app/database/entities/asset.entity';
import { createReadStream, stat } from 'fs'; import { constants, createReadStream, ReadStream, stat } from 'fs';
import { ServeFileDto } from './dto/serve-file.dto'; import { ServeFileDto } from './dto/serve-file.dto';
import { Response as Res } from 'express'; import { Response as Res } from 'express';
import { promisify } from 'util'; import { promisify } from 'util';
import { DeleteAssetDto } from './dto/delete-asset.dto'; import { DeleteAssetDto } from './dto/delete-asset.dto';
import { SearchAssetDto } from './dto/search-asset.dto'; import { SearchAssetDto } from './dto/search-asset.dto';
import fs from 'fs/promises';
const fileInfo = promisify(stat); const fileInfo = promisify(stat);
@@ -123,7 +124,7 @@ export class AssetService {
public async downloadFile(query: ServeFileDto, res: Res) { public async downloadFile(query: ServeFileDto, res: Res) {
try { try {
let file = null; let fileReadStream = null;
const asset = await this.findOne(query.did, query.aid); const asset = await this.findOne(query.did, query.aid);
if (query.isThumb === 'false' || !query.isThumb) { if (query.isThumb === 'false' || !query.isThumb) {
@@ -132,76 +133,90 @@ export class AssetService {
'Content-Type': asset.mimeType, 'Content-Type': asset.mimeType,
'Content-Length': size, 'Content-Length': size,
}); });
file = createReadStream(asset.originalPath);
await fs.access(asset.originalPath, constants.R_OK | constants.W_OK);
fileReadStream = createReadStream(asset.originalPath);
} else { } else {
if (!asset.resizePath) { if (!asset.resizePath) {
throw new Error('resizePath not set'); throw new NotFoundException('resizePath not set');
} }
const { size } = await fileInfo(asset.resizePath); const { size } = await fileInfo(asset.resizePath);
res.set({ res.set({
'Content-Type': 'image/jpeg', 'Content-Type': 'image/jpeg',
'Content-Length': size, 'Content-Length': size,
}); });
file = createReadStream(asset.resizePath);
await fs.access(asset.resizePath, constants.R_OK | constants.W_OK);
fileReadStream = createReadStream(asset.resizePath);
} }
return new StreamableFile(file); return new StreamableFile(fileReadStream);
} catch (e) { } catch (e) {
Logger.error('Error download asset ', e); Logger.error(`Error download asset`, 'downloadFile');
throw new InternalServerErrorException(`Failed to download asset ${e}`, 'DownloadFile'); throw new InternalServerErrorException(`Failed to download asset ${e}`, 'DownloadFile');
} }
} }
public async getAssetThumbnail(assetId: string): Promise<StreamableFile> { public async getAssetThumbnail(assetId: string) {
try { let fileReadStream: ReadStream;
const asset = await this.assetRepository.findOne({ id: assetId });
if (!asset) {
throw new NotFoundException('Asset not found');
}
const asset = await this.assetRepository.findOne({ where: { id: assetId } });
if (!asset) {
throw new NotFoundException('Asset not found');
}
try {
if (asset.webpPath && asset.webpPath.length > 0) { if (asset.webpPath && asset.webpPath.length > 0) {
return new StreamableFile(createReadStream(asset.webpPath)); await fs.access(asset.webpPath, constants.R_OK | constants.W_OK);
fileReadStream = createReadStream(asset.webpPath);
} else { } else {
if (!asset.resizePath) { if (!asset.resizePath) {
throw new Error('resizePath not set'); return new NotFoundException('resizePath not set');
} }
return new StreamableFile(createReadStream(asset.resizePath));
await fs.access(asset.resizePath, constants.R_OK | constants.W_OK);
fileReadStream = createReadStream(asset.resizePath);
} }
return new StreamableFile(fileReadStream);
} catch (e) { } catch (e) {
if (e instanceof NotFoundException) { Logger.error(`Cannot create read stream for asset ${asset.id}`, 'getAssetThumbnail');
throw e; throw new InternalServerErrorException(
} e,
Logger.error('Error serving asset thumbnail ', e); `Cannot read thumbnail file for asset ${asset.id} - contact your administrator`,
throw new InternalServerErrorException('Failed to serve asset thumbnail', 'GetAssetThumbnail'); );
} }
} }
public async serveFile(authUser: AuthUserDto, query: ServeFileDto, res: Res, headers: any) { public async serveFile(authUser: AuthUserDto, query: ServeFileDto, res: Res, headers: any) {
let file = null; let fileReadStream: ReadStream;
const asset = await this.findOne(query.did, query.aid); const asset = await this.findOne(query.did, query.aid);
if (!asset) { if (!asset) {
// TODO: maybe this should be a NotFoundException? throw new NotFoundException('Asset does not exist');
throw new BadRequestException('Asset does not exist');
} }
// Handle Sending Images // Handle Sending Images
if (asset.type == AssetType.IMAGE || query.isThumb == 'true') { if (asset.type == AssetType.IMAGE || query.isThumb == 'true') {
/**
* Serve file viewer on the web
*/
if (query.isWeb) {
res.set({
'Content-Type': 'image/jpeg',
});
if (!asset.resizePath) {
Logger.error('Error serving IMAGE asset for web', 'ServeFile');
throw new InternalServerErrorException(`Failed to serve image asset for web`, 'ServeFile');
}
return new StreamableFile(createReadStream(asset.resizePath));
}
try { try {
/**
* Serve file viewer on the web
*/
if (query.isWeb) {
res.set({
'Content-Type': 'image/jpeg',
});
if (!asset.resizePath) {
Logger.error('Error serving IMAGE asset for web', 'ServeFile');
throw new InternalServerErrorException(`Failed to serve image asset for web`, 'ServeFile');
}
await fs.access(asset.resizePath, constants.R_OK | constants.W_OK);
fileReadStream = createReadStream(asset.resizePath);
return new StreamableFile(fileReadStream);
}
/** /**
* Serve thumbnail image for both web and mobile app * Serve thumbnail image for both web and mobile app
*/ */
@@ -209,34 +224,38 @@ export class AssetService {
res.set({ res.set({
'Content-Type': asset.mimeType, 'Content-Type': asset.mimeType,
}); });
file = createReadStream(asset.originalPath);
await fs.access(asset.originalPath, constants.R_OK | constants.W_OK);
fileReadStream = createReadStream(asset.originalPath);
} else { } else {
if (asset.webpPath && asset.webpPath.length > 0) { if (asset.webpPath && asset.webpPath.length > 0) {
res.set({ res.set({
'Content-Type': 'image/webp', 'Content-Type': 'image/webp',
}); });
file = createReadStream(asset.webpPath); await fs.access(asset.webpPath, constants.R_OK | constants.W_OK);
fileReadStream = createReadStream(asset.webpPath);
} else { } else {
res.set({ res.set({
'Content-Type': 'image/jpeg', 'Content-Type': 'image/jpeg',
}); });
if (!asset.resizePath) { if (!asset.resizePath) {
throw new Error('resizePath not set'); throw new Error('resizePath not set');
} }
file = createReadStream(asset.resizePath);
await fs.access(asset.resizePath, constants.R_OK | constants.W_OK);
fileReadStream = createReadStream(asset.resizePath);
} }
} }
file.on('error', (error) => { return new StreamableFile(fileReadStream);
Logger.log(`Cannot create read stream ${error}`);
return new BadRequestException('Cannot Create Read Stream');
});
return new StreamableFile(file);
} catch (e) { } catch (e) {
Logger.error('Error serving IMAGE asset ', e); Logger.error(`Cannot create read stream for asset ${asset.id}`, 'serveFile[IMAGE]');
throw new InternalServerErrorException(`Failed to serve image asset ${e}`, 'ServeFile'); throw new InternalServerErrorException(
e,
`Cannot read thumbnail file for asset ${asset.id} - contact your administrator`,
);
} }
} else if (asset.type == AssetType.VIDEO) { } else if (asset.type == AssetType.VIDEO) {
try { try {
@@ -244,6 +263,8 @@ export class AssetService {
let videoPath = asset.originalPath; let videoPath = asset.originalPath;
let mimeType = asset.mimeType; let mimeType = asset.mimeType;
await fs.access(videoPath, constants.R_OK | constants.W_OK);
if (query.isWeb && asset.mimeType == 'video/quicktime') { if (query.isWeb && asset.mimeType == 'video/quicktime') {
videoPath = asset.encodedVideoPath == '' ? asset.originalPath : asset.encodedVideoPath; videoPath = asset.encodedVideoPath == '' ? asset.originalPath : asset.encodedVideoPath;
mimeType = asset.encodedVideoPath == '' ? asset.mimeType : 'video/mp4'; mimeType = asset.encodedVideoPath == '' ? asset.mimeType : 'video/mp4';
@@ -279,7 +300,6 @@ export class AssetService {
} }
/** Sending Partial Content With HTTP Code 206 */ /** Sending Partial Content With HTTP Code 206 */
console.log('Send Range', range);
res.status(206).set({ res.status(206).set({
'Content-Range': `bytes ${start}-${end}/${size}`, 'Content-Range': `bytes ${start}-${end}/${size}`,
'Accept-Ranges': 'bytes', 'Accept-Ranges': 'bytes',
@@ -298,7 +318,7 @@ export class AssetService {
return new StreamableFile(createReadStream(videoPath)); return new StreamableFile(createReadStream(videoPath));
} }
} catch (e) { } catch (e) {
Logger.error('Error serving VIDEO asset ', e); Logger.error(`Error serving VIDEO asset id ${asset.id}`, 'serveFile[VIDEO]');
throw new InternalServerErrorException(`Failed to serve video asset ${e}`, 'ServeFile'); throw new InternalServerErrorException(`Failed to serve video asset ${e}`, 'ServeFile');
} }
} }
@@ -335,11 +355,11 @@ export class AssetService {
// TODO: should use query builder // TODO: should use query builder
const rows = await this.assetRepository.query( const rows = await this.assetRepository.query(
` `
select distinct si.tags, si.objects, e.orientation, e."lensModel", e.make, e.model , a.type, e.city, e.state, e.country SELECT DISTINCT si.tags, si.objects, e.orientation, e."lensModel", e.make, e.model , a.type, e.city, e.state, e.country
from assets a FROM assets a
left join exif e on a.id = e."assetId" LEFT JOIN exif e ON a.id = e."assetId"
left join smart_info si on a.id = si."assetId" LEFT JOIN smart_info si ON a.id = si."assetId"
where a."userId" = $1; WHERE a."userId" = $1;
`, `,
[authUser.id], [authUser.id],
); );
@@ -395,12 +415,12 @@ export class AssetService {
async getCuratedLocation(authUser: AuthUserDto) { async getCuratedLocation(authUser: AuthUserDto) {
return await this.assetRepository.query( return await this.assetRepository.query(
` `
select distinct on (e.city) a.id, e.city, a."resizePath", a."deviceAssetId", a."deviceId" SELECT DISTINCT ON (e.city) a.id, e.city, a."resizePath", a."deviceAssetId", a."deviceId"
from assets a FROM assets a
left join exif e on a.id = e."assetId" LEFT JOIN exif e ON a.id = e."assetId"
where a."userId" = $1 WHERE a."userId" = $1
and e.city is not null AND e.city IS NOT NULL
and a.type = 'IMAGE'; AND a.type = 'IMAGE';
`, `,
[authUser.id], [authUser.id],
); );
@@ -409,11 +429,11 @@ export class AssetService {
async getCuratedObject(authUser: AuthUserDto) { async getCuratedObject(authUser: AuthUserDto) {
return await this.assetRepository.query( return await this.assetRepository.query(
` `
select distinct on (unnest(si.objects)) a.id, unnest(si.objects) as "object", a."resizePath", a."deviceAssetId", a."deviceId" SELECT DISTINCT ON (unnest(si.objects)) a.id, unnest(si.objects) as "object", a."resizePath", a."deviceAssetId", a."deviceId"
from assets a FROM assets a
left join smart_info si on a.id = si."assetId" LEFT JOIN smart_info si ON a.id = si."assetId"
where a."userId" = $1 WHERE a."userId" = $1
and si.objects is not null AND si.objects IS NOT NULL
`, `,
[authUser.id], [authUser.id],
); );

View File

@@ -18,22 +18,22 @@ export class AuthService {
) {} ) {}
private async validateUser(loginCredential: LoginCredentialDto): Promise<UserEntity | null> { private async validateUser(loginCredential: LoginCredentialDto): Promise<UserEntity | null> {
const user = await this.userRepository.findOne( const user = await this.userRepository.findOne({
{ email: loginCredential.email }, where: {
{ email: loginCredential.email,
select: [
'id',
'email',
'password',
'salt',
'firstName',
'lastName',
'isAdmin',
'profileImagePath',
'shouldChangePassword',
],
}, },
); select: [
'id',
'email',
'password',
'salt',
'firstName',
'lastName',
'isAdmin',
'profileImagePath',
'shouldChangePassword',
],
});
if (!user) { if (!user) {
return null; return null;

View File

@@ -33,7 +33,7 @@ export class CommunicationGateway implements OnGatewayConnection, OnGatewayDisco
? await this.immichJwtService.validateToken(accessToken) ? await this.immichJwtService.validateToken(accessToken)
: { status: false, userId: null }; : { status: false, userId: null };
if (!res.status) { if (!res.status || res.userId == null) {
client.emit('error', 'unauthorized'); client.emit('error', 'unauthorized');
client.disconnect(); client.disconnect();
return; return;

View File

@@ -15,8 +15,10 @@ export class DeviceInfoService {
async create(createDeviceInfoDto: CreateDeviceInfoDto, authUser: AuthUserDto) { async create(createDeviceInfoDto: CreateDeviceInfoDto, authUser: AuthUserDto) {
const res = await this.deviceRepository.findOne({ const res = await this.deviceRepository.findOne({
deviceId: createDeviceInfoDto.deviceId, where: {
userId: authUser.id, deviceId: createDeviceInfoDto.deviceId,
userId: authUser.id,
},
}); });
if (res) { if (res) {

View File

@@ -38,7 +38,7 @@ export class UserService {
} }
async getUserInfo(authUser: AuthUserDto) { async getUserInfo(authUser: AuthUserDto) {
return this.userRepository.findOne({ id: authUser.id }); return this.userRepository.findOne({ where: { id: authUser.id } });
} }
async getUserCount(isAdmin: boolean) { async getUserCount(isAdmin: boolean) {
@@ -85,7 +85,7 @@ export class UserService {
} }
async updateUser(updateUserDto: UpdateUserDto) { async updateUser(updateUserDto: UpdateUserDto) {
const user = await this.userRepository.findOne(updateUserDto.id); const user = await this.userRepository.findOne({ where: { id: updateUserDto.id } });
if (!user) { if (!user) {
throw new NotFoundException('User not found'); throw new NotFoundException('User not found');
} }
@@ -148,13 +148,12 @@ export class UserService {
async getUserProfileImage(userId: string, res: Res) { async getUserProfileImage(userId: string, res: Res) {
try { try {
const user = await this.userRepository.findOne({ id: userId }); const user = await this.userRepository.findOne({ where: { id: userId } });
if (!user) { if (!user) {
throw new NotFoundException('User not found'); throw new NotFoundException('User not found');
} }
if (!user.profileImagePath) { if (!user.profileImagePath) {
// throw new BadRequestException('User does not have a profile image');
res.status(404).send('User does not have a profile image'); res.status(404).send('User does not have a profile image');
return; return;
} }
@@ -165,7 +164,7 @@ export class UserService {
const fileStream = createReadStream(user.profileImagePath); const fileStream = createReadStream(user.profileImagePath);
return new StreamableFile(fileStream); return new StreamableFile(fileStream);
} catch (e) { } catch (e) {
console.log('error getting user profile'); res.status(404).send('User does not have a profile image');
} }
} }
} }

View File

@@ -6,7 +6,6 @@ import { extname } from 'path';
import { Request } from 'express'; import { Request } from 'express';
import { APP_UPLOAD_LOCATION } from '../constants/upload_location.constant'; import { APP_UPLOAD_LOCATION } from '../constants/upload_location.constant';
import { randomUUID } from 'crypto'; import { randomUUID } from 'crypto';
// import { CreateAssetDto } from '../api-v1/asset/dto/create-asset.dto';
export const assetUploadOption: MulterOptions = { export const assetUploadOption: MulterOptions = {
fileFilter: (req: Request, file: any, cb: any) => { fileFilter: (req: Request, file: any, cb: any) => {
@@ -30,34 +29,20 @@ export const assetUploadOption: MulterOptions = {
return; return;
} }
if (file.fieldname == 'assetData') { const originalUploadFolder = `${basePath}/${req.user.id}/original/${req.body['deviceId']}`;
const originalUploadFolder = `${basePath}/${req.user.id}/original/${req.body['deviceId']}`;
if (!existsSync(originalUploadFolder)) { if (!existsSync(originalUploadFolder)) {
mkdirSync(originalUploadFolder, { recursive: true }); mkdirSync(originalUploadFolder, { recursive: true });
}
// Save original to disk
cb(null, originalUploadFolder);
} else if (file.fieldname == 'thumbnailData') {
const thumbnailUploadFolder = `${basePath}/${req.user.id}/thumb/${req.body['deviceId']}`;
if (!existsSync(thumbnailUploadFolder)) {
mkdirSync(thumbnailUploadFolder, { recursive: true });
}
// Save thumbnail to disk
cb(null, thumbnailUploadFolder);
} }
// Save original to disk
cb(null, originalUploadFolder);
}, },
filename: (req: Request, file: Express.Multer.File, cb: any) => { filename: (req: Request, file: Express.Multer.File, cb: any) => {
const fileNameUUID = randomUUID(); const fileNameUUID = randomUUID();
if (file.fieldname == 'assetData') {
cb(null, `${fileNameUUID}${req.body['fileExtension'].toLowerCase()}`); cb(null, `${fileNameUUID}${req.body['fileExtension'].toLowerCase()}`);
} else if (file.fieldname == 'thumbnailData') {
cb(null, `${fileNameUUID}.jpeg`);
}
}, },
}), }),
}; };

View File

@@ -3,7 +3,7 @@
export const serverVersion = { export const serverVersion = {
major: 1, major: 1,
minor: 14, minor: 16,
patch: 0, patch: 0,
build: 21, build: 23,
}; };

View File

@@ -15,7 +15,7 @@ async function bootstrap() {
app.useWebSocketAdapter(new RedisIoAdapter(app)); app.useWebSocketAdapter(new RedisIoAdapter(app));
await app.listen(3000, () => { await app.listen(3001, () => {
if (process.env.NODE_ENV == 'development') { if (process.env.NODE_ENV == 'development') {
Logger.log('Running Immich Server in DEVELOPMENT environment', 'ImmichServer'); Logger.log('Running Immich Server in DEVELOPMENT environment', 'ImmichServer');
} }

View File

@@ -25,7 +25,7 @@ export class AdminRolesGuard implements CanActivate {
return false; return false;
} }
const user = await this.userRepository.findOne(userId); const user = await this.userRepository.findOne({ where: { id: userId } });
if (!user) { if (!user) {
return false; return false;
} }

View File

@@ -22,7 +22,7 @@ export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
async validate(payload: JwtPayloadDto) { async validate(payload: JwtPayloadDto) {
const { userId } = payload; const { userId } = payload;
const user = await this.usersRepository.findOne({ id: userId }); const user = await this.usersRepository.findOne({ where: { id: userId } });
if (!user) { if (!user) {
throw new UnauthorizedException('Failure to validate JWT payload'); throw new UnauthorizedException('Failure to validate JWT payload');

View File

@@ -3,12 +3,13 @@ import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm'; import { TypeOrmModule } from '@nestjs/typeorm';
import { AssetEntity } from '@app/database/entities/asset.entity'; import { AssetEntity } from '@app/database/entities/asset.entity';
import { ScheduleTasksService } from './schedule-tasks.service'; import { ScheduleTasksService } from './schedule-tasks.service';
import { thumbnailGeneratorQueueName, videoConversionQueueName } from '@app/job/constants/queue-name.constant';
@Module({ @Module({
imports: [ imports: [
TypeOrmModule.forFeature([AssetEntity]), TypeOrmModule.forFeature([AssetEntity]),
BullModule.registerQueue({ BullModule.registerQueue({
name: 'video-conversion-queue', name: videoConversionQueueName,
defaultJobOptions: { defaultJobOptions: {
attempts: 3, attempts: 3,
removeOnComplete: true, removeOnComplete: true,
@@ -16,7 +17,7 @@ import { ScheduleTasksService } from './schedule-tasks.service';
}, },
}), }),
BullModule.registerQueue({ BullModule.registerQueue({
name: 'thumbnail-generator-queue', name: thumbnailGeneratorQueueName,
defaultJobOptions: { defaultJobOptions: {
attempts: 3, attempts: 3,
removeOnComplete: true, removeOnComplete: true,

View File

@@ -2,10 +2,13 @@ import { Injectable, Logger } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule'; import { Cron, CronExpression } from '@nestjs/schedule';
import { InjectRepository } from '@nestjs/typeorm'; import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm'; import { Repository } from 'typeorm';
import { AssetEntity } from '@app/database/entities/asset.entity'; import { AssetEntity, AssetType } from '@app/database/entities/asset.entity';
import { InjectQueue } from '@nestjs/bull'; import { InjectQueue } from '@nestjs/bull';
import { Queue } from 'bull'; import { Queue } from 'bull';
import { randomUUID } from 'crypto'; import { randomUUID } from 'crypto';
import { generateWEBPThumbnailProcessorName, mp4ConversionProcessorName } from '@app/job/constants/job-name.constant';
import { thumbnailGeneratorQueueName, videoConversionQueueName } from '@app/job/constants/queue-name.constant';
import { IVideoTranscodeJob } from '@app/job/interfaces/video-transcode.interface';
@Injectable() @Injectable()
export class ScheduleTasksService { export class ScheduleTasksService {
@@ -13,11 +16,11 @@ export class ScheduleTasksService {
@InjectRepository(AssetEntity) @InjectRepository(AssetEntity)
private assetRepository: Repository<AssetEntity>, private assetRepository: Repository<AssetEntity>,
@InjectQueue('thumbnail-generator-queue') @InjectQueue(thumbnailGeneratorQueueName)
private thumbnailGeneratorQueue: Queue, private thumbnailGeneratorQueue: Queue,
@InjectQueue('video-conversion-queue') @InjectQueue(videoConversionQueueName)
private videoConversionQueue: Queue, private videoConversionQueue: Queue<IVideoTranscodeJob>,
) {} ) {}
@Cron(CronExpression.EVERY_DAY_AT_MIDNIGHT) @Cron(CronExpression.EVERY_DAY_AT_MIDNIGHT)
@@ -36,7 +39,11 @@ export class ScheduleTasksService {
} }
for (const asset of assets) { for (const asset of assets) {
await this.thumbnailGeneratorQueue.add('generate-webp-thumbnail', { asset: asset }, { jobId: randomUUID() }); await this.thumbnailGeneratorQueue.add(
generateWEBPThumbnailProcessorName,
{ asset: asset },
{ jobId: randomUUID() },
);
} }
} }
@@ -44,7 +51,7 @@ export class ScheduleTasksService {
async videoConversion() { async videoConversion() {
const assets = await this.assetRepository.find({ const assets = await this.assetRepository.find({
where: { where: {
type: 'VIDEO', type: AssetType.VIDEO,
mimeType: 'video/quicktime', mimeType: 'video/quicktime',
encodedVideoPath: '', encodedVideoPath: '',
}, },
@@ -54,7 +61,7 @@ export class ScheduleTasksService {
}); });
for (const asset of assets) { for (const asset of assets) {
await this.videoConversionQueue.add('mp4-conversion', { asset }, { jobId: randomUUID() }); await this.videoConversionQueue.add(mp4ConversionProcessorName, { asset }, { jobId: randomUUID() });
} }
} }
} }

View File

@@ -1,15 +1,18 @@
import { getConnection } from 'typeorm'; import { DataSource } from 'typeorm';
import { CanActivate, ExecutionContext } from '@nestjs/common'; import { CanActivate, ExecutionContext } from '@nestjs/common';
import { TestingModuleBuilder } from '@nestjs/testing'; import { TestingModuleBuilder } from '@nestjs/testing';
import { AuthUserDto } from '../src/decorators/auth-user.decorator'; import { AuthUserDto } from '../src/decorators/auth-user.decorator';
import { JwtAuthGuard } from '../src/modules/immich-jwt/guards/jwt-auth.guard'; import { JwtAuthGuard } from '../src/modules/immich-jwt/guards/jwt-auth.guard';
import databaseConfig from '@app/database/config/database.config';
type CustomAuthCallback = () => AuthUserDto; type CustomAuthCallback = () => AuthUserDto;
export async function clearDb() { export async function clearDb() {
const entities = getConnection().entityMetadatas; const db = new DataSource(databaseConfig);
const entities = db.entityMetadatas;
for (const entity of entities) { for (const entity of entities) {
const repository = getConnection().getRepository(entity.name); const repository = db.getRepository(entity.name);
await repository.query(`TRUNCATE ${entity.tableName} RESTART IDENTITY CASCADE;`); await repository.query(`TRUNCATE ${entity.tableName} RESTART IDENTITY CASCADE;`);
} }
} }

View File

@@ -8,7 +8,7 @@ async function bootstrap() {
app.useWebSocketAdapter(new RedisIoAdapter(app)); app.useWebSocketAdapter(new RedisIoAdapter(app));
await app.listen(3000, () => { await app.listen(3002, () => {
if (process.env.NODE_ENV == 'development') { if (process.env.NODE_ENV == 'development') {
Logger.log('Running Immich Microservices in DEVELOPMENT environment', 'ImmichMicroservice'); Logger.log('Running Immich Microservices in DEVELOPMENT environment', 'ImmichMicroservice');
} }

View File

@@ -12,6 +12,12 @@ import { ThumbnailGeneratorProcessor } from './processors/thumbnail.processor';
import { MetadataExtractionProcessor } from './processors/metadata-extraction.processor'; import { MetadataExtractionProcessor } from './processors/metadata-extraction.processor';
import { VideoTranscodeProcessor } from './processors/video-transcode.processor'; import { VideoTranscodeProcessor } from './processors/video-transcode.processor';
import { CommunicationModule } from '../../immich/src/api-v1/communication/communication.module'; import { CommunicationModule } from '../../immich/src/api-v1/communication/communication.module';
import {
assetUploadedQueueName,
metadataExtractionQueueName,
thumbnailGeneratorQueueName,
videoConversionQueueName,
} from '@app/job/constants/queue-name.constant';
@Module({ @Module({
imports: [ imports: [
@@ -26,7 +32,7 @@ import { CommunicationModule } from '../../immich/src/api-v1/communication/commu
}), }),
}), }),
BullModule.registerQueue({ BullModule.registerQueue({
name: 'thumbnail-generator-queue', name: thumbnailGeneratorQueueName,
defaultJobOptions: { defaultJobOptions: {
attempts: 3, attempts: 3,
removeOnComplete: true, removeOnComplete: true,
@@ -34,7 +40,7 @@ import { CommunicationModule } from '../../immich/src/api-v1/communication/commu
}, },
}), }),
BullModule.registerQueue({ BullModule.registerQueue({
name: 'asset-uploaded-queue', name: assetUploadedQueueName,
defaultJobOptions: { defaultJobOptions: {
attempts: 3, attempts: 3,
removeOnComplete: true, removeOnComplete: true,
@@ -42,7 +48,7 @@ import { CommunicationModule } from '../../immich/src/api-v1/communication/commu
}, },
}), }),
BullModule.registerQueue({ BullModule.registerQueue({
name: 'metadata-extraction-queue', name: metadataExtractionQueueName,
defaultJobOptions: { defaultJobOptions: {
attempts: 3, attempts: 3,
removeOnComplete: true, removeOnComplete: true,
@@ -50,7 +56,7 @@ import { CommunicationModule } from '../../immich/src/api-v1/communication/commu
}, },
}), }),
BullModule.registerQueue({ BullModule.registerQueue({
name: 'video-conversion-queue', name: videoConversionQueueName,
defaultJobOptions: { defaultJobOptions: {
attempts: 3, attempts: 3,
removeOnComplete: true, removeOnComplete: true,

View File

@@ -1,61 +1,58 @@
import { InjectQueue, Process, Processor } from '@nestjs/bull'; import { InjectQueue, Process, Processor } from '@nestjs/bull';
import { Job, Queue } from 'bull'; import { Job, Queue } from 'bull';
import { AssetEntity, AssetType } from '@app/database/entities/asset.entity'; import { AssetType } from '@app/database/entities/asset.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { randomUUID } from 'crypto'; import { randomUUID } from 'crypto';
import {
IAssetUploadedJob,
IMetadataExtractionJob,
IThumbnailGenerationJob,
IVideoTranscodeJob,
assetUploadedQueueName,
metadataExtractionQueueName,
thumbnailGeneratorQueueName,
videoConversionQueueName,
assetUploadedProcessorName,
exifExtractionProcessorName,
generateJPEGThumbnailProcessorName,
mp4ConversionProcessorName,
videoLengthExtractionProcessorName,
} from '@app/job';
@Processor('asset-uploaded-queue') @Processor(assetUploadedQueueName)
export class AssetUploadedProcessor { export class AssetUploadedProcessor {
constructor( constructor(
@InjectQueue('thumbnail-generator-queue') @InjectQueue(thumbnailGeneratorQueueName)
private thumbnailGeneratorQueue: Queue, private thumbnailGeneratorQueue: Queue<IThumbnailGenerationJob>,
@InjectQueue('metadata-extraction-queue') @InjectQueue(metadataExtractionQueueName)
private metadataExtractionQueue: Queue, private metadataExtractionQueue: Queue<IMetadataExtractionJob>,
@InjectQueue('video-conversion-queue') @InjectQueue(videoConversionQueueName)
private videoConversionQueue: Queue, private videoConversionQueue: Queue<IVideoTranscodeJob>,
@InjectRepository(AssetEntity)
private assetRepository: Repository<AssetEntity>,
) {} ) {}
/** /**
* Post processing uploaded asset to perform the following function if missing * Post processing uploaded asset to perform the following function if missing
* 1. Generate JPEG Thumbnail * 1. Generate JPEG Thumbnail
* 2. Generate Webp Thumbnail <-> if JPEG thumbnail exist * 2. Generate Webp Thumbnail
* 3. EXIF extractor * 3. EXIF extractor
* 4. Reverse Geocoding * 4. Reverse Geocoding
* *
* @param job asset-uploaded * @param job asset-uploaded
*/ */
@Process('asset-uploaded') @Process(assetUploadedProcessorName)
async processUploadedVideo(job: Job) { async processUploadedVideo(job: Job<IAssetUploadedJob>) {
const { const { asset, fileName, fileSize } = job.data;
asset,
fileName,
fileSize,
hasThumbnail,
}: { asset: AssetEntity; fileName: string; fileSize: number; hasThumbnail: boolean } = job.data;
if (hasThumbnail) { await this.thumbnailGeneratorQueue.add(generateJPEGThumbnailProcessorName, { asset }, { jobId: randomUUID() });
// The jobs below depends on the existence of jpeg thumbnail
await this.thumbnailGeneratorQueue.add('generate-webp-thumbnail', { asset }, { jobId: randomUUID() });
await this.metadataExtractionQueue.add('tag-image', { asset }, { jobId: randomUUID() });
await this.metadataExtractionQueue.add('detect-object', { asset }, { jobId: randomUUID() });
} else {
// Generate Thumbnail -> Then generate webp, tag image and detect object
await this.thumbnailGeneratorQueue.add('generate-jpeg-thumbnail', { asset }, { jobId: randomUUID() });
}
// Video Conversion // Video Conversion
if (asset.type == AssetType.VIDEO) { if (asset.type == AssetType.VIDEO) {
await this.videoConversionQueue.add('mp4-conversion', { asset }, { jobId: randomUUID() }); await this.videoConversionQueue.add(mp4ConversionProcessorName, { asset }, { jobId: randomUUID() });
} else { } else {
// Extract Metadata/Exif for Images - Currently the library cannot extract EXIF for video yet // Extract Metadata/Exif for Images - Currently the EXIF library on the web cannot extract EXIF for video yet
await this.metadataExtractionQueue.add( await this.metadataExtractionQueue.add(
'exif-extraction', exifExtractionProcessorName,
{ {
asset, asset,
fileName, fileName,
@@ -67,7 +64,7 @@ export class AssetUploadedProcessor {
// Extract video duration if uploaded from the web // Extract video duration if uploaded from the web
if (asset.type == AssetType.VIDEO && asset.duration == '0:00:00.000000') { if (asset.type == AssetType.VIDEO && asset.duration == '0:00:00.000000') {
await this.metadataExtractionQueue.add('extract-video-length', { asset }, { jobId: randomUUID() }); await this.metadataExtractionQueue.add(videoLengthExtractionProcessorName, { asset }, { jobId: randomUUID() });
} }
} }
} }

View File

@@ -12,9 +12,18 @@ import { Logger } from '@nestjs/common';
import axios from 'axios'; import axios from 'axios';
import { SmartInfoEntity } from '@app/database/entities/smart-info.entity'; import { SmartInfoEntity } from '@app/database/entities/smart-info.entity';
import ffmpeg from 'fluent-ffmpeg'; import ffmpeg from 'fluent-ffmpeg';
// import moment from 'moment'; import path from 'path';
import {
IExifExtractionProcessor,
IVideoLengthExtractionProcessor,
exifExtractionProcessorName,
imageTaggingProcessorName,
objectDetectionProcessorName,
videoLengthExtractionProcessorName,
metadataExtractionQueueName,
} from '@app/job';
@Processor('metadata-extraction-queue') @Processor(metadataExtractionQueueName)
export class MetadataExtractionProcessor { export class MetadataExtractionProcessor {
private geocodingClient?: GeocodeService; private geocodingClient?: GeocodeService;
@@ -35,8 +44,8 @@ export class MetadataExtractionProcessor {
} }
} }
@Process('exif-extraction') @Process(exifExtractionProcessorName)
async extractExifInfo(job: Job) { async extractExifInfo(job: Job<IExifExtractionProcessor>) {
try { try {
const { asset, fileName, fileSize }: { asset: AssetEntity; fileName: string; fileSize: number } = job.data; const { asset, fileName, fileSize }: { asset: AssetEntity; fileName: string; fileSize: number } = job.data;
@@ -48,7 +57,7 @@ export class MetadataExtractionProcessor {
newExif.assetId = asset.id; newExif.assetId = asset.id;
newExif.make = exifData['Make'] || null; newExif.make = exifData['Make'] || null;
newExif.model = exifData['Model'] || null; newExif.model = exifData['Model'] || null;
newExif.imageName = fileName || null; newExif.imageName = path.parse(fileName).name || null;
newExif.exifImageHeight = exifData['ExifImageHeight'] || null; newExif.exifImageHeight = exifData['ExifImageHeight'] || null;
newExif.exifImageWidth = exifData['ExifImageWidth'] || null; newExif.exifImageWidth = exifData['ExifImageWidth'] || null;
newExif.fileSizeInByte = fileSize || null; newExif.fileSizeInByte = fileSize || null;
@@ -89,11 +98,11 @@ export class MetadataExtractionProcessor {
} }
} }
@Process({ name: 'tag-image', concurrency: 2 }) @Process({ name: imageTaggingProcessorName, concurrency: 2 })
async tagImage(job: Job) { async tagImage(job: Job) {
const { asset }: { asset: AssetEntity } = job.data; const { asset }: { asset: AssetEntity } = job.data;
const res = await axios.post('http://immich-machine-learning:3001/image-classifier/tag-image', { const res = await axios.post('http://immich-machine-learning:3003/image-classifier/tag-image', {
thumbnailPath: asset.resizePath, thumbnailPath: asset.resizePath,
}); });
@@ -108,12 +117,12 @@ export class MetadataExtractionProcessor {
} }
} }
@Process({ name: 'detect-object', concurrency: 2 }) @Process({ name: objectDetectionProcessorName, concurrency: 2 })
async detectObject(job: Job) { async detectObject(job: Job) {
try { try {
const { asset }: { asset: AssetEntity } = job.data; const { asset }: { asset: AssetEntity } = job.data;
const res = await axios.post('http://immich-machine-learning:3001/object-detection/detect-object', { const res = await axios.post('http://immich-machine-learning:3003/object-detection/detect-object', {
thumbnailPath: asset.resizePath, thumbnailPath: asset.resizePath,
}); });
@@ -131,9 +140,9 @@ export class MetadataExtractionProcessor {
} }
} }
@Process({ name: 'extract-video-length', concurrency: 2 }) @Process({ name: videoLengthExtractionProcessorName, concurrency: 2 })
async extractVideoLength(job: Job) { async extractVideoLength(job: Job<IVideoLengthExtractionProcessor>) {
const { asset }: { asset: AssetEntity } = job.data; const { asset } = job.data;
ffmpeg.ffprobe(asset.originalPath, async (err, data) => { ffmpeg.ffprobe(asset.originalPath, async (err, data) => {
if (!err) { if (!err) {

View File

@@ -9,25 +9,35 @@ import { randomUUID } from 'node:crypto';
import { CommunicationGateway } from '../../../immich/src/api-v1/communication/communication.gateway'; import { CommunicationGateway } from '../../../immich/src/api-v1/communication/communication.gateway';
import ffmpeg from 'fluent-ffmpeg'; import ffmpeg from 'fluent-ffmpeg';
import { Logger } from '@nestjs/common'; import { Logger } from '@nestjs/common';
import {
WebpGeneratorProcessor,
generateJPEGThumbnailProcessorName,
generateWEBPThumbnailProcessorName,
imageTaggingProcessorName,
objectDetectionProcessorName,
metadataExtractionQueueName,
thumbnailGeneratorQueueName,
JpegGeneratorProcessor,
} from '@app/job';
@Processor('thumbnail-generator-queue') @Processor(thumbnailGeneratorQueueName)
export class ThumbnailGeneratorProcessor { export class ThumbnailGeneratorProcessor {
constructor( constructor(
@InjectRepository(AssetEntity) @InjectRepository(AssetEntity)
private assetRepository: Repository<AssetEntity>, private assetRepository: Repository<AssetEntity>,
@InjectQueue('thumbnail-generator-queue') @InjectQueue(thumbnailGeneratorQueueName)
private thumbnailGeneratorQueue: Queue, private thumbnailGeneratorQueue: Queue,
private wsCommunicateionGateway: CommunicationGateway, private wsCommunicateionGateway: CommunicationGateway,
@InjectQueue('metadata-extraction-queue') @InjectQueue(metadataExtractionQueueName)
private metadataExtractionQueue: Queue, private metadataExtractionQueue: Queue,
) {} ) {}
@Process('generate-jpeg-thumbnail') @Process({ name: generateJPEGThumbnailProcessorName, concurrency: 3 })
async generateJPEGThumbnail(job: Job) { async generateJPEGThumbnail(job: Job<JpegGeneratorProcessor>) {
const { asset }: { asset: AssetEntity } = job.data; const { asset } = job.data;
const resizePath = `upload/${asset.userId}/thumb/${asset.deviceId}/`; const resizePath = `upload/${asset.userId}/thumb/${asset.deviceId}/`;
@@ -43,6 +53,7 @@ export class ThumbnailGeneratorProcessor {
sharp(asset.originalPath) sharp(asset.originalPath)
.resize(1440, 2560, { fit: 'inside' }) .resize(1440, 2560, { fit: 'inside' })
.jpeg() .jpeg()
.rotate()
.toFile(jpegThumbnailPath, async (err) => { .toFile(jpegThumbnailPath, async (err) => {
if (!err) { if (!err) {
await this.assetRepository.update({ id: asset.id }, { resizePath: jpegThumbnailPath }); await this.assetRepository.update({ id: asset.id }, { resizePath: jpegThumbnailPath });
@@ -50,9 +61,13 @@ export class ThumbnailGeneratorProcessor {
// Update resize path to send to generate webp queue // Update resize path to send to generate webp queue
asset.resizePath = jpegThumbnailPath; asset.resizePath = jpegThumbnailPath;
await this.thumbnailGeneratorQueue.add('generate-webp-thumbnail', { asset }, { jobId: randomUUID() }); await this.thumbnailGeneratorQueue.add(
await this.metadataExtractionQueue.add('tag-image', { asset }, { jobId: randomUUID() }); generateWEBPThumbnailProcessorName,
await this.metadataExtractionQueue.add('detect-object', { asset }, { jobId: randomUUID() }); { asset },
{ jobId: randomUUID() },
);
await this.metadataExtractionQueue.add(imageTaggingProcessorName, { asset }, { jobId: randomUUID() });
await this.metadataExtractionQueue.add(objectDetectionProcessorName, { asset }, { jobId: randomUUID() });
this.wsCommunicateionGateway.server.to(asset.userId).emit('on_upload_success', JSON.stringify(asset)); this.wsCommunicateionGateway.server.to(asset.userId).emit('on_upload_success', JSON.stringify(asset));
} }
}); });
@@ -60,7 +75,7 @@ export class ThumbnailGeneratorProcessor {
if (asset.type == AssetType.VIDEO) { if (asset.type == AssetType.VIDEO) {
ffmpeg(asset.originalPath) ffmpeg(asset.originalPath)
.outputOptions(['-ss 00:00:01.000', '-frames:v 1']) .outputOptions(['-ss 00:00:00.000', '-frames:v 1'])
.output(jpegThumbnailPath) .output(jpegThumbnailPath)
.on('start', () => { .on('start', () => {
Logger.log('Start Generating Video Thumbnail', 'generateJPEGThumbnail'); Logger.log('Start Generating Video Thumbnail', 'generateJPEGThumbnail');
@@ -76,9 +91,13 @@ export class ThumbnailGeneratorProcessor {
// Update resize path to send to generate webp queue // Update resize path to send to generate webp queue
asset.resizePath = jpegThumbnailPath; asset.resizePath = jpegThumbnailPath;
await this.thumbnailGeneratorQueue.add('generate-webp-thumbnail', { asset }, { jobId: randomUUID() }); await this.thumbnailGeneratorQueue.add(
await this.metadataExtractionQueue.add('tag-image', { asset }, { jobId: randomUUID() }); generateWEBPThumbnailProcessorName,
await this.metadataExtractionQueue.add('detect-object', { asset }, { jobId: randomUUID() }); { asset },
{ jobId: randomUUID() },
);
await this.metadataExtractionQueue.add(imageTaggingProcessorName, { asset }, { jobId: randomUUID() });
await this.metadataExtractionQueue.add(objectDetectionProcessorName, { asset }, { jobId: randomUUID() });
this.wsCommunicateionGateway.server.to(asset.userId).emit('on_upload_success', JSON.stringify(asset)); this.wsCommunicateionGateway.server.to(asset.userId).emit('on_upload_success', JSON.stringify(asset));
}) })
@@ -86,8 +105,8 @@ export class ThumbnailGeneratorProcessor {
} }
} }
@Process({ name: 'generate-webp-thumbnail', concurrency: 2 }) @Process({ name: generateWEBPThumbnailProcessorName, concurrency: 3 })
async generateWepbThumbnail(job: Job<{ asset: AssetEntity }>) { async generateWepbThumbnail(job: Job<WebpGeneratorProcessor>) {
const { asset } = job.data; const { asset } = job.data;
if (!asset.resizePath) { if (!asset.resizePath) {
@@ -98,6 +117,7 @@ export class ThumbnailGeneratorProcessor {
sharp(asset.resizePath) sharp(asset.resizePath)
.resize(250) .resize(250)
.webp() .webp()
.rotate()
.toFile(webpPath, (err) => { .toFile(webpPath, (err) => {
if (!err) { if (!err) {
this.assetRepository.update({ id: asset.id }, { webpPath: webpPath }); this.assetRepository.update({ id: asset.id }, { webpPath: webpPath });

View File

@@ -1,3 +1,6 @@
import { mp4ConversionProcessorName } from '@app/job/constants/job-name.constant';
import { videoConversionQueueName } from '@app/job/constants/queue-name.constant';
import { IMp4ConversionProcessor } from '@app/job/interfaces/video-transcode.interface';
import { Process, Processor } from '@nestjs/bull'; import { Process, Processor } from '@nestjs/bull';
import { Logger } from '@nestjs/common'; import { Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm'; import { InjectRepository } from '@nestjs/typeorm';
@@ -8,16 +11,16 @@ import { Repository } from 'typeorm';
import { AssetEntity } from '../../../../libs/database/src/entities/asset.entity'; import { AssetEntity } from '../../../../libs/database/src/entities/asset.entity';
import { APP_UPLOAD_LOCATION } from '../../../immich/src/constants/upload_location.constant'; import { APP_UPLOAD_LOCATION } from '../../../immich/src/constants/upload_location.constant';
@Processor('video-conversion-queue') @Processor(videoConversionQueueName)
export class VideoTranscodeProcessor { export class VideoTranscodeProcessor {
constructor( constructor(
@InjectRepository(AssetEntity) @InjectRepository(AssetEntity)
private assetRepository: Repository<AssetEntity>, private assetRepository: Repository<AssetEntity>,
) {} ) {}
@Process({ name: 'mp4-conversion', concurrency: 1 }) @Process({ name: mp4ConversionProcessorName, concurrency: 1 })
async mp4Conversion(job: Job) { async mp4Conversion(job: Job<IMp4ConversionProcessor>) {
const { asset }: { asset: AssetEntity } = job.data; const { asset } = job.data;
if (asset.mimeType != 'video/mp4') { if (asset.mimeType != 'video/mp4') {
const basePath = APP_UPLOAD_LOCATION; const basePath = APP_UPLOAD_LOCATION;

View File

@@ -1,6 +1,7 @@
import { TypeOrmModuleOptions } from '@nestjs/typeorm'; import { TypeOrmModuleOptions } from '@nestjs/typeorm';
import { PostgresConnectionOptions } from 'typeorm/driver/postgres/PostgresConnectionOptions';
export const databaseConfig: TypeOrmModuleOptions = { export const databaseConfig: PostgresConnectionOptions = {
type: 'postgres', type: 'postgres',
host: process.env.DB_HOSTNAME || 'immich_postgres', host: process.env.DB_HOSTNAME || 'immich_postgres',
port: 5432, port: 5432,
@@ -10,11 +11,7 @@ export const databaseConfig: TypeOrmModuleOptions = {
entities: [__dirname + '/../**/*.entity.{js,ts}'], entities: [__dirname + '/../**/*.entity.{js,ts}'],
synchronize: false, synchronize: false,
migrations: [__dirname + '/../migrations/*.{js,ts}'], migrations: [__dirname + '/../migrations/*.{js,ts}'],
cli: {
migrationsDir: __dirname + '/../migrations',
},
migrationsRun: true, migrationsRun: true,
autoLoadEntities: true,
}; };
export default databaseConfig; export default databaseConfig;

View File

@@ -0,0 +1,23 @@
/**
* Asset Uploaded Queue Jobs
*/
export const assetUploadedProcessorName = 'asset-uploaded';
/**
* Video Conversion Queue Jobs
**/
export const mp4ConversionProcessorName = 'mp4-conversion';
/**
* Thumbnail Generator Queue Jobs
*/
export const generateJPEGThumbnailProcessorName = 'generate-jpeg-thumbnail';
export const generateWEBPThumbnailProcessorName = 'generate-webp-thumbnail';
/**
* Metadata Extraction Queue Jobs
*/
export const exifExtractionProcessorName = 'exif-extraction';
export const videoLengthExtractionProcessorName = 'extract-video-length';
export const objectDetectionProcessorName = 'detect-object';
export const imageTaggingProcessorName = 'tag-image';

View File

@@ -0,0 +1,4 @@
export const thumbnailGeneratorQueueName = 'thumbnail-generator-queue';
export const assetUploadedQueueName = 'asset-uploaded-queue';
export const metadataExtractionQueueName = 'metadata-extraction-queue';
export const videoConversionQueueName = 'video-conversion-queue';

View File

@@ -0,0 +1,7 @@
export * from './interfaces/asset-uploaded.interface';
export * from './interfaces/metadata-extraction.interface';
export * from './interfaces/video-transcode.interface';
export * from './interfaces/thumbnail-generation.interface';
export * from './constants/job-name.constant';
export * from './constants/queue-name.constant';

View File

@@ -0,0 +1,18 @@
import { AssetEntity } from '@app/database/entities/asset.entity';
export interface IAssetUploadedJob {
/**
* The Asset entity that was saved in the database
*/
asset: AssetEntity;
/**
* Original file name
*/
fileName: string;
/**
* File size in byte
*/
fileSize: number;
}

View File

@@ -0,0 +1,27 @@
import { AssetEntity } from '@app/database/entities/asset.entity';
export interface IExifExtractionProcessor {
/**
* The Asset entity that was saved in the database
*/
asset: AssetEntity;
/**
* Original file name
*/
fileName: string;
/**
* File size in byte
*/
fileSize: number;
}
export interface IVideoLengthExtractionProcessor {
/**
* The Asset entity that was saved in the database
*/
asset: AssetEntity;
}
export type IMetadataExtractionJob = IExifExtractionProcessor | IVideoLengthExtractionProcessor;

View File

@@ -0,0 +1,17 @@
import { AssetEntity } from '@app/database/entities/asset.entity';
export interface JpegGeneratorProcessor {
/**
* The Asset entity that was saved in the database
*/
asset: AssetEntity;
}
export interface WebpGeneratorProcessor {
/**
* The Asset entity that was saved in the database
*/
asset: AssetEntity;
}
export type IThumbnailGenerationJob = JpegGeneratorProcessor | WebpGeneratorProcessor;

View File

@@ -0,0 +1,10 @@
import { AssetEntity } from '@app/database/entities/asset.entity';
export interface IMp4ConversionProcessor {
/**
* The Asset entity that was saved in the database
*/
asset: AssetEntity;
}
export type IVideoTranscodeJob = IMp4ConversionProcessor;

View File

@@ -0,0 +1,9 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"declaration": true,
"outDir": "../../dist/libs/job"
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist", "test", "**/*spec.ts"]
}

View File

@@ -34,6 +34,15 @@
"compilerOptions": { "compilerOptions": {
"tsConfigPath": "libs/database/tsconfig.lib.json" "tsConfigPath": "libs/database/tsconfig.lib.json"
} }
},
"job": {
"type": "library",
"root": "libs/job",
"entryFile": "index",
"sourceRoot": "libs/job/src",
"compilerOptions": {
"tsConfigPath": "libs/job/tsconfig.lib.json"
}
} }
} }
} }

2307
server/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -26,19 +26,19 @@
}, },
"dependencies": { "dependencies": {
"@mapbox/mapbox-sdk": "^0.13.3", "@mapbox/mapbox-sdk": "^0.13.3",
"@nestjs/bull": "^0.4.2", "@nestjs/bull": "^0.5.5",
"@nestjs/common": "^8.0.0", "@nestjs/common": "^8.4.7",
"@nestjs/config": "^1.1.6", "@nestjs/config": "^2.1.0",
"@nestjs/core": "^8.0.0", "@nestjs/core": "^8.4.7",
"@nestjs/jwt": "^8.0.0", "@nestjs/jwt": "^8.0.1",
"@nestjs/mapped-types": "*", "@nestjs/mapped-types": "*",
"@nestjs/passport": "^8.1.0", "@nestjs/passport": "^8.2.2",
"@nestjs/platform-express": "^8.0.0", "@nestjs/platform-express": "^8.4.7",
"@nestjs/platform-fastify": "^8.2.6", "@nestjs/platform-fastify": "^8.4.7",
"@nestjs/platform-socket.io": "^8.2.6", "@nestjs/platform-socket.io": "^8.4.7",
"@nestjs/schedule": "^2.0.1", "@nestjs/schedule": "^2.0.1",
"@nestjs/typeorm": "^8.0.3", "@nestjs/typeorm": "^8.1.4",
"@nestjs/websockets": "^8.2.6", "@nestjs/websockets": "^8.4.7",
"@socket.io/redis-adapter": "^7.1.0", "@socket.io/redis-adapter": "^7.1.0",
"axios": "^0.26.0", "axios": "^0.26.0",
"bcrypt": "^5.0.1", "bcrypt": "^5.0.1",
@@ -61,12 +61,12 @@
"sharp": "^0.28.0", "sharp": "^0.28.0",
"socket.io-redis": "^6.1.1", "socket.io-redis": "^6.1.1",
"systeminformation": "^5.11.0", "systeminformation": "^5.11.0",
"typeorm": "^0.2.41" "typeorm": "^0.3.6"
}, },
"devDependencies": { "devDependencies": {
"@nestjs/cli": "^8.2.4", "@nestjs/cli": "^8.2.8",
"@nestjs/schematics": "^8.0.0", "@nestjs/schematics": "^8.0.11",
"@nestjs/testing": "^8.0.0", "@nestjs/testing": "^8.4.7",
"@types/bcrypt": "^5.0.0", "@types/bcrypt": "^5.0.0",
"@types/bull": "^3.15.7", "@types/bull": "^3.15.7",
"@types/cron": "^2.0.0", "@types/cron": "^2.0.0",
@@ -120,7 +120,8 @@
"moduleNameMapper": { "moduleNameMapper": {
"^@app/database(|/.*)$": "<rootDir>/libs/database/src/$1", "^@app/database(|/.*)$": "<rootDir>/libs/database/src/$1",
"@app/database/config/(.*)": "<rootDir>/libs/database/src/config/$1", "@app/database/config/(.*)": "<rootDir>/libs/database/src/config/$1",
"@app/database/config": "<rootDir>/libs/database/src/config" "@app/database/config": "<rootDir>/libs/database/src/config",
"^@app/job(|/.*)$": "<rootDir>/libs/job/src/$1"
} }
} }
} }

View File

@@ -21,6 +21,12 @@
], ],
"@app/database/*": [ "@app/database/*": [
"libs/database/src/*" "libs/database/src/*"
],
"@app/job": [
"libs/job/src"
],
"@app/job/*": [
"libs/job/src/*"
] ]
} }
}, },

View File

@@ -63,7 +63,9 @@
dispatch('close'); dispatch('close');
}; };
const navigateAssetForward = () => { const navigateAssetForward = (e?: Event) => {
e?.stopPropagation();
const nextAsset = $flattenAssetGroupByDate[selectedIndex + 1]; const nextAsset = $flattenAssetGroupByDate[selectedIndex + 1];
viewDeviceId = nextAsset.deviceId; viewDeviceId = nextAsset.deviceId;
viewAssetId = nextAsset.id; viewAssetId = nextAsset.id;
@@ -73,7 +75,9 @@
pushState(viewAssetId); pushState(viewAssetId);
}; };
const navigateAssetBackward = () => { const navigateAssetBackward = (e?: Event) => {
e?.stopPropagation();
const lastAsset = $flattenAssetGroupByDate[selectedIndex - 1]; const lastAsset = $flattenAssetGroupByDate[selectedIndex - 1];
viewDeviceId = lastAsset.deviceId; viewDeviceId = lastAsset.deviceId;
viewAssetId = lastAsset.id; viewAssetId = lastAsset.id;

View File

@@ -8,6 +8,7 @@
import type { ImmichAsset } from '../../models/immich-asset'; import type { ImmichAsset } from '../../models/immich-asset';
import { createEventDispatcher, onMount } from 'svelte'; import { createEventDispatcher, onMount } from 'svelte';
import { browser } from '$app/env'; import { browser } from '$app/env';
import { round } from 'lodash';
// Map Property // Map Property
let map: any; let map: any;
@@ -80,6 +81,16 @@
return `${sizeInByte}B`; return `${sizeInByte}B`;
} }
}; };
const getMegapixel = (width: number, height: number): number | undefined => {
const megapixel = Math.round((height * width) / 1_000_000);
if (megapixel) {
return megapixel;
}
return undefined;
};
</script> </script>
<section class="p-2"> <section class="p-2">
@@ -129,8 +140,13 @@
<div> <div>
<p>{`${asset.exifInfo.imageName}.${asset.originalPath.split('.')[1]}` || ''}</p> <p>{`${asset.exifInfo.imageName}.${asset.originalPath.split('.')[1]}` || ''}</p>
<div class="flex text-sm gap-2"> <div class="flex text-sm gap-2">
<p>{((asset.exifInfo.exifImageHeight * asset.exifInfo.exifImageWidth) / 1_000_000).toFixed(0)}MP</p> {#if asset.exifInfo.exifImageHeight && asset.exifInfo.exifImageWidth}
<p>{asset.exifInfo.exifImageHeight} x {asset.exifInfo.exifImageWidth}</p> {#if getMegapixel(asset.exifInfo.exifImageHeight, asset.exifInfo.exifImageWidth)}
<p>{getMegapixel(asset.exifInfo.exifImageHeight, asset.exifInfo.exifImageWidth)}MP</p>
{/if}
<p>{asset.exifInfo.exifImageHeight} x {asset.exifInfo.exifImageWidth}</p>
{/if}
<p>{getHumanReadableString(asset.exifInfo.fileSizeInByte)}</p> <p>{getHumanReadableString(asset.exifInfo.fileSizeInByte)}</p>
</div> </div>
</div> </div>

View File

@@ -5,6 +5,8 @@
import CloudUploadOutline from 'svelte-material-icons/CloudUploadOutline.svelte'; import CloudUploadOutline from 'svelte-material-icons/CloudUploadOutline.svelte';
import WindowMinimize from 'svelte-material-icons/WindowMinimize.svelte'; import WindowMinimize from 'svelte-material-icons/WindowMinimize.svelte';
import type { UploadAsset } from '$lib/models/upload-asset'; import type { UploadAsset } from '$lib/models/upload-asset';
import { getAssetsInfo } from '$lib/stores/assets';
import { session } from '$app/stores';
let showDetail = true; let showDetail = true;
@@ -73,8 +75,15 @@
} }
let isUploading = false; let isUploading = false;
uploadAssetsStore.isUploading.subscribe((value) => {
isUploading = value;
uploadAssetsStore.isUploading.subscribe((value) => (isUploading = value)); if (isUploading == false) {
if ($session.user) {
getAssetsInfo($session.user.accessToken);
}
}
});
</script> </script>
{#if isUploading} {#if isUploading}

View File

@@ -2,8 +2,8 @@ import { writable, derived } from 'svelte/store';
import { getRequest } from '$lib/api'; import { getRequest } from '$lib/api';
import type { ImmichAsset } from '$lib/models/immich-asset'; import type { ImmichAsset } from '$lib/models/immich-asset';
import lodash from 'lodash-es'; import lodash from 'lodash-es';
import _ from 'lodash';
import moment from 'moment'; import moment from 'moment';
export const assets = writable<ImmichAsset[]>([]); export const assets = writable<ImmichAsset[]>([]);
export const assetsGroupByDate = derived(assets, ($assets) => { export const assetsGroupByDate = derived(assets, ($assets) => {
@@ -14,7 +14,6 @@ export const assetsGroupByDate = derived(assets, ($assets) => {
.sortBy((group) => $assets.indexOf(group[0])) .sortBy((group) => $assets.indexOf(group[0]))
.value(); .value();
} catch (e) { } catch (e) {
console.log('error deriving state assets', e);
return []; return [];
} }
}); });

View File

@@ -1,12 +1,16 @@
import { Socket, io } from 'socket.io-client'; import { Socket, io } from 'socket.io-client';
import { writable } from 'svelte/store';
import { serverEndpoint } from '../constants'; import { serverEndpoint } from '../constants';
import type { ImmichAsset } from '../models/immich-asset'; import type { ImmichAsset } from '../models/immich-asset';
import { assets } from './assets'; import { assets } from './assets';
let websocket: Socket;
export const openWebsocketConnection = (accessToken: string) => { export const openWebsocketConnection = (accessToken: string) => {
const websocketEndpoint = serverEndpoint.replace('/api', ''); const websocketEndpoint = serverEndpoint.replace('/api', '');
try { try {
const websocket = io(websocketEndpoint, { websocket = io(websocketEndpoint, {
path: '/api/socket.io', path: '/api/socket.io',
transports: ['polling'], transports: ['polling'],
reconnection: true, reconnection: true,
@@ -26,11 +30,14 @@ export const openWebsocketConnection = (accessToken: string) => {
const listenToEvent = (socket: Socket) => { const listenToEvent = (socket: Socket) => {
socket.on('on_upload_success', (data) => { socket.on('on_upload_success', (data) => {
const newUploadedAsset: ImmichAsset = JSON.parse(data); const newUploadedAsset: ImmichAsset = JSON.parse(data);
// assets.update((assets) => [...assets, newUploadedAsset]);
assets.update((assets) => [...assets, newUploadedAsset]);
}); });
socket.on('error', (e) => { socket.on('error', (e) => {
console.log('Websocket Error', e); console.log('Websocket Error', e);
}); });
}; };
export const closeWebsocketConnection = () => {
websocket?.close();
};

View File

@@ -84,7 +84,7 @@ export async function fileUploader(asset: File, accessToken: string) {
request.upload.onload = () => { request.upload.onload = () => {
setTimeout(() => { setTimeout(() => {
uploadAssetsStore.removeUploadAsset(deviceAssetId); uploadAssetsStore.removeUploadAsset(deviceAssetId);
}, 2500); }, 1000);
}; };
// listen for `error` event // listen for `error` event

View File

@@ -31,7 +31,7 @@
import ImageOutline from 'svelte-material-icons/ImageOutline.svelte'; import ImageOutline from 'svelte-material-icons/ImageOutline.svelte';
import { AppSideBarSelection } from '$lib/models/admin-sidebar-selection'; import { AppSideBarSelection } from '$lib/models/admin-sidebar-selection';
import { onMount } from 'svelte'; import { onDestroy, onMount } from 'svelte';
import { fly } from 'svelte/transition'; import { fly } from 'svelte/transition';
import { session } from '$app/stores'; import { session } from '$app/stores';
import { assetsGroupByDate, flattenAssetGroupByDate } from '$lib/stores/assets'; import { assetsGroupByDate, flattenAssetGroupByDate } from '$lib/stores/assets';
@@ -42,7 +42,7 @@
import DownloadPanel from '../../lib/components/asset-viewer/download-panel.svelte'; import DownloadPanel from '../../lib/components/asset-viewer/download-panel.svelte';
import StatusBox from '../../lib/components/shared/status-box.svelte'; import StatusBox from '../../lib/components/shared/status-box.svelte';
import { fileUploader } from '../../lib/utils/file-uploader'; import { fileUploader } from '../../lib/utils/file-uploader';
import { openWebsocketConnection } from '../../lib/stores/websocket'; import { openWebsocketConnection, closeWebsocketConnection } from '../../lib/stores/websocket';
export let user: ImmichUser; export let user: ImmichUser;
let selectedAction: AppSideBarSelection; let selectedAction: AppSideBarSelection;
@@ -71,6 +71,10 @@
} }
}); });
onDestroy(() => {
closeWebsocketConnection();
});
const thumbnailMouseEventHandler = (event: CustomEvent) => { const thumbnailMouseEventHandler = (event: CustomEvent) => {
const { selectedGroupIndex }: { selectedGroupIndex: number } = event.detail; const { selectedGroupIndex }: { selectedGroupIndex: number } = event.detail;