Compare commits
22 Commits
v1.10.0_15
...
v1.12.0_18
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b7603fd150 | ||
|
|
517a3363d6 | ||
|
|
3511b69fc8 | ||
|
|
e6efc61b3b | ||
|
|
360c1d9a15 | ||
|
|
e3449f9c8f | ||
|
|
a8e723d722 | ||
|
|
d116234523 | ||
|
|
dce2bc7508 | ||
|
|
2bf764f560 | ||
|
|
587b77e70b | ||
|
|
53cd9fd8bf | ||
|
|
a8220172f8 | ||
|
|
397f8c70b4 | ||
|
|
68ff5377b0 | ||
|
|
b359dc3cb6 | ||
|
|
5b036067ed | ||
|
|
b9f38162d5 | ||
|
|
ab6909bfbd | ||
|
|
53c3c916a6 | ||
|
|
6924aa5eb1 | ||
|
|
a3b45d62b6 |
8
.github/ISSUE_TEMPLATE/bug_report.md
vendored
8
.github/ISSUE_TEMPLATE/bug_report.md
vendored
@@ -16,10 +16,10 @@ Note: Please search to see if an issue already exists for the bug you encountere
|
||||
A clear and concise description of what the bug is.
|
||||
|
||||
**Task List**
|
||||
[ ] I have read thoroughly the README setup and installation instructions.
|
||||
[ ] If my setup is different, I have included my docker-compose file.
|
||||
[ ] I have included my redacted `.env` file.
|
||||
[ ] I have included information on my machine, and environment.
|
||||
- [ ] I have read thoroughly the README setup and installation instructions.
|
||||
- [ ] If my setup is different, I have included my docker-compose file.
|
||||
- [ ] I have included my redacted `.env` file.
|
||||
- [ ] I have included information on my machine, and environment.
|
||||
|
||||
**To Reproduce**
|
||||
Steps to reproduce the behavior:
|
||||
|
||||
27
.github/workflows/build_push_docker_latest.yml
vendored
27
.github/workflows/build_push_docker_latest.yml
vendored
@@ -4,17 +4,16 @@ on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
build_and_push_server_latest:
|
||||
# This image include both the server and microservices - the two containers can be slitted into separated
|
||||
# service with its coressponding entry file.
|
||||
build_and_push_server_monorepo_latest:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
# ref: "main" # branch
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Set up QEMU
|
||||
@@ -27,23 +26,22 @@ jobs:
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
- name: Build and push Immich
|
||||
- name: Build and push Immich Mono Repo
|
||||
uses: docker/build-push-action@v3.0.0
|
||||
with:
|
||||
context: ./server
|
||||
file: ./server/Dockerfile
|
||||
platforms: linux/arm/v7,linux/amd64,linux/arm64
|
||||
push: ${{ github.event_name != 'pull_request' }}
|
||||
push: true
|
||||
tags: |
|
||||
altran1502/immich-server:latest
|
||||
|
||||
build_and_push_microservice_latest:
|
||||
build_and_push_machine_learning_latest:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
# ref: "main" # branch
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Set up QEMU
|
||||
@@ -56,15 +54,15 @@ jobs:
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
- name: Build and Push Microservices
|
||||
- name: Build and Push Machine Learning
|
||||
uses: docker/build-push-action@v3.0.0
|
||||
with:
|
||||
context: ./microservices
|
||||
file: ./microservices/Dockerfile
|
||||
context: ./machine-learning
|
||||
file: ./machine-learning/Dockerfile
|
||||
platforms: linux/arm/v7,linux/amd64
|
||||
push: ${{ github.event_name != 'pull_request' }}
|
||||
push: true
|
||||
tags: |
|
||||
altran1502/immich-microservices:latest
|
||||
altran1502/immich-machine-learning:latest
|
||||
|
||||
build_and_push_web_latest:
|
||||
runs-on: ubuntu-latest
|
||||
@@ -72,7 +70,6 @@ jobs:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
# ref: "main" # branch
|
||||
fetch-depth: 0
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v2.0.0
|
||||
@@ -91,6 +88,6 @@ jobs:
|
||||
file: ./web/Dockerfile
|
||||
platforms: linux/arm/v7,linux/amd64,linux/arm64
|
||||
target: prod
|
||||
push: ${{ github.event_name != 'pull_request' }}
|
||||
push: true
|
||||
tags: |
|
||||
altran1502/immich-web:latest
|
||||
|
||||
95
.github/workflows/build_push_docker_staging.yml
vendored
Normal file
95
.github/workflows/build_push_docker_staging.yml
vendored
Normal file
@@ -0,0 +1,95 @@
|
||||
name: Build and Push Docker Image - Staging
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
# This image include both the server and microservices - the two containers can be slitted into separated
|
||||
# service with its coressponding entry file.
|
||||
build_and_push_server_monorepo_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 Immich Mono Repo
|
||||
uses: docker/build-push-action@v3.0.0
|
||||
with:
|
||||
context: ./server
|
||||
file: ./server/Dockerfile
|
||||
platforms: linux/arm/v7,linux/amd64,linux/arm64
|
||||
push: ${{ github.event_name == 'pull_request' }}
|
||||
tags: |
|
||||
altran1502/immich-server:staging
|
||||
|
||||
build_and_push_machine_learning_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 Machine Learning
|
||||
uses: docker/build-push-action@v3.0.0
|
||||
with:
|
||||
context: ./machine-learning
|
||||
file: ./machine-learning/Dockerfile
|
||||
platforms: linux/arm/v7,linux/amd64
|
||||
push: ${{ github.event_name == 'pull_request' }}
|
||||
tags: |
|
||||
altran1502/immich-machine-learning:staging
|
||||
|
||||
build_and_push_web_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 Web
|
||||
uses: docker/build-push-action@v3.0.0
|
||||
with:
|
||||
context: ./web
|
||||
file: ./web/Dockerfile
|
||||
platforms: linux/arm/v7,linux/amd64,linux/arm64
|
||||
target: prod
|
||||
push: ${{ github.event_name == 'pull_request' }}
|
||||
tags: |
|
||||
altran1502/immich-web:staging
|
||||
20
.github/workflows/build_push_server_release.yml
vendored
20
.github/workflows/build_push_server_release.yml
vendored
@@ -6,7 +6,7 @@ on:
|
||||
types: [published]
|
||||
|
||||
jobs:
|
||||
build_and_push_server_release:
|
||||
build_and_push_server_monorepo_release:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -44,43 +44,37 @@ jobs:
|
||||
tags: |
|
||||
altran1502/immich-server:${{ steps.previoustag.outputs.tag }}
|
||||
|
||||
build_and_push_microservice_release:
|
||||
build_and_push_machine_learning_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-microservices release
|
||||
- name: Build and Push Machine Learning
|
||||
uses: docker/build-push-action@v3.0.0
|
||||
with:
|
||||
context: ./microservices
|
||||
file: ./microservices/Dockerfile
|
||||
context: ./machine-learning
|
||||
file: ./machine-learning/Dockerfile
|
||||
platforms: linux/arm/v7,linux/amd64
|
||||
push: ${{ github.event_name != 'pull_request' }}
|
||||
push: true
|
||||
tags: |
|
||||
altran1502/immich-microservices:${{ steps.previoustag.outputs.tag }}
|
||||
altran1502/immich-machine-learning:${{ steps.previoustag.outputs.tag }}
|
||||
|
||||
build_and_push_web_release:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
6
Makefile
6
Makefile
@@ -5,16 +5,16 @@ dev-update:
|
||||
docker-compose -f ./docker/docker-compose.dev.yml up --build -V --remove-orphans
|
||||
|
||||
dev-scale:
|
||||
docker-compose -f ./docker/docker-compose.dev.yml up --build -V --scale immich_server=3 --remove-orphans
|
||||
docker-compose -f ./docker/docker-compose.dev.yml up --build -V --scale immich-server=3 --remove-orphans
|
||||
|
||||
stage:
|
||||
docker-compose -f ./docker/docker-compose.staging.yml up --build -V --remove-orphans
|
||||
|
||||
test-e2e:
|
||||
docker-compose -f ./docker/docker-compose.test.yml --env-file ./docker/.env.test up --abort-on-container-exit --exit-code-from immich_server_test
|
||||
docker-compose -f ./docker/docker-compose.test.yml --env-file ./docker/.env.test up --renew-anon-volumes --abort-on-container-exit --exit-code-from immich_server_test --remove-orphans
|
||||
|
||||
prod:
|
||||
docker-compose -f ./docker/docker-compose.yml up --build -V --remove-orphans
|
||||
|
||||
prod-scale:
|
||||
docker-compose -f ./docker/docker-compose.yml up --build -V --scale immich_server=3 --scale immich_microservices=3 --remove-orphans
|
||||
docker-compose -f ./docker/docker-compose.yml up --build -V --scale immich-server=5 --scale immich-microservices=3 --remove-orphans
|
||||
@@ -10,14 +10,16 @@
|
||||
<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=Server Docker&logo=docker&labelColor=ececec" />
|
||||
</a>
|
||||
|
||||
<a href="https://discord.gg/rxnyVTXGbM">
|
||||
<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>
|
||||
<br/>
|
||||
<br/>
|
||||
<br/>
|
||||
<br/>
|
||||
|
||||
<p align="center">
|
||||
<img src="design/immich-logo.svg" width="200" title="Immich Logo">
|
||||
<img src="design/feature-panel.png" title="Immich Logo">
|
||||
</p>
|
||||
</p>
|
||||
|
||||
@@ -257,5 +259,5 @@ You need to change the CPU type from `kvm64` to `host` under VMs hardware tab.
|
||||
`Hardware > Processors > Edit > Advanced > Type (dropdown menu) > host`
|
||||
|
||||
Otherwise you can:
|
||||
- edit `docker-compose.yml` file and comment the whole `immich_microservices` service **which will disable machine learning features like object detection and image classification**
|
||||
- edit `docker-compose.yml` file and comment the whole `immich-machine-learning` service **which will disable machine learning features like object detection and image classification**
|
||||
- switch to a different VM/desktop with different architecture.
|
||||
|
||||
BIN
design/feature-panel.png
Normal file
BIN
design/feature-panel.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 48 KiB |
@@ -1,9 +1,12 @@
|
||||
DB_HOSTNAME=immich_postgres_test
|
||||
# Database
|
||||
DB_HOSTNAME=immich_postgres_test
|
||||
DB_USERNAME=postgres
|
||||
DB_PASSWORD=postgres
|
||||
DB_DATABASE_NAME=e2e_test
|
||||
|
||||
# Redis
|
||||
REDIS_HOSTNAME=immich_redis_test
|
||||
|
||||
# Upload File Config
|
||||
UPLOAD_LOCATION=./upload
|
||||
|
||||
@@ -13,4 +16,7 @@ JWT_SECRET=randomstringthatissolongandpowerfulthatnoonecanguess
|
||||
# MAPBOX
|
||||
## ENABLE_MAPBOX is either true of false -> if true, you have to provide MAPBOX_KEY
|
||||
ENABLE_MAPBOX=false
|
||||
MAPBOX_KEY=
|
||||
|
||||
# WEB
|
||||
MAPBOX_KEY=
|
||||
VITE_SERVER_ENDPOINT=http://localhost:2283
|
||||
@@ -6,7 +6,7 @@ services:
|
||||
build:
|
||||
context: ../server
|
||||
dockerfile: Dockerfile
|
||||
command: npm run start:dev
|
||||
command: npm run start:dev immich
|
||||
expose:
|
||||
- "3000"
|
||||
volumes:
|
||||
@@ -23,16 +23,35 @@ services:
|
||||
networks:
|
||||
- immich-network
|
||||
|
||||
immich-microservices:
|
||||
image: immich-microservices-dev:1.9.0
|
||||
immich-machine-learning:
|
||||
image: immich-machine-learning-dev:1.9.0
|
||||
build:
|
||||
context: ../microservices
|
||||
context: ../machine-learning
|
||||
dockerfile: Dockerfile
|
||||
command: npm run start:dev
|
||||
expose:
|
||||
- "3001"
|
||||
volumes:
|
||||
- ../microservices:/usr/src/app
|
||||
- ../machine-learning:/usr/src/app
|
||||
- ${UPLOAD_LOCATION}:/usr/src/app/upload
|
||||
- /usr/src/app/node_modules
|
||||
env_file:
|
||||
- .env
|
||||
environment:
|
||||
- NODE_ENV=development
|
||||
depends_on:
|
||||
- database
|
||||
networks:
|
||||
- immich-network
|
||||
|
||||
immich-microservices:
|
||||
image: immich-microservices:1.9.0
|
||||
build:
|
||||
context: ../server
|
||||
dockerfile: Dockerfile
|
||||
command: npm run start:dev microservices
|
||||
volumes:
|
||||
- ../server:/usr/src/app
|
||||
- ${UPLOAD_LOCATION}:/usr/src/app/upload
|
||||
- /usr/src/app/node_modules
|
||||
env_file:
|
||||
|
||||
@@ -2,11 +2,8 @@ version: "3.8"
|
||||
|
||||
services:
|
||||
immich-server:
|
||||
image: immich-server-staging:latest
|
||||
build:
|
||||
context: ../server
|
||||
dockerfile: Dockerfile
|
||||
entrypoint: ["/bin/sh", "./entrypoint.sh"]
|
||||
image: altran1502/immich-server:staging
|
||||
entrypoint: ["/bin/sh", "./start-server.sh"]
|
||||
expose:
|
||||
- "3000"
|
||||
volumes:
|
||||
@@ -23,10 +20,23 @@ services:
|
||||
restart: always
|
||||
|
||||
immich-microservices:
|
||||
image: immich-microservices-staging:latest
|
||||
build:
|
||||
context: ../microservices
|
||||
dockerfile: Dockerfile
|
||||
image: altran1502/immich-server:staging
|
||||
entrypoint: ["/bin/sh", "./start-microservices.sh"]
|
||||
volumes:
|
||||
- ${UPLOAD_LOCATION}:/usr/src/app/upload
|
||||
env_file:
|
||||
- .env
|
||||
environment:
|
||||
- NODE_ENV=production
|
||||
depends_on:
|
||||
- redis
|
||||
- database
|
||||
networks:
|
||||
- immich-network
|
||||
restart: always
|
||||
|
||||
immich-machine-learning:
|
||||
image: altran1502/immich-machine-learning:staging
|
||||
entrypoint: ["/bin/sh", "./entrypoint.sh"]
|
||||
expose:
|
||||
- "3001"
|
||||
@@ -43,12 +53,8 @@ services:
|
||||
restart: always
|
||||
|
||||
immich-web:
|
||||
image: immich-web-staging:latest
|
||||
image: altran1502/immich-web:staging
|
||||
entrypoint: ["/bin/sh", "./entrypoint.sh"]
|
||||
build:
|
||||
context: ../web
|
||||
dockerfile: Dockerfile
|
||||
target: prod
|
||||
env_file:
|
||||
- .env
|
||||
ports:
|
||||
@@ -57,14 +63,12 @@ services:
|
||||
- immich-network
|
||||
restart: always
|
||||
|
||||
|
||||
redis:
|
||||
container_name: immich_redis
|
||||
image: redis:6.2
|
||||
networks:
|
||||
- immich-network
|
||||
restart: always
|
||||
|
||||
|
||||
database:
|
||||
container_name: immich_postgres
|
||||
@@ -82,6 +86,7 @@ services:
|
||||
- 5432:5432
|
||||
networks:
|
||||
- immich-network
|
||||
restart: always
|
||||
|
||||
nginx:
|
||||
container_name: proxy_nginx
|
||||
@@ -102,4 +107,4 @@ services:
|
||||
networks:
|
||||
immich-network:
|
||||
volumes:
|
||||
pgdata:
|
||||
pgdata:
|
||||
|
||||
@@ -40,7 +40,7 @@ services:
|
||||
POSTGRES_DB: ${DB_DATABASE_NAME}
|
||||
PG_DATA: /var/lib/postgresql/data
|
||||
volumes:
|
||||
- pgdata-test:/var/lib/postgresql/data
|
||||
- /var/lib/postgresql/data
|
||||
ports:
|
||||
- 5432:5432
|
||||
networks:
|
||||
@@ -48,5 +48,3 @@ services:
|
||||
|
||||
networks:
|
||||
immich_network_test:
|
||||
volumes:
|
||||
pgdata-test:
|
||||
|
||||
@@ -3,7 +3,7 @@ version: "3.8"
|
||||
services:
|
||||
immich-server:
|
||||
image: altran1502/immich-server:latest
|
||||
entrypoint: ["/bin/sh", "./entrypoint.sh"]
|
||||
entrypoint: ["/bin/sh", "./start-server.sh"]
|
||||
expose:
|
||||
- "3000"
|
||||
volumes:
|
||||
@@ -20,7 +20,23 @@ services:
|
||||
restart: always
|
||||
|
||||
immich-microservices:
|
||||
image: altran1502/immich-microservices:latest
|
||||
image: altran1502/immich-server:latest
|
||||
entrypoint: ["/bin/sh", "./start-microservices.sh"]
|
||||
volumes:
|
||||
- ${UPLOAD_LOCATION}:/usr/src/app/upload
|
||||
env_file:
|
||||
- .env
|
||||
environment:
|
||||
- NODE_ENV=production
|
||||
depends_on:
|
||||
- redis
|
||||
- database
|
||||
networks:
|
||||
- immich-network
|
||||
restart: always
|
||||
|
||||
immich-machine-learning:
|
||||
image: altran1502/immich-machine-learning:latest
|
||||
entrypoint: ["/bin/sh", "./entrypoint.sh"]
|
||||
expose:
|
||||
- "3001"
|
||||
@@ -47,14 +63,12 @@ services:
|
||||
- immich-network
|
||||
restart: always
|
||||
|
||||
|
||||
redis:
|
||||
container_name: immich_redis
|
||||
image: redis:6.2
|
||||
networks:
|
||||
- immich-network
|
||||
restart: always
|
||||
|
||||
|
||||
database:
|
||||
container_name: immich_postgres
|
||||
@@ -73,7 +87,7 @@ services:
|
||||
networks:
|
||||
- immich-network
|
||||
restart: always
|
||||
|
||||
|
||||
nginx:
|
||||
container_name: proxy_nginx
|
||||
image: nginx:latest
|
||||
@@ -93,4 +107,4 @@ services:
|
||||
networks:
|
||||
immich-network:
|
||||
volumes:
|
||||
pgdata:
|
||||
pgdata:
|
||||
|
||||
@@ -32,4 +32,6 @@ lerna-debug.log*
|
||||
!.vscode/settings.json
|
||||
!.vscode/tasks.json
|
||||
!.vscode/launch.json
|
||||
!.vscode/extensions.json
|
||||
!.vscode/extensions.json
|
||||
|
||||
upload/
|
||||
@@ -7,7 +7,7 @@ export class ImageClassifierController {
|
||||
private readonly imageClassifierService: ImageClassifierService,
|
||||
) { }
|
||||
|
||||
@Post('/tagImage')
|
||||
@Post('/tag-image')
|
||||
async tagImage(@Body('thumbnailPath') thumbnailPath: string) {
|
||||
return await this.imageClassifierService.tagImage(thumbnailPath);
|
||||
}
|
||||
@@ -8,14 +8,14 @@ async function bootstrap() {
|
||||
await app.listen(3001, () => {
|
||||
if (process.env.NODE_ENV == 'development') {
|
||||
Logger.log(
|
||||
'Running Immich Microservices in DEVELOPMENT environment',
|
||||
'Running Immich Machine Learning in DEVELOPMENT environment',
|
||||
'IMMICH MICROSERVICES',
|
||||
);
|
||||
}
|
||||
|
||||
if (process.env.NODE_ENV == 'production') {
|
||||
Logger.log(
|
||||
'Running Immich Microservices in PRODUCTION environment',
|
||||
'Running Immich Machine Learning in PRODUCTION environment',
|
||||
'IMMICH MICROSERVICES',
|
||||
);
|
||||
}
|
||||
@@ -8,7 +8,7 @@ export class ObjectDetectionController {
|
||||
private readonly objectDetectionService: ObjectDetectionService,
|
||||
) { }
|
||||
|
||||
@Post('/detectObject')
|
||||
@Post('/detect-object')
|
||||
async detectObject(@Body('thumbnailPath') thumbnailPath: string) {
|
||||
return await this.objectDetectionService.detectObject(thumbnailPath);
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
devenv/
|
||||
3
machine_learning/.gitignore
vendored
3
machine_learning/.gitignore
vendored
@@ -1,3 +0,0 @@
|
||||
__pycache__/
|
||||
devenv/
|
||||
app/upload
|
||||
@@ -1,25 +0,0 @@
|
||||
## GPU Build
|
||||
# FROM tensorflow/tensorflow:latest-gpu as gpu
|
||||
|
||||
# WORKDIR /code
|
||||
|
||||
# COPY ./requirements.txt /code/requirements.txt
|
||||
|
||||
# RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
|
||||
|
||||
# COPY ./app /code/app
|
||||
|
||||
|
||||
## CPU BUILD
|
||||
FROM python:3.8 as cpu
|
||||
|
||||
RUN apt-get update
|
||||
RUN apt-get install ffmpeg libsm6 libxext6 -y
|
||||
|
||||
WORKDIR /code
|
||||
|
||||
COPY ./requirements.txt /code/requirements.txt
|
||||
|
||||
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
|
||||
|
||||
COPY ./app /code/app
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 193 KiB |
@@ -1,37 +0,0 @@
|
||||
from tensorflow.keras.applications import InceptionV3
|
||||
from tensorflow.keras.applications.inception_v3 import preprocess_input, decode_predictions
|
||||
from tensorflow.keras.preprocessing import image
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
import cv2
|
||||
IMG_SIZE = 299
|
||||
PREDICTION_MODEL = InceptionV3(weights='imagenet')
|
||||
|
||||
|
||||
def classify_image(image_path: str):
|
||||
img_path = f'./app/{image_path}'
|
||||
# img = image.load_img(img_path, target_size=(IMG_SIZE, IMG_SIZE))
|
||||
|
||||
target_image = cv2.imread(img_path, cv2.IMREAD_UNCHANGED)
|
||||
resized_target_image = cv2.resize(target_image, (IMG_SIZE, IMG_SIZE))
|
||||
|
||||
x = image.img_to_array(resized_target_image)
|
||||
x = np.expand_dims(x, axis=0)
|
||||
x = preprocess_input(x)
|
||||
|
||||
preds = PREDICTION_MODEL.predict(x)
|
||||
result = decode_predictions(preds, top=3)[0]
|
||||
payload = []
|
||||
for _, value, _ in result:
|
||||
payload.append(value)
|
||||
|
||||
return payload
|
||||
|
||||
|
||||
def warm_up():
|
||||
img_path = f'./app/test.png'
|
||||
img = image.load_img(img_path, target_size=(IMG_SIZE, IMG_SIZE))
|
||||
x = image.img_to_array(img)
|
||||
x = np.expand_dims(x, axis=0)
|
||||
x = preprocess_input(x)
|
||||
PREDICTION_MODEL.predict(x)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,46 +0,0 @@
|
||||
from pydantic import BaseModel
|
||||
from fastapi import FastAPI
|
||||
|
||||
from .object_detection import object_detection
|
||||
from .image_classifier import image_classifier
|
||||
|
||||
from tf2_yolov4.anchors import YOLOV4_ANCHORS
|
||||
from tf2_yolov4.model import YOLOv4
|
||||
|
||||
|
||||
HEIGHT, WIDTH = (640, 960)
|
||||
|
||||
# Warm up model
|
||||
image_classifier.warm_up()
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
class TagImagePayload(BaseModel):
|
||||
thumbnail_path: str
|
||||
|
||||
|
||||
@app.post("/tagImage")
|
||||
async def post_root(payload: TagImagePayload):
|
||||
image_path = payload.thumbnail_path
|
||||
|
||||
if image_path[0] == '.':
|
||||
image_path = image_path[2:]
|
||||
|
||||
return image_classifier.classify_image(image_path=image_path)
|
||||
|
||||
|
||||
@app.get("/")
|
||||
async def test():
|
||||
|
||||
object_detection.run_detection()
|
||||
# image = tf.io.read_file("./app/cars.jpg")
|
||||
# image = tf.image.decode_image(image)
|
||||
# image = tf.image.resize(image, (HEIGHT, WIDTH))
|
||||
# images = tf.expand_dims(image, axis=0) / 255.0
|
||||
|
||||
# model = YOLOv4(
|
||||
# (HEIGHT, WIDTH, 3),
|
||||
# 80,
|
||||
# YOLOV4_ANCHORS,
|
||||
# "darknet",
|
||||
# )
|
||||
@@ -1,4 +0,0 @@
|
||||
|
||||
|
||||
def run_detection():
|
||||
print("run detection")
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 345 KiB |
@@ -1,8 +0,0 @@
|
||||
opencv-python==4.5.5.64
|
||||
fastapi>=0.68.0,<0.69.0
|
||||
pydantic>=1.8.0,<2.0.0
|
||||
uvicorn>=0.15.0,<0.16.0
|
||||
tensorflow==2.8.0
|
||||
numpy==1.22.2
|
||||
pillow==9.0.1
|
||||
tf2_yolov4==0.1.0
|
||||
@@ -23,4 +23,11 @@
|
||||
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
|
||||
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
|
||||
<uses-permission android:name="android.permission.ACCESS_MEDIA_LOCATION" />
|
||||
|
||||
<queries>
|
||||
<intent>
|
||||
<action android:name="android.intent.action.VIEW" />
|
||||
<data android:scheme="https" />
|
||||
</intent>
|
||||
</queries>
|
||||
</manifest>
|
||||
@@ -0,0 +1,2 @@
|
||||
* Update to Material Design 3
|
||||
* Fixed back button navigation - no longer return back to the home page
|
||||
@@ -0,0 +1 @@
|
||||
* Added announcement pop-up when a new released is pushed out in Github.
|
||||
@@ -0,0 +1,2 @@
|
||||
* Fixed crash issue when upload large file on slow network
|
||||
* Updated album to conform with server refactoring of SharedAlbum to Album
|
||||
@@ -23,6 +23,8 @@ PODS:
|
||||
- Flutter
|
||||
- FMDB (>= 2.7.5)
|
||||
- Toast (4.0.0)
|
||||
- url_launcher_ios (0.0.1):
|
||||
- Flutter
|
||||
- video_player_avfoundation (0.0.1):
|
||||
- Flutter
|
||||
- wakelock (0.0.1):
|
||||
@@ -37,6 +39,7 @@ DEPENDENCIES:
|
||||
- path_provider_ios (from `.symlinks/plugins/path_provider_ios/ios`)
|
||||
- photo_manager (from `.symlinks/plugins/photo_manager/ios`)
|
||||
- sqflite (from `.symlinks/plugins/sqflite/ios`)
|
||||
- url_launcher_ios (from `.symlinks/plugins/url_launcher_ios/ios`)
|
||||
- video_player_avfoundation (from `.symlinks/plugins/video_player_avfoundation/ios`)
|
||||
- wakelock (from `.symlinks/plugins/wakelock/ios`)
|
||||
|
||||
@@ -63,6 +66,8 @@ EXTERNAL SOURCES:
|
||||
:path: ".symlinks/plugins/photo_manager/ios"
|
||||
sqflite:
|
||||
:path: ".symlinks/plugins/sqflite/ios"
|
||||
url_launcher_ios:
|
||||
:path: ".symlinks/plugins/url_launcher_ios/ios"
|
||||
video_player_avfoundation:
|
||||
:path: ".symlinks/plugins/video_player_avfoundation/ios"
|
||||
wakelock:
|
||||
@@ -80,6 +85,7 @@ SPEC CHECKSUMS:
|
||||
SAMKeychain: 483e1c9f32984d50ca961e26818a534283b4cd5c
|
||||
sqflite: 6d358c025f5b867b29ed92fc697fd34924e11904
|
||||
Toast: 91b396c56ee72a5790816f40d3a94dd357abc196
|
||||
url_launcher_ios: 839c58cdb4279282219f5e248c3321761ff3c4de
|
||||
video_player_avfoundation: e489aac24ef5cf7af82702979ed16f2a5ef84cff
|
||||
wakelock: d0fc7c864128eac40eba1617cb5264d9c940b46f
|
||||
|
||||
|
||||
@@ -58,7 +58,7 @@
|
||||
<string>UIInterfaceOrientationPortrait</string>
|
||||
<string>UIInterfaceOrientationLandscapeLeft</string>
|
||||
<string>UIInterfaceOrientationLandscapeRight</string>
|
||||
</array>
|
||||
</array>
|
||||
<key>UISupportedInterfaceOrientations~ipad</key>
|
||||
<array>
|
||||
<string>UIInterfaceOrientationPortrait</string>
|
||||
@@ -76,5 +76,11 @@
|
||||
<false />
|
||||
<key>CADisableMinimumFrameDurationOnPhone</key>
|
||||
<true />
|
||||
|
||||
|
||||
<key>LSApplicationQueriesSchemes</key>
|
||||
<array>
|
||||
<string>https</string>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -19,7 +19,7 @@ platform :ios do
|
||||
desc "iOS Beta"
|
||||
lane :beta do
|
||||
increment_version_number(
|
||||
version_number: "1.10.0"
|
||||
version_number: "1.12.0"
|
||||
)
|
||||
increment_build_number(
|
||||
build_number: latest_testflight_build_number + 1,
|
||||
|
||||
@@ -13,3 +13,7 @@ const String savedLoginInfoKey = "immichSavedLoginInfoKey";
|
||||
// Backup Info
|
||||
const String hiveBackupInfoBox = "immichBackupAlbumInfoBox";
|
||||
const String backupInfoKey = "immichBackupAlbumInfoKey";
|
||||
|
||||
// Github Release Info
|
||||
const String hiveGithubReleaseInfoBox = "immichGithubReleaseInfoBox";
|
||||
const String githubReleaseInfoKey = "immichGithubReleaseInfoKey";
|
||||
|
||||
@@ -5,14 +5,17 @@ import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:immich_mobile/constants/immich_colors.dart';
|
||||
import 'package:immich_mobile/modules/backup/models/hive_backup_albums.model.dart';
|
||||
import 'package:immich_mobile/modules/login/models/hive_saved_login_info.model.dart';
|
||||
import 'package:immich_mobile/modules/login/providers/authentication.provider.dart';
|
||||
import 'package:immich_mobile/shared/providers/asset.provider.dart';
|
||||
import 'package:immich_mobile/routing/router.dart';
|
||||
import 'package:immich_mobile/routing/tab_navigation_observer.dart';
|
||||
import 'package:immich_mobile/shared/providers/app_state.provider.dart';
|
||||
import 'package:immich_mobile/modules/backup/providers/backup.provider.dart';
|
||||
import 'package:immich_mobile/shared/providers/release_info.provider.dart';
|
||||
import 'package:immich_mobile/shared/providers/server_info.provider.dart';
|
||||
import 'package:immich_mobile/shared/providers/websocket.provider.dart';
|
||||
import 'package:immich_mobile/shared/views/immich_loading_overlay.dart';
|
||||
import 'package:immich_mobile/shared/views/version_announcement_overlay.dart';
|
||||
import 'constants/hive_box.dart';
|
||||
|
||||
void main() async {
|
||||
@@ -24,6 +27,7 @@ void main() async {
|
||||
await Hive.openBox(userInfoBox);
|
||||
await Hive.openBox<HiveSavedLoginInfo>(hiveLoginInfoBox);
|
||||
await Hive.openBox<HiveBackupAlbums>(hiveBackupInfoBox);
|
||||
await Hive.openBox(hiveGithubReleaseInfoBox);
|
||||
|
||||
SystemChrome.setSystemUIOverlayStyle(
|
||||
const SystemUiOverlayStyle(
|
||||
@@ -48,10 +52,18 @@ class _ImmichAppState extends ConsumerState<ImmichApp> with WidgetsBindingObserv
|
||||
case AppLifecycleState.resumed:
|
||||
debugPrint("[APP STATE] resumed");
|
||||
ref.watch(appStateProvider.notifier).state = AppStateEnum.resumed;
|
||||
ref.watch(backupProvider.notifier).resumeBackup();
|
||||
|
||||
var isAuthenticated = ref.watch(authenticationProvider).isAuthenticated;
|
||||
|
||||
if (isAuthenticated) {
|
||||
ref.watch(backupProvider.notifier).resumeBackup();
|
||||
ref.watch(assetProvider.notifier).getAllAsset();
|
||||
ref.watch(serverInfoProvider.notifier).getServerVersion();
|
||||
}
|
||||
|
||||
ref.watch(websocketProvider.notifier).connect();
|
||||
ref.watch(assetProvider.notifier).getAllAsset();
|
||||
ref.watch(serverInfoProvider.notifier).getServerVersion();
|
||||
|
||||
ref.watch(releaseInfoProvider.notifier).checkGithubReleaseInfo();
|
||||
|
||||
break;
|
||||
|
||||
@@ -95,6 +107,8 @@ class _ImmichAppState extends ConsumerState<ImmichApp> with WidgetsBindingObserv
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
ref.watch(releaseInfoProvider.notifier).checkGithubReleaseInfo();
|
||||
|
||||
return MaterialApp(
|
||||
debugShowCheckedModeBanner: false,
|
||||
home: Stack(
|
||||
@@ -103,6 +117,7 @@ class _ImmichAppState extends ConsumerState<ImmichApp> with WidgetsBindingObserv
|
||||
title: 'Immich',
|
||||
debugShowCheckedModeBanner: false,
|
||||
theme: ThemeData(
|
||||
useMaterial3: true,
|
||||
brightness: Brightness.light,
|
||||
primarySwatch: Colors.indigo,
|
||||
fontFamily: 'WorkSans',
|
||||
@@ -120,6 +135,7 @@ class _ImmichAppState extends ConsumerState<ImmichApp> with WidgetsBindingObserv
|
||||
routerDelegate: _immichRouter.delegate(navigatorObservers: () => [TabNavigationObserver(ref: ref)]),
|
||||
),
|
||||
const ImmichLoadingOverlay(),
|
||||
const VersionAnnouncementOverlay(),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:cancellation_token_http/http.dart';
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:photo_manager/photo_manager.dart';
|
||||
|
||||
@@ -12,7 +12,7 @@ class BackUpState extends Equatable {
|
||||
final BackUpProgressEnum backupProgress;
|
||||
final List<String> allAssetOnDatabase;
|
||||
final double progressInPercentage;
|
||||
final CancelToken cancelToken;
|
||||
final CancellationToken cancelToken;
|
||||
final ServerInfo serverInfo;
|
||||
|
||||
/// All available albums on the device
|
||||
@@ -43,7 +43,7 @@ class BackUpState extends Equatable {
|
||||
BackUpProgressEnum? backupProgress,
|
||||
List<String>? allAssetOnDatabase,
|
||||
double? progressInPercentage,
|
||||
CancelToken? cancelToken,
|
||||
CancellationToken? cancelToken,
|
||||
ServerInfo? serverInfo,
|
||||
List<AvailableAlbum>? availableAlbums,
|
||||
Set<AssetPathEntity>? selectedBackupAlbums,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'package:cancellation_token_http/http.dart';
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:hive_flutter/hive_flutter.dart';
|
||||
@@ -19,7 +20,7 @@ class BackupNotifier extends StateNotifier<BackUpState> {
|
||||
backupProgress: BackUpProgressEnum.idle,
|
||||
allAssetOnDatabase: const [],
|
||||
progressInPercentage: 0,
|
||||
cancelToken: CancelToken(),
|
||||
cancelToken: CancellationToken(),
|
||||
serverInfo: ServerInfo(
|
||||
diskAvailable: "0",
|
||||
diskAvailableRaw: 0,
|
||||
@@ -266,7 +267,7 @@ class BackupNotifier extends StateNotifier<BackUpState> {
|
||||
}
|
||||
|
||||
// Perform Backup
|
||||
state = state.copyWith(cancelToken: CancelToken());
|
||||
state = state.copyWith(cancelToken: CancellationToken());
|
||||
_backupService.backupAsset(assetsWillBeBackup, state.cancelToken, _onAssetUploaded, _onUploadProgress);
|
||||
} else {
|
||||
PhotoManager.openSetting();
|
||||
@@ -274,7 +275,7 @@ class BackupNotifier extends StateNotifier<BackUpState> {
|
||||
}
|
||||
|
||||
void cancelBackup() {
|
||||
state.cancelToken.cancel('Cancel Backup');
|
||||
state.cancelToken.cancel();
|
||||
state = state.copyWith(backupProgress: BackUpProgressEnum.idle, progressInPercentage: 0.0);
|
||||
}
|
||||
|
||||
|
||||
@@ -8,11 +8,11 @@ import 'package:hive/hive.dart';
|
||||
import 'package:immich_mobile/constants/hive_box.dart';
|
||||
import 'package:immich_mobile/shared/services/network.service.dart';
|
||||
import 'package:immich_mobile/shared/models/device_info.model.dart';
|
||||
import 'package:immich_mobile/utils/dio_http_interceptor.dart';
|
||||
import 'package:immich_mobile/utils/files_helper.dart';
|
||||
import 'package:photo_manager/photo_manager.dart';
|
||||
import 'package:http_parser/http_parser.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
import 'package:cancellation_token_http/http.dart' as http;
|
||||
|
||||
class BackupService {
|
||||
final NetworkService _networkService = NetworkService();
|
||||
@@ -26,17 +26,13 @@ class BackupService {
|
||||
return result.cast<String>();
|
||||
}
|
||||
|
||||
backupAsset(Set<AssetEntity> assetList, CancelToken cancelToken, Function(String, String) singleAssetDoneCb,
|
||||
Function(int, int) uploadProgress) async {
|
||||
var dio = Dio();
|
||||
dio.interceptors.add(AuthenticatedRequestInterceptor());
|
||||
|
||||
backupAsset(Set<AssetEntity> assetList, http.CancellationToken cancelToken,
|
||||
Function(String, String) singleAssetDoneCb, Function(int, int) uploadProgress) async {
|
||||
String deviceId = Hive.box(userInfoBox).get(deviceIdKey);
|
||||
String savedEndpoint = Hive.box(userInfoBox).get(serverEndpointKey);
|
||||
File? file;
|
||||
|
||||
MultipartFile assetRawUploadData;
|
||||
MultipartFile thumbnailUploadData;
|
||||
http.MultipartFile? thumbnailUploadData;
|
||||
|
||||
for (var entity in assetList) {
|
||||
try {
|
||||
@@ -47,35 +43,27 @@ class BackupService {
|
||||
}
|
||||
|
||||
if (file != null) {
|
||||
FormData formData;
|
||||
String originalFileName = await entity.titleAsync;
|
||||
String fileNameWithoutPath = originalFileName.toString().split(".")[0];
|
||||
var fileExtension = p.extension(file.path);
|
||||
var mimeType = FileHelper.getMimeType(file.path);
|
||||
assetRawUploadData = await MultipartFile.fromFile(
|
||||
file.path,
|
||||
var fileStream = file.openRead();
|
||||
var assetRawUploadData = http.MultipartFile(
|
||||
"assetData",
|
||||
fileStream,
|
||||
file.lengthSync(),
|
||||
filename: fileNameWithoutPath,
|
||||
contentType: MediaType(
|
||||
mimeType["type"],
|
||||
mimeType["subType"],
|
||||
),
|
||||
);
|
||||
formData = FormData.fromMap({
|
||||
'deviceAssetId': entity.id,
|
||||
'deviceId': deviceId,
|
||||
'assetType': _getAssetType(entity.type),
|
||||
'createdAt': entity.createDateTime.toIso8601String(),
|
||||
'modifiedAt': entity.modifiedDateTime.toIso8601String(),
|
||||
'isFavorite': entity.isFavorite,
|
||||
'fileExtension': fileExtension,
|
||||
'duration': entity.videoDuration,
|
||||
'assetData': [assetRawUploadData]
|
||||
});
|
||||
|
||||
// Build thumbnail multipart data
|
||||
var thumbnailData = await entity.thumbnailDataWithSize(const ThumbnailSize(1440, 2560));
|
||||
if (thumbnailData != null) {
|
||||
thumbnailUploadData = MultipartFile.fromBytes(
|
||||
thumbnailUploadData = http.MultipartFile.fromBytes(
|
||||
"thumbnailData",
|
||||
List.from(thumbnailData),
|
||||
filename: fileNameWithoutPath,
|
||||
contentType: MediaType(
|
||||
@@ -83,39 +71,37 @@ class BackupService {
|
||||
"jpeg",
|
||||
),
|
||||
);
|
||||
|
||||
// Send thumbnail data if it is exist
|
||||
formData = FormData.fromMap({
|
||||
'deviceAssetId': entity.id,
|
||||
'deviceId': deviceId,
|
||||
'assetType': _getAssetType(entity.type),
|
||||
'createdAt': entity.createDateTime.toIso8601String(),
|
||||
'modifiedAt': entity.modifiedDateTime.toIso8601String(),
|
||||
'isFavorite': entity.isFavorite,
|
||||
'fileExtension': fileExtension,
|
||||
'duration': entity.videoDuration,
|
||||
'thumbnailData': [thumbnailUploadData],
|
||||
'assetData': [assetRawUploadData]
|
||||
});
|
||||
}
|
||||
|
||||
Response res = await dio.post(
|
||||
'$savedEndpoint/asset/upload',
|
||||
data: formData,
|
||||
cancelToken: cancelToken,
|
||||
onSendProgress: (sent, total) => uploadProgress(sent, total),
|
||||
);
|
||||
var box = Hive.box(userInfoBox);
|
||||
|
||||
var req = MultipartRequest('POST', Uri.parse('$savedEndpoint/asset/upload'),
|
||||
onProgress: ((bytes, totalBytes) => uploadProgress(bytes, totalBytes)));
|
||||
req.headers["Authorization"] = "Bearer ${box.get(accessTokenKey)}";
|
||||
|
||||
req.fields['deviceAssetId'] = entity.id;
|
||||
req.fields['deviceId'] = deviceId;
|
||||
req.fields['assetType'] = _getAssetType(entity.type);
|
||||
req.fields['createdAt'] = entity.createDateTime.toIso8601String();
|
||||
req.fields['modifiedAt'] = entity.modifiedDateTime.toIso8601String();
|
||||
req.fields['isFavorite'] = entity.isFavorite.toString();
|
||||
req.fields['fileExtension'] = fileExtension;
|
||||
req.fields['duration'] = entity.videoDuration.toString();
|
||||
|
||||
if (thumbnailUploadData != null) {
|
||||
req.files.add(thumbnailUploadData);
|
||||
}
|
||||
req.files.add(assetRawUploadData);
|
||||
|
||||
var res = await req.send(cancellationToken: cancelToken);
|
||||
|
||||
if (res.statusCode == 201) {
|
||||
singleAssetDoneCb(entity.id, deviceId);
|
||||
}
|
||||
}
|
||||
} on DioError catch (e) {
|
||||
debugPrint("DioError backupAsset: ${e.response}");
|
||||
if (e.type == DioErrorType.cancel || e.type == DioErrorType.other) {
|
||||
return;
|
||||
}
|
||||
continue;
|
||||
} on http.CancelledException {
|
||||
debugPrint("Backup was cancelled by the user");
|
||||
return;
|
||||
} catch (e) {
|
||||
debugPrint("ERROR backupAsset: ${e.toString()}");
|
||||
continue;
|
||||
@@ -150,3 +136,35 @@ class BackupService {
|
||||
return DeviceInfoRemote.fromJson(res.toString());
|
||||
}
|
||||
}
|
||||
|
||||
class MultipartRequest extends http.MultipartRequest {
|
||||
/// Creates a new [MultipartRequest].
|
||||
MultipartRequest(
|
||||
String method,
|
||||
Uri url, {
|
||||
required this.onProgress,
|
||||
}) : super(method, url);
|
||||
|
||||
final void Function(int bytes, int totalBytes) onProgress;
|
||||
|
||||
/// Freezes all mutable fields and returns a
|
||||
/// single-subscription [http.ByteStream]
|
||||
/// that will emit the request body.
|
||||
@override
|
||||
http.ByteStream finalize() {
|
||||
final byteStream = super.finalize();
|
||||
|
||||
final total = contentLength;
|
||||
var bytes = 0;
|
||||
|
||||
final t = StreamTransformer.fromHandlers(
|
||||
handleData: (List<int> data, EventSink<List<int>> sink) {
|
||||
bytes += data.length;
|
||||
onProgress.call(bytes, total);
|
||||
sink.add(data);
|
||||
},
|
||||
);
|
||||
final stream = byteStream.transform(t);
|
||||
return http.ByteStream(stream);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -96,6 +96,12 @@ class BackupControllerPage extends HookConsumerWidget {
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 8.0),
|
||||
child: OutlinedButton(
|
||||
style: OutlinedButton.styleFrom(
|
||||
side: const BorderSide(
|
||||
width: 1,
|
||||
color: Color.fromARGB(255, 220, 220, 220),
|
||||
),
|
||||
),
|
||||
onPressed: () {
|
||||
isAutoBackup
|
||||
? ref.watch(authenticationProvider.notifier).setAutoBackup(false)
|
||||
@@ -191,6 +197,13 @@ class BackupControllerPage extends HookConsumerWidget {
|
||||
),
|
||||
),
|
||||
trailing: OutlinedButton(
|
||||
style: OutlinedButton.styleFrom(
|
||||
enableFeedback: true,
|
||||
side: const BorderSide(
|
||||
width: 1,
|
||||
color: Color.fromARGB(255, 220, 220, 220),
|
||||
),
|
||||
),
|
||||
onPressed: () {
|
||||
AutoRouter.of(context).push(const BackupAlbumSelectionRoute());
|
||||
},
|
||||
@@ -278,13 +291,20 @@ class BackupControllerPage extends HookConsumerWidget {
|
||||
child: Container(
|
||||
child: backupState.backupProgress == BackUpProgressEnum.inProgress
|
||||
? ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(primary: Colors.red[300]),
|
||||
style: ElevatedButton.styleFrom(
|
||||
primary: Colors.red[300],
|
||||
onPrimary: Colors.grey[50],
|
||||
),
|
||||
onPressed: () {
|
||||
ref.read(backupProvider.notifier).cancelBackup();
|
||||
},
|
||||
child: const Text("Cancel"),
|
||||
)
|
||||
: ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(
|
||||
primary: Theme.of(context).primaryColor,
|
||||
onPrimary: Colors.grey[50],
|
||||
),
|
||||
onPressed: shouldBackup
|
||||
? () {
|
||||
ref.read(backupProvider.notifier).startBackupProcess();
|
||||
|
||||
@@ -109,7 +109,7 @@ class ImmichSliverAppBar extends ConsumerWidget {
|
||||
? const Icon(Icons.backup_rounded)
|
||||
: Badge(
|
||||
padding: const EdgeInsets.all(4),
|
||||
elevation: 1,
|
||||
elevation: 2,
|
||||
position: BadgePosition.bottomEnd(bottom: -4, end: -4),
|
||||
badgeColor: Colors.white,
|
||||
badgeContent: const Icon(
|
||||
@@ -117,7 +117,6 @@ class ImmichSliverAppBar extends ConsumerWidget {
|
||||
size: 8,
|
||||
),
|
||||
child: const Icon(Icons.backup_rounded)),
|
||||
tooltip: 'Backup Controller',
|
||||
onPressed: () async {
|
||||
var onPop = await AutoRouter.of(context).push(const BackupControllerRoute());
|
||||
|
||||
|
||||
@@ -153,7 +153,6 @@ class ProfileDrawer extends HookConsumerWidget {
|
||||
),
|
||||
],
|
||||
),
|
||||
const Padding(padding: EdgeInsets.all(8)),
|
||||
Text(
|
||||
"${_authState.firstName} ${_authState.lastName}",
|
||||
style: TextStyle(
|
||||
@@ -162,12 +161,9 @@ class ProfileDrawer extends HookConsumerWidget {
|
||||
fontSize: 24,
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 4.0),
|
||||
child: Text(
|
||||
_authState.userEmail,
|
||||
style: TextStyle(color: Colors.grey[800], fontSize: 12),
|
||||
),
|
||||
Text(
|
||||
_authState.userEmail,
|
||||
style: TextStyle(color: Colors.grey[800], fontSize: 12),
|
||||
)
|
||||
],
|
||||
),
|
||||
|
||||
@@ -96,12 +96,20 @@ class ServerEndpointInput extends StatelessWidget {
|
||||
|
||||
const ServerEndpointInput({Key? key, required this.controller}) : super(key: key);
|
||||
|
||||
String? _validateInput(String? url) {
|
||||
if (url == null) return null;
|
||||
if (!url.startsWith(RegExp(r'https?://'))) return 'Please specify http:// or https://';
|
||||
return null;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return TextFormField(
|
||||
controller: controller,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Server Endpoint URL', border: OutlineInputBorder(), hintText: 'http://your-server-ip:port'),
|
||||
validator: _validateInput,
|
||||
autovalidateMode: AutovalidateMode.always,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -111,12 +119,22 @@ class EmailInput extends StatelessWidget {
|
||||
|
||||
const EmailInput({Key? key, required this.controller}) : super(key: key);
|
||||
|
||||
String? _validateInput(String? email) {
|
||||
if (email == null || email == '') return null;
|
||||
if (email.endsWith(' ')) return 'Trailing whitespace';
|
||||
if (email.startsWith(' ')) return 'Leading whitespace';
|
||||
if (email.contains(' ') || !email.contains('@')) return 'Invalid Email';
|
||||
return null;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return TextFormField(
|
||||
controller: controller,
|
||||
decoration:
|
||||
const InputDecoration(labelText: 'Email', border: OutlineInputBorder(), hintText: 'youremail@email.com'),
|
||||
validator: _validateInput,
|
||||
autovalidateMode: AutovalidateMode.always,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -153,9 +171,12 @@ class LoginButton extends ConsumerWidget {
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
return ElevatedButton(
|
||||
style: ButtonStyle(
|
||||
style: ElevatedButton.styleFrom(
|
||||
visualDensity: VisualDensity.standard,
|
||||
padding: MaterialStateProperty.all<EdgeInsets>(const EdgeInsets.symmetric(vertical: 10, horizontal: 25)),
|
||||
primary: Theme.of(context).primaryColor,
|
||||
onPrimary: Colors.grey[50],
|
||||
elevation: 2,
|
||||
padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 25),
|
||||
),
|
||||
onPressed: () async {
|
||||
// This will remove current cache asset state of previous user login.
|
||||
|
||||
@@ -79,14 +79,14 @@ class SearchResultPage extends HookConsumerWidget {
|
||||
return Chip(
|
||||
label: Wrap(
|
||||
spacing: 5,
|
||||
runAlignment: WrapAlignment.center,
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
alignment: WrapAlignment.center,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 2.0),
|
||||
child: Text(
|
||||
currentSearchTerm.value,
|
||||
style: TextStyle(color: Theme.of(context).primaryColor),
|
||||
maxLines: 1,
|
||||
),
|
||||
Text(
|
||||
currentSearchTerm.value,
|
||||
style: TextStyle(color: Theme.of(context).primaryColor, fontSize: 13, fontWeight: FontWeight.bold),
|
||||
maxLines: 1,
|
||||
),
|
||||
Icon(
|
||||
Icons.close_rounded,
|
||||
|
||||
@@ -2,8 +2,8 @@ import 'dart:convert';
|
||||
|
||||
import 'package:collection/collection.dart';
|
||||
|
||||
import 'package:immich_mobile/modules/sharing/models/shared_asset.model.dart';
|
||||
import 'package:immich_mobile/modules/sharing/models/shared_user.model.dart';
|
||||
import 'package:immich_mobile/shared/models/immich_asset.model.dart';
|
||||
import 'package:immich_mobile/shared/models/user.model.dart';
|
||||
|
||||
class SharedAlbum {
|
||||
final String id;
|
||||
@@ -11,8 +11,8 @@ class SharedAlbum {
|
||||
final String albumName;
|
||||
final String createdAt;
|
||||
final String? albumThumbnailAssetId;
|
||||
final List<SharedUsers> sharedUsers;
|
||||
final List<SharedAssets>? sharedAssets;
|
||||
final List<User> sharedUsers;
|
||||
final List<ImmichAsset>? assets;
|
||||
|
||||
SharedAlbum({
|
||||
required this.id,
|
||||
@@ -21,7 +21,7 @@ class SharedAlbum {
|
||||
required this.createdAt,
|
||||
required this.albumThumbnailAssetId,
|
||||
required this.sharedUsers,
|
||||
this.sharedAssets,
|
||||
this.assets,
|
||||
});
|
||||
|
||||
SharedAlbum copyWith({
|
||||
@@ -30,8 +30,8 @@ class SharedAlbum {
|
||||
String? albumName,
|
||||
String? createdAt,
|
||||
String? albumThumbnailAssetId,
|
||||
List<SharedUsers>? sharedUsers,
|
||||
List<SharedAssets>? sharedAssets,
|
||||
List<User>? sharedUsers,
|
||||
List<ImmichAsset>? assets,
|
||||
}) {
|
||||
return SharedAlbum(
|
||||
id: id ?? this.id,
|
||||
@@ -40,7 +40,7 @@ class SharedAlbum {
|
||||
createdAt: createdAt ?? this.createdAt,
|
||||
albumThumbnailAssetId: albumThumbnailAssetId ?? this.albumThumbnailAssetId,
|
||||
sharedUsers: sharedUsers ?? this.sharedUsers,
|
||||
sharedAssets: sharedAssets ?? this.sharedAssets,
|
||||
assets: assets ?? this.assets,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -55,8 +55,8 @@ class SharedAlbum {
|
||||
result.addAll({'albumThumbnailAssetId': albumThumbnailAssetId});
|
||||
}
|
||||
result.addAll({'sharedUsers': sharedUsers.map((x) => x.toMap()).toList()});
|
||||
if (sharedAssets != null) {
|
||||
result.addAll({'sharedAssets': sharedAssets!.map((x) => x.toMap()).toList()});
|
||||
if (assets != null) {
|
||||
result.addAll({'assets': assets!.map((x) => x.toMap()).toList()});
|
||||
}
|
||||
|
||||
return result;
|
||||
@@ -69,9 +69,9 @@ class SharedAlbum {
|
||||
albumName: map['albumName'] ?? '',
|
||||
createdAt: map['createdAt'] ?? '',
|
||||
albumThumbnailAssetId: map['albumThumbnailAssetId'],
|
||||
sharedUsers: List<SharedUsers>.from(map['sharedUsers']?.map((x) => SharedUsers.fromMap(x))),
|
||||
sharedAssets: map['sharedAssets'] != null
|
||||
? List<SharedAssets>.from(map['sharedAssets']?.map((x) => SharedAssets.fromMap(x)))
|
||||
sharedUsers: List<User>.from(map['sharedUsers']?.map((x) => User.fromMap(x))),
|
||||
assets: map['assets'] != null
|
||||
? List<ImmichAsset>.from(map['assets']?.map((x) => ImmichAsset.fromMap(x)))
|
||||
: null,
|
||||
);
|
||||
}
|
||||
@@ -82,7 +82,7 @@ class SharedAlbum {
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'SharedAlbum(id: $id, ownerId: $ownerId, albumName: $albumName, createdAt: $createdAt, albumThumbnailAssetId: $albumThumbnailAssetId, sharedUsers: $sharedUsers, sharedAssets: $sharedAssets)';
|
||||
return 'SharedAlbum(id: $id, ownerId: $ownerId, albumName: $albumName, createdAt: $createdAt, albumThumbnailAssetId: $albumThumbnailAssetId, sharedUsers: $sharedUsers, assets: $assets)';
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -97,7 +97,7 @@ class SharedAlbum {
|
||||
other.createdAt == createdAt &&
|
||||
other.albumThumbnailAssetId == albumThumbnailAssetId &&
|
||||
listEquals(other.sharedUsers, sharedUsers) &&
|
||||
listEquals(other.sharedAssets, sharedAssets);
|
||||
listEquals(other.assets, assets);
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -108,6 +108,6 @@ class SharedAlbum {
|
||||
createdAt.hashCode ^
|
||||
albumThumbnailAssetId.hashCode ^
|
||||
sharedUsers.hashCode ^
|
||||
sharedAssets.hashCode;
|
||||
assets.hashCode;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:immich_mobile/shared/models/immich_asset.model.dart';
|
||||
|
||||
class SharedAssets {
|
||||
final ImmichAsset assetInfo;
|
||||
|
||||
SharedAssets({
|
||||
required this.assetInfo,
|
||||
});
|
||||
|
||||
SharedAssets copyWith({
|
||||
ImmichAsset? assetInfo,
|
||||
}) {
|
||||
return SharedAssets(
|
||||
assetInfo: assetInfo ?? this.assetInfo,
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toMap() {
|
||||
final result = <String, dynamic>{};
|
||||
|
||||
result.addAll({'assetInfo': assetInfo.toMap()});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
factory SharedAssets.fromMap(Map<String, dynamic> map) {
|
||||
return SharedAssets(
|
||||
assetInfo: ImmichAsset.fromMap(map['assetInfo']),
|
||||
);
|
||||
}
|
||||
|
||||
String toJson() => json.encode(toMap());
|
||||
|
||||
factory SharedAssets.fromJson(String source) => SharedAssets.fromMap(json.decode(source));
|
||||
|
||||
@override
|
||||
String toString() => 'SharedAssets(assetInfo: $assetInfo)';
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
if (identical(this, other)) return true;
|
||||
|
||||
return other is SharedAssets && other.assetInfo == assetInfo;
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode => assetInfo.hashCode;
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:immich_mobile/shared/models/user_info.model.dart';
|
||||
|
||||
class SharedUsers {
|
||||
final int id;
|
||||
final String albumId;
|
||||
final String sharedUserId;
|
||||
final UserInfo userInfo;
|
||||
|
||||
SharedUsers({
|
||||
required this.id,
|
||||
required this.albumId,
|
||||
required this.sharedUserId,
|
||||
required this.userInfo,
|
||||
});
|
||||
|
||||
SharedUsers copyWith({
|
||||
int? id,
|
||||
String? albumId,
|
||||
String? sharedUserId,
|
||||
UserInfo? userInfo,
|
||||
}) {
|
||||
return SharedUsers(
|
||||
id: id ?? this.id,
|
||||
albumId: albumId ?? this.albumId,
|
||||
sharedUserId: sharedUserId ?? this.sharedUserId,
|
||||
userInfo: userInfo ?? this.userInfo,
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toMap() {
|
||||
final result = <String, dynamic>{};
|
||||
|
||||
result.addAll({'id': id});
|
||||
result.addAll({'albumId': albumId});
|
||||
result.addAll({'sharedUserId': sharedUserId});
|
||||
result.addAll({'userInfo': userInfo.toMap()});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
factory SharedUsers.fromMap(Map<String, dynamic> map) {
|
||||
return SharedUsers(
|
||||
id: map['id']?.toInt() ?? 0,
|
||||
albumId: map['albumId'] ?? '',
|
||||
sharedUserId: map['sharedUserId'] ?? '',
|
||||
userInfo: UserInfo.fromMap(map['userInfo']),
|
||||
);
|
||||
}
|
||||
|
||||
String toJson() => json.encode(toMap());
|
||||
|
||||
factory SharedUsers.fromJson(String source) => SharedUsers.fromMap(json.decode(source));
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'SharedUsers(id: $id, albumId: $albumId, sharedUserId: $sharedUserId, userInfo: $userInfo)';
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
if (identical(this, other)) return true;
|
||||
|
||||
return other is SharedUsers &&
|
||||
other.id == id &&
|
||||
other.albumId == albumId &&
|
||||
other.sharedUserId == sharedUserId &&
|
||||
other.userInfo == userInfo;
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return id.hashCode ^ albumId.hashCode ^ sharedUserId.hashCode ^ userInfo.hashCode;
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:immich_mobile/shared/models/user_info.model.dart';
|
||||
import 'package:immich_mobile/shared/models/user.model.dart';
|
||||
import 'package:immich_mobile/shared/services/user.service.dart';
|
||||
|
||||
final suggestedSharedUsersProvider = FutureProvider.autoDispose<List<UserInfo>>((ref) async {
|
||||
final suggestedSharedUsersProvider = FutureProvider.autoDispose<List<User>>((ref) async {
|
||||
UserService userService = UserService();
|
||||
|
||||
return await userService.getAllUsersInfo();
|
||||
|
||||
@@ -12,9 +12,10 @@ class SharedAlbumService {
|
||||
|
||||
Future<List<SharedAlbum>> getAllSharedAlbum() async {
|
||||
try {
|
||||
var res = await _networkService.getRequest(url: 'shared/allSharedAlbums');
|
||||
var res = await _networkService.getRequest(url: 'album?shared=true');
|
||||
List<dynamic> decodedData = jsonDecode(res.toString());
|
||||
List<SharedAlbum> result = List.from(decodedData.map((e) => SharedAlbum.fromMap(e)));
|
||||
List<SharedAlbum> result =
|
||||
List.from(decodedData.map((e) => SharedAlbum.fromMap(e)));
|
||||
|
||||
return result;
|
||||
} catch (e) {
|
||||
@@ -24,9 +25,10 @@ class SharedAlbumService {
|
||||
return [];
|
||||
}
|
||||
|
||||
Future<bool> createSharedAlbum(String albumName, Set<ImmichAsset> assets, List<String> sharedUserIds) async {
|
||||
Future<bool> createSharedAlbum(String albumName, Set<ImmichAsset> assets,
|
||||
List<String> sharedUserIds) async {
|
||||
try {
|
||||
var res = await _networkService.postRequest(url: 'shared/createAlbum', data: {
|
||||
var res = await _networkService.postRequest(url: 'album', data: {
|
||||
"albumName": albumName,
|
||||
"sharedWithUserIds": sharedUserIds,
|
||||
"assetIds": assets.map((asset) => asset.id).toList(),
|
||||
@@ -45,7 +47,7 @@ class SharedAlbumService {
|
||||
|
||||
Future<SharedAlbum> getAlbumDetail(String albumId) async {
|
||||
try {
|
||||
var res = await _networkService.getRequest(url: 'shared/$albumId');
|
||||
var res = await _networkService.getRequest(url: 'album/$albumId');
|
||||
dynamic decodedData = jsonDecode(res.toString());
|
||||
SharedAlbum result = SharedAlbum.fromMap(decodedData);
|
||||
|
||||
@@ -55,9 +57,11 @@ class SharedAlbumService {
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool> addAdditionalAssetToAlbum(Set<ImmichAsset> assets, String albumId) async {
|
||||
Future<bool> addAdditionalAssetToAlbum(
|
||||
Set<ImmichAsset> assets, String albumId) async {
|
||||
try {
|
||||
var res = await _networkService.postRequest(url: 'shared/addAssets', data: {
|
||||
var res =
|
||||
await _networkService.putRequest(url: 'album/$albumId/assets', data: {
|
||||
"albumId": albumId,
|
||||
"assetIds": assets.map((asset) => asset.id).toList(),
|
||||
});
|
||||
@@ -73,10 +77,11 @@ class SharedAlbumService {
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool> addAdditionalUserToAlbum(List<String> sharedUserIds, String albumId) async {
|
||||
Future<bool> addAdditionalUserToAlbum(
|
||||
List<String> sharedUserIds, String albumId) async {
|
||||
try {
|
||||
var res = await _networkService.postRequest(url: 'shared/addUsers', data: {
|
||||
"albumId": albumId,
|
||||
var res =
|
||||
await _networkService.putRequest(url: 'album/$albumId/users', data: {
|
||||
"sharedUserIds": sharedUserIds,
|
||||
});
|
||||
|
||||
@@ -93,7 +98,7 @@ class SharedAlbumService {
|
||||
|
||||
Future<bool> deleteAlbum(String albumId) async {
|
||||
try {
|
||||
Response res = await _networkService.deleteRequest(url: 'shared/$albumId');
|
||||
Response res = await _networkService.deleteRequest(url: 'album/$albumId');
|
||||
|
||||
if (res.statusCode != 200) {
|
||||
return false;
|
||||
@@ -108,7 +113,8 @@ class SharedAlbumService {
|
||||
|
||||
Future<bool> leaveAlbum(String albumId) async {
|
||||
try {
|
||||
Response res = await _networkService.deleteRequest(url: 'shared/leaveAlbum/$albumId');
|
||||
Response res =
|
||||
await _networkService.deleteRequest(url: 'album/$albumId/user/me');
|
||||
|
||||
if (res.statusCode != 200) {
|
||||
return false;
|
||||
@@ -121,10 +127,11 @@ class SharedAlbumService {
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool> removeAssetFromAlbum(String albumId, List<String> assetIds) async {
|
||||
Future<bool> removeAssetFromAlbum(
|
||||
String albumId, List<String> assetIds) async {
|
||||
try {
|
||||
Response res = await _networkService.deleteRequest(url: 'shared/removeAssets/', data: {
|
||||
"albumId": albumId,
|
||||
Response res = await _networkService
|
||||
.deleteRequest(url: 'album/$albumId/assets', data: {
|
||||
"assetIds": assetIds,
|
||||
});
|
||||
|
||||
@@ -139,10 +146,11 @@ class SharedAlbumService {
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool> changeTitleAlbum(String albumId, String ownerId, String newAlbumTitle) async {
|
||||
Future<bool> changeTitleAlbum(
|
||||
String albumId, String ownerId, String newAlbumTitle) async {
|
||||
try {
|
||||
Response res = await _networkService.patchRequest(url: 'shared/updateInfo', data: {
|
||||
"albumId": albumId,
|
||||
Response res =
|
||||
await _networkService.patchRequest(url: 'album/$albumId/', data: {
|
||||
"ownerId": ownerId,
|
||||
"albumName": newAlbumTitle,
|
||||
});
|
||||
|
||||
@@ -13,15 +13,14 @@ class AlbumActionOutlinedButton extends StatelessWidget {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(right: 8.0),
|
||||
child: OutlinedButton.icon(
|
||||
style: ButtonStyle(
|
||||
padding: MaterialStateProperty.all<EdgeInsets>(const EdgeInsets.symmetric(vertical: 0, horizontal: 10)),
|
||||
shape: MaterialStateProperty.resolveWith<OutlinedBorder>(
|
||||
(_) => RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(25),
|
||||
),
|
||||
style: OutlinedButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(vertical: 0, horizontal: 10),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(25),
|
||||
),
|
||||
side: MaterialStateProperty.resolveWith<BorderSide>(
|
||||
(_) => const BorderSide(width: 1, color: Color.fromARGB(255, 158, 158, 158)),
|
||||
side: const BorderSide(
|
||||
width: 1,
|
||||
color: Color.fromARGB(255, 215, 215, 215),
|
||||
),
|
||||
),
|
||||
icon: Icon(iconData, size: 15),
|
||||
|
||||
@@ -86,63 +86,60 @@ class SelectionThumbnailImage extends HookConsumerWidget {
|
||||
}
|
||||
}
|
||||
},
|
||||
child: Hero(
|
||||
tag: asset.id,
|
||||
child: Stack(
|
||||
children: [
|
||||
Container(
|
||||
decoration: BoxDecoration(border: drawBorderColor()),
|
||||
child: CachedNetworkImage(
|
||||
cacheKey: "${asset.id}-${cacheKey.value}",
|
||||
width: 150,
|
||||
height: 150,
|
||||
memCacheHeight: asset.type == 'IMAGE' ? 150 : 150,
|
||||
fit: BoxFit.cover,
|
||||
imageUrl: thumbnailRequestUrl,
|
||||
httpHeaders: {"Authorization": "Bearer ${box.get(accessTokenKey)}"},
|
||||
fadeInDuration: const Duration(milliseconds: 250),
|
||||
progressIndicatorBuilder: (context, url, downloadProgress) => Transform.scale(
|
||||
scale: 0.2,
|
||||
child: CircularProgressIndicator(value: downloadProgress.progress),
|
||||
),
|
||||
errorWidget: (context, url, error) {
|
||||
return Icon(
|
||||
Icons.image_not_supported_outlined,
|
||||
color: Theme.of(context).primaryColor,
|
||||
);
|
||||
},
|
||||
child: Stack(
|
||||
children: [
|
||||
Container(
|
||||
decoration: BoxDecoration(border: drawBorderColor()),
|
||||
child: CachedNetworkImage(
|
||||
cacheKey: "${asset.id}-${cacheKey.value}",
|
||||
width: 150,
|
||||
height: 150,
|
||||
memCacheHeight: asset.type == 'IMAGE' ? 150 : 150,
|
||||
fit: BoxFit.cover,
|
||||
imageUrl: thumbnailRequestUrl,
|
||||
httpHeaders: {"Authorization": "Bearer ${box.get(accessTokenKey)}"},
|
||||
fadeInDuration: const Duration(milliseconds: 250),
|
||||
progressIndicatorBuilder: (context, url, downloadProgress) => Transform.scale(
|
||||
scale: 0.2,
|
||||
child: CircularProgressIndicator(value: downloadProgress.progress),
|
||||
),
|
||||
errorWidget: (context, url, error) {
|
||||
return Icon(
|
||||
Icons.image_not_supported_outlined,
|
||||
color: Theme.of(context).primaryColor,
|
||||
);
|
||||
},
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(3.0),
|
||||
child: Align(
|
||||
alignment: Alignment.topLeft,
|
||||
child: _buildSelectionIcon(asset),
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(3.0),
|
||||
child: Align(
|
||||
alignment: Alignment.topLeft,
|
||||
child: _buildSelectionIcon(asset),
|
||||
),
|
||||
asset.type == 'IMAGE'
|
||||
? Container()
|
||||
: Positioned(
|
||||
bottom: 5,
|
||||
right: 5,
|
||||
child: Row(
|
||||
children: [
|
||||
Text(
|
||||
asset.duration.toString().substring(0, 7),
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 10,
|
||||
),
|
||||
),
|
||||
const Icon(
|
||||
Icons.play_circle_outline_rounded,
|
||||
),
|
||||
asset.type == 'IMAGE'
|
||||
? Container()
|
||||
: Positioned(
|
||||
bottom: 5,
|
||||
right: 5,
|
||||
child: Row(
|
||||
children: [
|
||||
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,
|
||||
),
|
||||
],
|
||||
),
|
||||
)
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -23,32 +23,29 @@ class SharedAlbumThumbnailImage extends HookConsumerWidget {
|
||||
onTap: () {
|
||||
// debugPrint("View ${asset.id}");
|
||||
},
|
||||
child: Hero(
|
||||
tag: asset.id,
|
||||
child: Stack(
|
||||
children: [
|
||||
CachedNetworkImage(
|
||||
cacheKey: "${asset.id}-${cacheKey.value}",
|
||||
width: 500,
|
||||
height: 500,
|
||||
memCacheHeight: asset.type == 'IMAGE' ? 500 : 500,
|
||||
fit: BoxFit.cover,
|
||||
imageUrl: thumbnailRequestUrl,
|
||||
httpHeaders: {"Authorization": "Bearer ${box.get(accessTokenKey)}"},
|
||||
fadeInDuration: const Duration(milliseconds: 250),
|
||||
progressIndicatorBuilder: (context, url, downloadProgress) => Transform.scale(
|
||||
scale: 0.2,
|
||||
child: CircularProgressIndicator(value: downloadProgress.progress),
|
||||
),
|
||||
errorWidget: (context, url, error) {
|
||||
return Icon(
|
||||
Icons.image_not_supported_outlined,
|
||||
color: Theme.of(context).primaryColor,
|
||||
);
|
||||
},
|
||||
child: Stack(
|
||||
children: [
|
||||
CachedNetworkImage(
|
||||
cacheKey: "${asset.id}-${cacheKey.value}",
|
||||
width: 500,
|
||||
height: 500,
|
||||
memCacheHeight: asset.type == 'IMAGE' ? 500 : 500,
|
||||
fit: BoxFit.cover,
|
||||
imageUrl: thumbnailRequestUrl,
|
||||
httpHeaders: {"Authorization": "Bearer ${box.get(accessTokenKey)}"},
|
||||
fadeInDuration: const Duration(milliseconds: 250),
|
||||
progressIndicatorBuilder: (context, url, downloadProgress) => Transform.scale(
|
||||
scale: 0.2,
|
||||
child: CircularProgressIndicator(value: downloadProgress.progress),
|
||||
),
|
||||
],
|
||||
),
|
||||
errorWidget: (context, url, error) {
|
||||
return Icon(
|
||||
Icons.image_not_supported_outlined,
|
||||
color: Theme.of(context).primaryColor,
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -49,7 +49,7 @@ class SharingSliverAppBar extends StatelessWidget {
|
||||
),
|
||||
label: const Text(
|
||||
"Create shared album",
|
||||
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 13),
|
||||
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 12),
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -69,7 +69,7 @@ class SharingSliverAppBar extends StatelessWidget {
|
||||
),
|
||||
label: const Text(
|
||||
"Share with partner",
|
||||
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 13),
|
||||
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 12),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -36,10 +36,10 @@ class AlbumViewerPage extends HookConsumerWidget {
|
||||
/// 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.
|
||||
void _onAddPhotosPressed(SharedAlbum albumInfo) async {
|
||||
if (albumInfo.sharedAssets != null && albumInfo.sharedAssets!.isNotEmpty) {
|
||||
if (albumInfo.assets != null && albumInfo.assets!.isNotEmpty) {
|
||||
ref
|
||||
.watch(assetSelectionProvider.notifier)
|
||||
.addNewAssets(albumInfo.sharedAssets!.map((e) => e.assetInfo).toList());
|
||||
.addNewAssets(albumInfo.assets!.toList());
|
||||
}
|
||||
|
||||
ref.watch(assetSelectionProvider.notifier).setIsAlbumExist(true);
|
||||
@@ -101,10 +101,10 @@ class AlbumViewerPage extends HookConsumerWidget {
|
||||
}
|
||||
|
||||
Widget _buildAlbumDateRange(SharedAlbum albumInfo) {
|
||||
if (albumInfo.sharedAssets != null && albumInfo.sharedAssets!.isNotEmpty) {
|
||||
if (albumInfo.assets != null && albumInfo.assets!.isNotEmpty) {
|
||||
String startDate = "";
|
||||
DateTime parsedStartDate = DateTime.parse(albumInfo.sharedAssets!.first.assetInfo.createdAt);
|
||||
DateTime parsedEndDate = DateTime.parse(albumInfo.sharedAssets!.last.assetInfo.createdAt);
|
||||
DateTime parsedStartDate = DateTime.parse(albumInfo.assets!.first.createdAt);
|
||||
DateTime parsedEndDate = DateTime.parse(albumInfo.assets!.last.createdAt);
|
||||
|
||||
if (parsedStartDate.year == parsedEndDate.year) {
|
||||
startDate = DateFormat('LLL d').format(parsedStartDate);
|
||||
@@ -163,7 +163,7 @@ class AlbumViewerPage extends HookConsumerWidget {
|
||||
}
|
||||
|
||||
Widget _buildImageGrid(SharedAlbum albumInfo) {
|
||||
if (albumInfo.sharedAssets != null && albumInfo.sharedAssets!.isNotEmpty) {
|
||||
if (albumInfo.assets != null && albumInfo.assets!.isNotEmpty) {
|
||||
return SliverPadding(
|
||||
padding: const EdgeInsets.only(top: 10.0),
|
||||
sliver: SliverGrid(
|
||||
@@ -174,9 +174,9 @@ class AlbumViewerPage extends HookConsumerWidget {
|
||||
),
|
||||
delegate: SliverChildBuilderDelegate(
|
||||
(BuildContext context, int index) {
|
||||
return AlbumViewerThumbnail(asset: albumInfo.sharedAssets![index].assetInfo);
|
||||
return AlbumViewerThumbnail(asset: albumInfo.assets![index]);
|
||||
},
|
||||
childCount: albumInfo.sharedAssets?.length,
|
||||
childCount: albumInfo.assets?.length,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -82,11 +82,11 @@ class CreateSharedAlbumPage extends HookConsumerWidget {
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.only(top: 16, left: 18, right: 18),
|
||||
child: OutlinedButton.icon(
|
||||
style: ButtonStyle(
|
||||
alignment: Alignment.centerLeft,
|
||||
padding:
|
||||
MaterialStateProperty.all<EdgeInsets>(const EdgeInsets.symmetric(vertical: 22, horizontal: 16)),
|
||||
),
|
||||
style: OutlinedButton.styleFrom(
|
||||
alignment: Alignment.centerLeft,
|
||||
padding: const EdgeInsets.symmetric(vertical: 22, horizontal: 16),
|
||||
side: const BorderSide(color: Color.fromARGB(255, 206, 206, 206)),
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5))),
|
||||
onPressed: _onSelectPhotosButtonPressed,
|
||||
icon: const Icon(Icons.add_rounded),
|
||||
label: Padding(
|
||||
|
||||
@@ -4,7 +4,7 @@ import 'package:flutter_hooks/flutter_hooks.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:immich_mobile/modules/sharing/models/shared_album.model.dart';
|
||||
import 'package:immich_mobile/modules/sharing/providers/suggested_shared_users.provider.dart';
|
||||
import 'package:immich_mobile/shared/models/user_info.model.dart';
|
||||
import 'package:immich_mobile/shared/models/user.model.dart';
|
||||
import 'package:immich_mobile/shared/ui/immich_loading_indicator.dart';
|
||||
|
||||
class SelectAdditionalUserForSharingPage extends HookConsumerWidget {
|
||||
@@ -14,14 +14,14 @@ class SelectAdditionalUserForSharingPage extends HookConsumerWidget {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
AsyncValue<List<UserInfo>> suggestedShareUsers = ref.watch(suggestedSharedUsersProvider);
|
||||
final sharedUsersList = useState<Set<UserInfo>>({});
|
||||
AsyncValue<List<User>> suggestedShareUsers = ref.watch(suggestedSharedUsersProvider);
|
||||
final sharedUsersList = useState<Set<User>>({});
|
||||
|
||||
_addNewUsersHandler() {
|
||||
AutoRouter.of(context).pop(sharedUsersList.value.map((e) => e.id).toList());
|
||||
}
|
||||
|
||||
_buildTileIcon(UserInfo user) {
|
||||
_buildTileIcon(User user) {
|
||||
if (sharedUsersList.value.contains(user)) {
|
||||
return CircleAvatar(
|
||||
backgroundColor: Theme.of(context).primaryColor,
|
||||
@@ -38,7 +38,7 @@ class SelectAdditionalUserForSharingPage extends HookConsumerWidget {
|
||||
}
|
||||
}
|
||||
|
||||
_buildUserList(List<UserInfo> users) {
|
||||
_buildUserList(List<User> users) {
|
||||
List<Widget> usersChip = [];
|
||||
|
||||
for (var user in sharedUsersList.value) {
|
||||
@@ -120,7 +120,7 @@ class SelectAdditionalUserForSharingPage extends HookConsumerWidget {
|
||||
body: suggestedShareUsers.when(
|
||||
data: (users) {
|
||||
for (var sharedUsers in albumInfo.sharedUsers) {
|
||||
users.removeWhere((u) => u.id == sharedUsers.sharedUserId || u.id == albumInfo.ownerId);
|
||||
users.removeWhere((u) => u.id == sharedUsers.id || u.id == albumInfo.ownerId);
|
||||
}
|
||||
|
||||
return _buildUserList(users);
|
||||
|
||||
@@ -8,15 +8,15 @@ import 'package:immich_mobile/modules/sharing/providers/shared_album.provider.da
|
||||
import 'package:immich_mobile/modules/sharing/providers/suggested_shared_users.provider.dart';
|
||||
import 'package:immich_mobile/modules/sharing/services/shared_album.service.dart';
|
||||
import 'package:immich_mobile/routing/router.dart';
|
||||
import 'package:immich_mobile/shared/models/user_info.model.dart';
|
||||
import 'package:immich_mobile/shared/models/user.model.dart';
|
||||
import 'package:immich_mobile/shared/ui/immich_loading_indicator.dart';
|
||||
|
||||
class SelectUserForSharingPage extends HookConsumerWidget {
|
||||
const SelectUserForSharingPage({Key? key}) : super(key: key);
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final sharedUsersList = useState<Set<UserInfo>>({});
|
||||
AsyncValue<List<UserInfo>> suggestedShareUsers = ref.watch(suggestedSharedUsersProvider);
|
||||
final sharedUsersList = useState<Set<User>>({});
|
||||
AsyncValue<List<User>> suggestedShareUsers = ref.watch(suggestedSharedUsersProvider);
|
||||
|
||||
_createSharedAlbum() async {
|
||||
var isSuccess = await SharedAlbumService().createSharedAlbum(
|
||||
@@ -36,7 +36,7 @@ class SelectUserForSharingPage extends HookConsumerWidget {
|
||||
const ScaffoldMessenger(child: SnackBar(content: Text('Failed to create album')));
|
||||
}
|
||||
|
||||
_buildTileIcon(UserInfo user) {
|
||||
_buildTileIcon(User user) {
|
||||
if (sharedUsersList.value.contains(user)) {
|
||||
return CircleAvatar(
|
||||
backgroundColor: Theme.of(context).primaryColor,
|
||||
@@ -53,7 +53,7 @@ class SelectUserForSharingPage extends HookConsumerWidget {
|
||||
}
|
||||
}
|
||||
|
||||
_buildUserList(List<UserInfo> users) {
|
||||
_buildUserList(List<User> users) {
|
||||
List<Widget> usersChip = [];
|
||||
|
||||
for (var user in sharedUsersList.value) {
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import 'dart:convert';
|
||||
|
||||
class ImmichAsset {
|
||||
import 'package:equatable/equatable.dart';
|
||||
|
||||
class ImmichAsset extends Equatable {
|
||||
final String id;
|
||||
final String deviceAssetId;
|
||||
final String userId;
|
||||
@@ -13,7 +15,7 @@ class ImmichAsset {
|
||||
final String originalPath;
|
||||
final String resizePath;
|
||||
|
||||
ImmichAsset({
|
||||
const ImmichAsset({
|
||||
required this.id,
|
||||
required this.deviceAssetId,
|
||||
required this.userId,
|
||||
@@ -56,19 +58,23 @@ class ImmichAsset {
|
||||
}
|
||||
|
||||
Map<String, dynamic> toMap() {
|
||||
return {
|
||||
'id': id,
|
||||
'deviceAssetId': deviceAssetId,
|
||||
'userId': userId,
|
||||
'deviceId': deviceId,
|
||||
'type': type,
|
||||
'createdAt': createdAt,
|
||||
'modifiedAt': modifiedAt,
|
||||
'isFavorite': isFavorite,
|
||||
'duration': duration,
|
||||
'originalPath': originalPath,
|
||||
'resizePath': resizePath,
|
||||
};
|
||||
final result = <String, dynamic>{};
|
||||
|
||||
result.addAll({'id': id});
|
||||
result.addAll({'deviceAssetId': deviceAssetId});
|
||||
result.addAll({'userId': userId});
|
||||
result.addAll({'deviceId': deviceId});
|
||||
result.addAll({'type': type});
|
||||
result.addAll({'createdAt': createdAt});
|
||||
result.addAll({'modifiedAt': modifiedAt});
|
||||
result.addAll({'isFavorite': isFavorite});
|
||||
if (duration != null) {
|
||||
result.addAll({'duration': duration});
|
||||
}
|
||||
result.addAll({'originalPath': originalPath});
|
||||
result.addAll({'resizePath': resizePath});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
factory ImmichAsset.fromMap(Map<String, dynamic> map) {
|
||||
@@ -97,35 +103,7 @@ class ImmichAsset {
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
if (identical(this, other)) return true;
|
||||
|
||||
return other is ImmichAsset &&
|
||||
other.id == id &&
|
||||
other.deviceAssetId == deviceAssetId &&
|
||||
other.userId == userId &&
|
||||
other.deviceId == deviceId &&
|
||||
other.type == type &&
|
||||
other.createdAt == createdAt &&
|
||||
other.modifiedAt == modifiedAt &&
|
||||
other.isFavorite == isFavorite &&
|
||||
other.duration == duration &&
|
||||
other.originalPath == originalPath &&
|
||||
other.resizePath == resizePath;
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return id.hashCode ^
|
||||
deviceAssetId.hashCode ^
|
||||
userId.hashCode ^
|
||||
deviceId.hashCode ^
|
||||
type.hashCode ^
|
||||
createdAt.hashCode ^
|
||||
modifiedAt.hashCode ^
|
||||
isFavorite.hashCode ^
|
||||
duration.hashCode ^
|
||||
originalPath.hashCode ^
|
||||
resizePath.hashCode;
|
||||
List<Object> get props {
|
||||
return [id];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,25 +1,33 @@
|
||||
import 'dart:convert';
|
||||
|
||||
class UserInfo {
|
||||
class User {
|
||||
final String id;
|
||||
final String email;
|
||||
final String createdAt;
|
||||
final String firstName;
|
||||
final String lastName;
|
||||
|
||||
UserInfo({
|
||||
User({
|
||||
required this.id,
|
||||
required this.email,
|
||||
required this.createdAt,
|
||||
required this.firstName,
|
||||
required this.lastName,
|
||||
});
|
||||
|
||||
UserInfo copyWith({
|
||||
User copyWith({
|
||||
String? id,
|
||||
String? email,
|
||||
String? createdAt,
|
||||
String? firstName,
|
||||
String? lastName,
|
||||
}) {
|
||||
return UserInfo(
|
||||
return User(
|
||||
id: id ?? this.id,
|
||||
email: email ?? this.email,
|
||||
createdAt: createdAt ?? this.createdAt,
|
||||
firstName: firstName ?? this.firstName,
|
||||
lastName: lastName ?? this.lastName,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -33,17 +41,19 @@ class UserInfo {
|
||||
return result;
|
||||
}
|
||||
|
||||
factory UserInfo.fromMap(Map<String, dynamic> map) {
|
||||
return UserInfo(
|
||||
factory User.fromMap(Map<String, dynamic> map) {
|
||||
return User(
|
||||
id: map['id'] ?? '',
|
||||
email: map['email'] ?? '',
|
||||
createdAt: map['createdAt'] ?? '',
|
||||
firstName: map['firstName'] ?? '',
|
||||
lastName: map['lastName'] ?? '',
|
||||
);
|
||||
}
|
||||
|
||||
String toJson() => json.encode(toMap());
|
||||
|
||||
factory UserInfo.fromJson(String source) => UserInfo.fromMap(json.decode(source));
|
||||
factory User.fromJson(String source) => User.fromMap(json.decode(source));
|
||||
|
||||
@override
|
||||
String toString() => 'UserInfo(id: $id, email: $email, createdAt: $createdAt)';
|
||||
@@ -52,7 +62,12 @@ class UserInfo {
|
||||
bool operator ==(Object other) {
|
||||
if (identical(this, other)) return true;
|
||||
|
||||
return other is UserInfo && other.id == id && other.email == email && other.createdAt == createdAt;
|
||||
return other is User &&
|
||||
other.id == id &&
|
||||
other.email == email &&
|
||||
other.createdAt == createdAt &&
|
||||
other.firstName == firstName &&
|
||||
other.lastName == lastName;
|
||||
}
|
||||
|
||||
@override
|
||||
57
mobile/lib/shared/providers/release_info.provider.dart
Normal file
57
mobile/lib/shared/providers/release_info.provider.dart
Normal file
@@ -0,0 +1,57 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:hive_flutter/hive_flutter.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:immich_mobile/constants/hive_box.dart';
|
||||
import 'package:immich_mobile/shared/views/version_announcement_overlay.dart';
|
||||
|
||||
class ReleaseInfoNotifier extends StateNotifier<String> {
|
||||
ReleaseInfoNotifier() : super("");
|
||||
|
||||
void checkGithubReleaseInfo() async {
|
||||
var dio = Dio();
|
||||
var box = Hive.box(hiveGithubReleaseInfoBox);
|
||||
|
||||
try {
|
||||
String? localReleaseVersion = box.get(githubReleaseInfoKey);
|
||||
|
||||
Response res = await dio.get(
|
||||
"https://api.github.com/repos/alextran1502/immich/releases/latest",
|
||||
options: Options(
|
||||
headers: {"Accept": "application/vnd.github.v3+json"},
|
||||
),
|
||||
);
|
||||
|
||||
if (res.statusCode == 200) {
|
||||
String latestTagVersion = res.data["tag_name"];
|
||||
state = latestTagVersion;
|
||||
|
||||
debugPrint("Local release version $localReleaseVersion");
|
||||
debugPrint("Remote release veresion $latestTagVersion");
|
||||
|
||||
if (localReleaseVersion == null && latestTagVersion.isNotEmpty) {
|
||||
VersionAnnouncementOverlayController.appLoader.show();
|
||||
return;
|
||||
}
|
||||
|
||||
if (latestTagVersion.isNotEmpty && localReleaseVersion != latestTagVersion) {
|
||||
VersionAnnouncementOverlayController.appLoader.show();
|
||||
return;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint("Error gettting latest release version");
|
||||
|
||||
state = "";
|
||||
}
|
||||
}
|
||||
|
||||
void acknowledgeNewVersion() {
|
||||
var box = Hive.box(hiveGithubReleaseInfoBox);
|
||||
|
||||
box.put(githubReleaseInfoKey, state);
|
||||
VersionAnnouncementOverlayController.appLoader.hide();
|
||||
}
|
||||
}
|
||||
|
||||
final releaseInfoProvider = StateNotifierProvider<ReleaseInfoNotifier, String>((ref) => ReleaseInfoNotifier());
|
||||
@@ -19,11 +19,6 @@ class ServerInfoNotifier extends StateNotifier<ServerInfoState> {
|
||||
|
||||
final ServerInfoService _serverInfoService = ServerInfoService();
|
||||
|
||||
getMapboxInfo() async {
|
||||
MapboxInfo mapboxInfoRes = await _serverInfoService.getMapboxInfo();
|
||||
state = state.copyWith(mapboxInfo: mapboxInfoRes);
|
||||
}
|
||||
|
||||
getServerVersion() async {
|
||||
ServerVersion? serverVersion = await _serverInfoService.getServerVersion();
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ class NetworkService {
|
||||
} on DioError catch (e) {
|
||||
debugPrint("DioError: ${e.response}");
|
||||
} catch (e) {
|
||||
debugPrint("ERROR getRequest: ${e.toString()}");
|
||||
debugPrint("ERROR deleteRequest: ${e.toString()}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -78,7 +78,26 @@ class NetworkService {
|
||||
debugPrint("DioError: ${e.response}");
|
||||
return null;
|
||||
} catch (e) {
|
||||
debugPrint("ERROR BackupService: $e");
|
||||
debugPrint("ERROR PostRequest: $e");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Future<dynamic> putRequest({required String url, dynamic data}) async {
|
||||
try {
|
||||
var dio = Dio();
|
||||
dio.interceptors.add(AuthenticatedRequestInterceptor());
|
||||
|
||||
var savedEndpoint = Hive.box(userInfoBox).get(serverEndpointKey);
|
||||
String validUrl = Uri.parse('$savedEndpoint/$url').toString();
|
||||
Response res = await dio.put(validUrl, data: data);
|
||||
|
||||
return res;
|
||||
} on DioError catch (e) {
|
||||
debugPrint("DioError: ${e.response}");
|
||||
return null;
|
||||
} catch (e) {
|
||||
debugPrint("ERROR PutRequest: $e");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -97,7 +116,7 @@ class NetworkService {
|
||||
} on DioError catch (e) {
|
||||
debugPrint("DioError: ${e.response}");
|
||||
} catch (e) {
|
||||
debugPrint("ERROR BackupService: $e");
|
||||
debugPrint("ERROR PatchRequest: $e");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -122,7 +141,7 @@ class NetworkService {
|
||||
debugPrint("[PING SERVER] DioError: ${e.response} - $e");
|
||||
return false;
|
||||
} catch (e) {
|
||||
debugPrint("ERROR BackupService: $e");
|
||||
debugPrint("ERROR PingServer: $e");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:immich_mobile/shared/models/mapbox_info.model.dart';
|
||||
import 'package:immich_mobile/shared/models/server_version.model.dart';
|
||||
import 'package:immich_mobile/shared/services/network.service.dart';
|
||||
@@ -13,15 +14,16 @@ class ServerInfoService {
|
||||
return ServerInfo.fromJson(response.toString());
|
||||
}
|
||||
|
||||
Future<MapboxInfo> getMapboxInfo() async {
|
||||
Response response = await _networkService.getRequest(url: 'server-info/mapbox');
|
||||
|
||||
return MapboxInfo.fromJson(response.toString());
|
||||
}
|
||||
|
||||
Future<ServerVersion?> getServerVersion() async {
|
||||
Response response = await _networkService.getRequest(url: 'server-info/version');
|
||||
try {
|
||||
Response response =
|
||||
await _networkService.getRequest(url: 'server-info/version');
|
||||
|
||||
return ServerVersion.fromJson(response.toString());
|
||||
return ServerVersion.fromJson(response.toString());
|
||||
} catch (e) {
|
||||
debugPrint("Error getting server info");
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ import 'package:hive/hive.dart';
|
||||
import 'package:image_picker/image_picker.dart';
|
||||
import 'package:immich_mobile/constants/hive_box.dart';
|
||||
import 'package:immich_mobile/shared/models/upload_profile_image_repsonse.model.dart';
|
||||
import 'package:immich_mobile/shared/models/user_info.model.dart';
|
||||
import 'package:immich_mobile/shared/models/user.model.dart';
|
||||
import 'package:immich_mobile/shared/services/network.service.dart';
|
||||
import 'package:immich_mobile/utils/dio_http_interceptor.dart';
|
||||
import 'package:immich_mobile/utils/files_helper.dart';
|
||||
@@ -15,11 +15,11 @@ import 'package:http_parser/http_parser.dart';
|
||||
class UserService {
|
||||
final NetworkService _networkService = NetworkService();
|
||||
|
||||
Future<List<UserInfo>> getAllUsersInfo() async {
|
||||
Future<List<User>> getAllUsersInfo() async {
|
||||
try {
|
||||
Response res = await _networkService.getRequest(url: 'user');
|
||||
List<dynamic> decodedData = jsonDecode(res.toString());
|
||||
List<UserInfo> result = List.from(decodedData.map((e) => UserInfo.fromMap(e)));
|
||||
List<User> result = List.from(decodedData.map((e) => User.fromMap(e)));
|
||||
|
||||
return result;
|
||||
} catch (e) {
|
||||
|
||||
@@ -19,26 +19,32 @@ class TabControllerPage extends ConsumerWidget {
|
||||
],
|
||||
builder: (context, child, animation) {
|
||||
final tabsRouter = AutoTabsRouter.of(context);
|
||||
return Scaffold(
|
||||
body: FadeTransition(
|
||||
opacity: animation,
|
||||
child: child,
|
||||
return WillPopScope(
|
||||
onWillPop: () async {
|
||||
tabsRouter.setActiveIndex(0);
|
||||
return false;
|
||||
},
|
||||
child: Scaffold(
|
||||
body: FadeTransition(
|
||||
opacity: animation,
|
||||
child: child,
|
||||
),
|
||||
bottomNavigationBar: isMultiSelectEnable
|
||||
? null
|
||||
: BottomNavigationBar(
|
||||
selectedLabelStyle: const TextStyle(fontSize: 15, fontWeight: FontWeight.w600),
|
||||
unselectedLabelStyle: const TextStyle(fontSize: 15, fontWeight: FontWeight.w600),
|
||||
currentIndex: tabsRouter.activeIndex,
|
||||
onTap: (index) {
|
||||
tabsRouter.setActiveIndex(index);
|
||||
},
|
||||
items: const [
|
||||
BottomNavigationBarItem(label: 'Photos', icon: Icon(Icons.photo)),
|
||||
BottomNavigationBarItem(label: 'Search', icon: Icon(Icons.search)),
|
||||
BottomNavigationBarItem(label: 'Sharing', icon: Icon(Icons.group_outlined)),
|
||||
],
|
||||
),
|
||||
),
|
||||
bottomNavigationBar: isMultiSelectEnable
|
||||
? null
|
||||
: BottomNavigationBar(
|
||||
selectedLabelStyle: const TextStyle(fontSize: 15, fontWeight: FontWeight.w600),
|
||||
unselectedLabelStyle: const TextStyle(fontSize: 15, fontWeight: FontWeight.w600),
|
||||
currentIndex: tabsRouter.activeIndex,
|
||||
onTap: (index) {
|
||||
tabsRouter.setActiveIndex(index);
|
||||
},
|
||||
items: const [
|
||||
BottomNavigationBarItem(label: 'Photos', icon: Icon(Icons.photo)),
|
||||
BottomNavigationBarItem(label: 'Search', icon: Icon(Icons.search)),
|
||||
BottomNavigationBarItem(label: 'Sharing', icon: Icon(Icons.group_outlined)),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
133
mobile/lib/shared/views/version_announcement_overlay.dart
Normal file
133
mobile/lib/shared/views/version_announcement_overlay.dart
Normal file
@@ -0,0 +1,133 @@
|
||||
import 'package:flutter/gestures.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:immich_mobile/shared/providers/release_info.provider.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
|
||||
class VersionAnnouncementOverlay extends HookConsumerWidget {
|
||||
const VersionAnnouncementOverlay({
|
||||
Key? key,
|
||||
}) : super(key: key);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
void goToReleaseNote() async {
|
||||
final Uri _url = Uri.parse('https://github.com/alextran1502/immich/releases/latest');
|
||||
await launchUrl(_url);
|
||||
}
|
||||
|
||||
void onAcknowledgeTapped() {
|
||||
ref.watch(releaseInfoProvider.notifier).acknowledgeNewVersion();
|
||||
}
|
||||
|
||||
return ValueListenableBuilder<bool>(
|
||||
valueListenable: VersionAnnouncementOverlayController.appLoader.loaderShowingNotifier,
|
||||
builder: (context, shouldShow, child) {
|
||||
if (shouldShow) {
|
||||
return Scaffold(
|
||||
backgroundColor: Colors.black38,
|
||||
body: Center(
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: 307),
|
||||
child: Wrap(
|
||||
children: [
|
||||
Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(30.0),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const Text(
|
||||
"New Server Version Available 🎉",
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
fontFamily: 'WorkSans',
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Colors.indigo,
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 16.0),
|
||||
child: RichText(
|
||||
text: TextSpan(
|
||||
style: const TextStyle(
|
||||
fontSize: 14, fontFamily: 'WorkSans', color: Colors.black87, height: 1.2),
|
||||
children: <TextSpan>[
|
||||
const TextSpan(
|
||||
text: 'Hi friend, there is a new release of',
|
||||
),
|
||||
const TextSpan(
|
||||
text: ' Immich ',
|
||||
style: TextStyle(
|
||||
fontFamily: "SnowBurstOne",
|
||||
color: Colors.indigo,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const TextSpan(
|
||||
text: "please take your time to visit the ",
|
||||
),
|
||||
TextSpan(
|
||||
text: "release note",
|
||||
style: const TextStyle(
|
||||
decoration: TextDecoration.underline,
|
||||
),
|
||||
recognizer: TapGestureRecognizer()..onTap = goToReleaseNote,
|
||||
),
|
||||
const TextSpan(
|
||||
text:
|
||||
" and ensure your docker-compose and .env setup is up-to-date to prevent any misconfigurations, especially if you use WatchTower or any mechanism that handles updating your server application automatically.",
|
||||
)
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 16.0),
|
||||
child: ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(
|
||||
shape: const StadiumBorder(),
|
||||
visualDensity: VisualDensity.standard,
|
||||
primary: Colors.indigo,
|
||||
onPrimary: Colors.grey[50],
|
||||
elevation: 2,
|
||||
padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 25),
|
||||
),
|
||||
onPressed: onAcknowledgeTapped,
|
||||
child: const Text(
|
||||
"Acknowledge",
|
||||
style: TextStyle(
|
||||
fontSize: 14,
|
||||
),
|
||||
)),
|
||||
)
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
return Container();
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class VersionAnnouncementOverlayController {
|
||||
static final VersionAnnouncementOverlayController appLoader = VersionAnnouncementOverlayController();
|
||||
ValueNotifier<bool> loaderShowingNotifier = ValueNotifier(false);
|
||||
ValueNotifier<String> loaderTextNotifier = ValueNotifier('error message');
|
||||
|
||||
void show() {
|
||||
loaderShowingNotifier.value = true;
|
||||
}
|
||||
|
||||
void hide() {
|
||||
loaderShowingNotifier.value = false;
|
||||
}
|
||||
}
|
||||
@@ -141,6 +141,20 @@ packages:
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "1.0.1"
|
||||
cancellation_token:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: cancellation_token
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "1.4.0"
|
||||
cancellation_token_http:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: cancellation_token_http
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "1.1.0"
|
||||
characters:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -437,7 +451,7 @@ packages:
|
||||
source: hosted
|
||||
version: "0.15.0"
|
||||
http:
|
||||
dependency: transitive
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: http
|
||||
url: "https://pub.dartlang.org"
|
||||
@@ -1015,6 +1029,62 @@ packages:
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "2.0.4"
|
||||
url_launcher:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: url_launcher
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "6.1.3"
|
||||
url_launcher_android:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: url_launcher_android
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "6.0.17"
|
||||
url_launcher_ios:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: url_launcher_ios
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "6.0.17"
|
||||
url_launcher_linux:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: url_launcher_linux
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "3.0.1"
|
||||
url_launcher_macos:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: url_launcher_macos
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "3.0.1"
|
||||
url_launcher_platform_interface:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: url_launcher_platform_interface
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "2.0.5"
|
||||
url_launcher_web:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: url_launcher_web
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "2.0.11"
|
||||
url_launcher_windows:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: url_launcher_windows
|
||||
url: "https://pub.dartlang.org"
|
||||
source: hosted
|
||||
version: "3.0.1"
|
||||
uuid:
|
||||
dependency: transitive
|
||||
description:
|
||||
|
||||
@@ -2,7 +2,7 @@ name: immich_mobile
|
||||
description: Immich - selfhosted backup media file on mobile phone
|
||||
|
||||
publish_to: "none"
|
||||
version: 1.10.0+15
|
||||
version: 1.12.0+18
|
||||
|
||||
environment:
|
||||
sdk: ">=2.15.1 <3.0.0"
|
||||
@@ -39,6 +39,9 @@ dependencies:
|
||||
flutter_swipe_detector: ^2.0.0
|
||||
equatable: ^2.0.3
|
||||
image_picker: ^0.8.5+3
|
||||
url_launcher: ^6.1.3
|
||||
http: 0.13.4
|
||||
cancellation_token_http: ^1.1.0
|
||||
|
||||
dev_dependencies:
|
||||
flutter_test:
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
FROM node:16-alpine3.14
|
||||
FROM node:16-alpine3.14 as core
|
||||
|
||||
ARG DEBIAN_FRONTEND=noninteractive
|
||||
|
||||
@@ -8,8 +8,8 @@ COPY package.json package-lock.json ./
|
||||
|
||||
RUN apk add --update-cache build-base python3 libheif vips-dev vips ffmpeg
|
||||
|
||||
RUN npm install
|
||||
RUN npm install --legacy-peer-deps
|
||||
|
||||
COPY . .
|
||||
|
||||
RUN npm run build
|
||||
RUN npm run build
|
||||
|
||||
228
server/apps/immich/src/api-v1/album/album-repository.ts
Normal file
228
server/apps/immich/src/api-v1/album/album-repository.ts
Normal file
@@ -0,0 +1,228 @@
|
||||
import { AlbumEntity } from '@app/database/entities/album.entity';
|
||||
import { AssetAlbumEntity } from '@app/database/entities/asset-album.entity';
|
||||
import { UserAlbumEntity } from '@app/database/entities/user-album.entity';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { getConnection, Repository, SelectQueryBuilder } from 'typeorm';
|
||||
import { AddAssetsDto } from './dto/add-assets.dto';
|
||||
import { AddUsersDto } from './dto/add-users.dto';
|
||||
import { CreateAlbumDto } from './dto/create-album.dto';
|
||||
import { GetAlbumsDto } from './dto/get-albums.dto';
|
||||
import { RemoveAssetsDto } from './dto/remove-assets.dto';
|
||||
import { UpdateAlbumDto } from './dto/update-album.dto';
|
||||
|
||||
export interface IAlbumRepository {
|
||||
create(ownerId: string, createAlbumDto: CreateAlbumDto): Promise<AlbumEntity>;
|
||||
getList(ownerId: string, getAlbumsDto: GetAlbumsDto): Promise<AlbumEntity[]>;
|
||||
get(albumId: string): Promise<AlbumEntity>;
|
||||
delete(album: AlbumEntity): Promise<void>;
|
||||
addSharedUsers(album: AlbumEntity, addUsersDto: AddUsersDto): Promise<AlbumEntity>;
|
||||
removeUser(album: AlbumEntity, userId: string): Promise<void>;
|
||||
removeAssets(album: AlbumEntity, removeAssets: RemoveAssetsDto): Promise<boolean>;
|
||||
addAssets(album: AlbumEntity, addAssetsDto: AddAssetsDto): Promise<AlbumEntity>;
|
||||
updateAlbum(album: AlbumEntity, updateAlbumDto: UpdateAlbumDto): Promise<AlbumEntity>;
|
||||
}
|
||||
|
||||
export const ALBUM_REPOSITORY = 'ALBUM_REPOSITORY';
|
||||
|
||||
@Injectable()
|
||||
export class AlbumRepository implements IAlbumRepository {
|
||||
constructor(
|
||||
@InjectRepository(AlbumEntity)
|
||||
private albumRepository: Repository<AlbumEntity>,
|
||||
|
||||
@InjectRepository(AssetAlbumEntity)
|
||||
private assetAlbumRepository: Repository<AssetAlbumEntity>,
|
||||
|
||||
@InjectRepository(UserAlbumEntity)
|
||||
private userAlbumRepository: Repository<UserAlbumEntity>,
|
||||
) {}
|
||||
|
||||
async create(ownerId: string, createAlbumDto: CreateAlbumDto): Promise<AlbumEntity> {
|
||||
return await getConnection().transaction(async (transactionalEntityManager) => {
|
||||
// Create album entity
|
||||
const newAlbum = new AlbumEntity();
|
||||
newAlbum.ownerId = ownerId;
|
||||
newAlbum.albumName = createAlbumDto.albumName;
|
||||
|
||||
const album = await transactionalEntityManager.save(newAlbum);
|
||||
|
||||
// Add shared users
|
||||
if (createAlbumDto.sharedWithUserIds?.length) {
|
||||
for (const sharedUserId of createAlbumDto.sharedWithUserIds) {
|
||||
const newSharedUser = new UserAlbumEntity();
|
||||
newSharedUser.albumId = album.id;
|
||||
newSharedUser.sharedUserId = sharedUserId;
|
||||
|
||||
await transactionalEntityManager.save(newSharedUser);
|
||||
}
|
||||
}
|
||||
|
||||
// Add shared assets
|
||||
const newRecords: AssetAlbumEntity[] = [];
|
||||
|
||||
if (createAlbumDto.assetIds?.length) {
|
||||
for (const assetId of createAlbumDto.assetIds) {
|
||||
const newAssetAlbum = new AssetAlbumEntity();
|
||||
newAssetAlbum.assetId = assetId;
|
||||
newAssetAlbum.albumId = album.id;
|
||||
|
||||
newRecords.push(newAssetAlbum);
|
||||
}
|
||||
}
|
||||
|
||||
if (!album.albumThumbnailAssetId && newRecords.length > 0) {
|
||||
album.albumThumbnailAssetId = newRecords[0].assetId;
|
||||
await transactionalEntityManager.save(album);
|
||||
}
|
||||
|
||||
await transactionalEntityManager.save([...newRecords]);
|
||||
|
||||
return album;
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
getList(ownerId: string, getAlbumsDto: GetAlbumsDto): Promise<AlbumEntity[]> {
|
||||
const filteringByShared = typeof getAlbumsDto.shared == 'boolean';
|
||||
const userId = ownerId;
|
||||
let query = this.albumRepository.createQueryBuilder('album');
|
||||
|
||||
const getSharedAlbumIdsSubQuery = (qb: SelectQueryBuilder<AlbumEntity>) => {
|
||||
return qb
|
||||
.subQuery()
|
||||
.select('albumSub.id')
|
||||
.from(AlbumEntity, 'albumSub')
|
||||
.innerJoin('albumSub.sharedUsers', 'userAlbumSub')
|
||||
.where('albumSub.ownerId = :ownerId', { ownerId: userId })
|
||||
.getQuery();
|
||||
};
|
||||
|
||||
if (filteringByShared) {
|
||||
if (getAlbumsDto.shared) {
|
||||
// shared albums
|
||||
query = query
|
||||
.innerJoinAndSelect('album.sharedUsers', 'sharedUser')
|
||||
.innerJoinAndSelect('sharedUser.userInfo', 'userInfo')
|
||||
.where((qb) => {
|
||||
// owned and shared with other users
|
||||
const subQuery = getSharedAlbumIdsSubQuery(qb);
|
||||
return `album.id IN ${subQuery}`;
|
||||
})
|
||||
.orWhere((qb) => {
|
||||
// shared with userId
|
||||
const subQuery = qb
|
||||
.subQuery()
|
||||
.select('userAlbum.albumId')
|
||||
.from(UserAlbumEntity, 'userAlbum')
|
||||
.where('userAlbum.sharedUserId = :sharedUserId', { sharedUserId: userId })
|
||||
.getQuery();
|
||||
return `album.id IN ${subQuery}`;
|
||||
});
|
||||
} else {
|
||||
// owned, not shared albums
|
||||
query = query.where('album.ownerId = :ownerId', { ownerId: userId }).andWhere((qb) => {
|
||||
const subQuery = getSharedAlbumIdsSubQuery(qb);
|
||||
return `album.id NOT IN ${subQuery}`;
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// owned and shared with userId
|
||||
query = query
|
||||
.leftJoinAndSelect('album.sharedUsers', 'sharedUser')
|
||||
.leftJoinAndSelect('sharedUser.userInfo', 'userInfo')
|
||||
.where('album.ownerId = :ownerId', { ownerId: userId })
|
||||
.orWhere((qb) => {
|
||||
const subQuery = qb
|
||||
.subQuery()
|
||||
.select('userAlbum.albumId')
|
||||
.from(UserAlbumEntity, 'userAlbum')
|
||||
.where('userAlbum.sharedUserId = :sharedUserId', { sharedUserId: userId })
|
||||
.getQuery();
|
||||
return `album.id IN ${subQuery}`;
|
||||
});
|
||||
}
|
||||
return query.orderBy('album.createdAt', 'DESC').getMany();
|
||||
}
|
||||
|
||||
async get(albumId: string): Promise<AlbumEntity | undefined> {
|
||||
const album = await this.albumRepository.findOne({
|
||||
where: { id: albumId },
|
||||
relations: ['sharedUsers', 'sharedUsers.userInfo', 'assets', 'assets.assetInfo'],
|
||||
});
|
||||
|
||||
if (!album) {
|
||||
return;
|
||||
}
|
||||
// TODO: sort in query
|
||||
const sortedSharedAsset = album.assets.sort(
|
||||
(a, b) => new Date(a.assetInfo.createdAt).valueOf() - new Date(b.assetInfo.createdAt).valueOf(),
|
||||
);
|
||||
|
||||
album.assets = sortedSharedAsset;
|
||||
|
||||
return album;
|
||||
}
|
||||
|
||||
async delete(album: AlbumEntity): Promise<void> {
|
||||
await this.albumRepository.delete({ id: album.id, ownerId: album.ownerId });
|
||||
}
|
||||
|
||||
async addSharedUsers(album: AlbumEntity, addUsersDto: AddUsersDto): Promise<AlbumEntity> {
|
||||
const newRecords: UserAlbumEntity[] = [];
|
||||
|
||||
for (const sharedUserId of addUsersDto.sharedUserIds) {
|
||||
const newEntity = new UserAlbumEntity();
|
||||
newEntity.albumId = album.id;
|
||||
newEntity.sharedUserId = sharedUserId;
|
||||
|
||||
newRecords.push(newEntity);
|
||||
}
|
||||
|
||||
await this.userAlbumRepository.save([...newRecords]);
|
||||
return this.get(album.id);
|
||||
}
|
||||
|
||||
async removeUser(album: AlbumEntity, userId: string): Promise<void> {
|
||||
await this.userAlbumRepository.delete({ albumId: album.id, sharedUserId: userId });
|
||||
}
|
||||
|
||||
async removeAssets(album: AlbumEntity, removeAssetsDto: RemoveAssetsDto): Promise<boolean> {
|
||||
let deleteAssetCount = 0;
|
||||
// TODO: should probably do a single delete query?
|
||||
for (const assetId of removeAssetsDto.assetIds) {
|
||||
const res = await this.assetAlbumRepository.delete({ albumId: album.id, assetId: assetId });
|
||||
if (res.affected == 1) deleteAssetCount++;
|
||||
}
|
||||
|
||||
// TODO: No need to return boolean if using a singe delete query
|
||||
return deleteAssetCount == removeAssetsDto.assetIds.length;
|
||||
}
|
||||
|
||||
async addAssets(album: AlbumEntity, addAssetsDto: AddAssetsDto): Promise<AlbumEntity> {
|
||||
const newRecords: AssetAlbumEntity[] = [];
|
||||
|
||||
for (const assetId of addAssetsDto.assetIds) {
|
||||
const newAssetAlbum = new AssetAlbumEntity();
|
||||
newAssetAlbum.assetId = assetId;
|
||||
newAssetAlbum.albumId = album.id;
|
||||
|
||||
newRecords.push(newAssetAlbum);
|
||||
}
|
||||
|
||||
// Add album thumbnail if not exist.
|
||||
if (!album.albumThumbnailAssetId && newRecords.length > 0) {
|
||||
album.albumThumbnailAssetId = newRecords[0].assetId;
|
||||
await this.albumRepository.save(album);
|
||||
}
|
||||
|
||||
await this.assetAlbumRepository.save([...newRecords]);
|
||||
return this.get(album.id);
|
||||
}
|
||||
|
||||
updateAlbum(album: AlbumEntity, updateAlbumDto: UpdateAlbumDto): Promise<AlbumEntity> {
|
||||
album.albumName = updateAlbumDto.albumName;
|
||||
|
||||
return this.albumRepository.save(album);
|
||||
}
|
||||
}
|
||||
105
server/apps/immich/src/api-v1/album/album.controller.ts
Normal file
105
server/apps/immich/src/api-v1/album/album.controller.ts
Normal file
@@ -0,0 +1,105 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Body,
|
||||
Patch,
|
||||
Param,
|
||||
Delete,
|
||||
UseGuards,
|
||||
ValidationPipe,
|
||||
ParseUUIDPipe,
|
||||
Put,
|
||||
Query,
|
||||
} from '@nestjs/common';
|
||||
import { ParseMeUUIDPipe } from '../validation/parse-me-uuid-pipe';
|
||||
import { AlbumService } from './album.service';
|
||||
import { CreateAlbumDto } from './dto/create-album.dto';
|
||||
import { JwtAuthGuard } from '../../modules/immich-jwt/guards/jwt-auth.guard';
|
||||
import { AuthUserDto, GetAuthUser } from '../../decorators/auth-user.decorator';
|
||||
import { AddAssetsDto } from './dto/add-assets.dto';
|
||||
import { AddUsersDto } from './dto/add-users.dto';
|
||||
import { RemoveAssetsDto } from './dto/remove-assets.dto';
|
||||
import { UpdateAlbumDto } from './dto/update-album.dto';
|
||||
import { GetAlbumsDto } from './dto/get-albums.dto';
|
||||
|
||||
// TODO might be worth creating a AlbumParamsDto that validates `albumId` instead of using the pipe.
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Controller('album')
|
||||
export class AlbumController {
|
||||
constructor(private readonly albumService: AlbumService) {}
|
||||
|
||||
@Post()
|
||||
async create(@GetAuthUser() authUser: AuthUserDto, @Body(ValidationPipe) createAlbumDto: CreateAlbumDto) {
|
||||
return this.albumService.create(authUser, createAlbumDto);
|
||||
}
|
||||
|
||||
@Put('/:albumId/users')
|
||||
async addUsers(
|
||||
@GetAuthUser() authUser: AuthUserDto,
|
||||
@Body(ValidationPipe) addUsersDto: AddUsersDto,
|
||||
@Param('albumId', new ParseUUIDPipe({ version: '4' })) albumId: string,
|
||||
) {
|
||||
return this.albumService.addUsersToAlbum(authUser, addUsersDto, albumId);
|
||||
}
|
||||
|
||||
@Put('/:albumId/assets')
|
||||
async addAssets(
|
||||
@GetAuthUser() authUser: AuthUserDto,
|
||||
@Body(ValidationPipe) addAssetsDto: AddAssetsDto,
|
||||
@Param('albumId', new ParseUUIDPipe({ version: '4' })) albumId: string,
|
||||
) {
|
||||
return this.albumService.addAssetsToAlbum(authUser, addAssetsDto, albumId);
|
||||
}
|
||||
|
||||
@Get()
|
||||
async getAllAlbums(
|
||||
@GetAuthUser() authUser: AuthUserDto,
|
||||
@Query(new ValidationPipe({ transform: true })) query: GetAlbumsDto,
|
||||
) {
|
||||
return this.albumService.getAllAlbums(authUser, query);
|
||||
}
|
||||
|
||||
@Get('/:albumId')
|
||||
async getAlbumInfo(
|
||||
@GetAuthUser() authUser: AuthUserDto,
|
||||
@Param('albumId', new ParseUUIDPipe({ version: '4' })) albumId: string,
|
||||
) {
|
||||
return this.albumService.getAlbumInfo(authUser, albumId);
|
||||
}
|
||||
|
||||
@Delete('/:albumId/assets')
|
||||
async removeAssetFromAlbum(
|
||||
@GetAuthUser() authUser: AuthUserDto,
|
||||
@Body(ValidationPipe) removeAssetsDto: RemoveAssetsDto,
|
||||
@Param('albumId', new ParseUUIDPipe({ version: '4' })) albumId: string,
|
||||
) {
|
||||
return this.albumService.removeAssetsFromAlbum(authUser, removeAssetsDto, albumId);
|
||||
}
|
||||
|
||||
@Delete('/:albumId')
|
||||
async deleteAlbum(
|
||||
@GetAuthUser() authUser: AuthUserDto,
|
||||
@Param('albumId', new ParseUUIDPipe({ version: '4' })) albumId: string,
|
||||
) {
|
||||
return this.albumService.deleteAlbum(authUser, albumId);
|
||||
}
|
||||
|
||||
@Delete('/:albumId/user/:userId')
|
||||
async removeUserFromAlbum(
|
||||
@GetAuthUser() authUser: AuthUserDto,
|
||||
@Param('albumId', new ParseUUIDPipe({ version: '4' })) albumId: string,
|
||||
@Param('userId', new ParseMeUUIDPipe({ version: '4' })) userId: string,
|
||||
) {
|
||||
return this.albumService.removeUserFromAlbum(authUser, albumId, userId);
|
||||
}
|
||||
|
||||
@Patch('/:albumId')
|
||||
async updateAlbumInfo(
|
||||
@GetAuthUser() authUser: AuthUserDto,
|
||||
@Body(ValidationPipe) updateAlbumInfoDto: UpdateAlbumDto,
|
||||
@Param('albumId', new ParseUUIDPipe({ version: '4' })) albumId: string,
|
||||
) {
|
||||
return this.albumService.updateAlbumTitle(authUser, updateAlbumInfoDto, albumId);
|
||||
}
|
||||
}
|
||||
23
server/apps/immich/src/api-v1/album/album.module.ts
Normal file
23
server/apps/immich/src/api-v1/album/album.module.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AlbumService } from './album.service';
|
||||
import { AlbumController } from './album.controller';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { AssetEntity } from '@app/database/entities/asset.entity';
|
||||
import { UserEntity } from '@app/database/entities/user.entity';
|
||||
import { AlbumEntity } from '../../../../../libs/database/src/entities/album.entity';
|
||||
import { AssetAlbumEntity } from '@app/database/entities/asset-album.entity';
|
||||
import { UserAlbumEntity } from '@app/database/entities/user-album.entity';
|
||||
import { AlbumRepository, ALBUM_REPOSITORY } from './album-repository';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([AssetEntity, UserEntity, AlbumEntity, AssetAlbumEntity, UserAlbumEntity])],
|
||||
controllers: [AlbumController],
|
||||
providers: [
|
||||
AlbumService,
|
||||
{
|
||||
provide: ALBUM_REPOSITORY,
|
||||
useClass: AlbumRepository,
|
||||
},
|
||||
],
|
||||
})
|
||||
export class AlbumModule {}
|
||||
414
server/apps/immich/src/api-v1/album/album.service.spec.ts
Normal file
414
server/apps/immich/src/api-v1/album/album.service.spec.ts
Normal file
@@ -0,0 +1,414 @@
|
||||
import { AlbumService } from './album.service';
|
||||
import { IAlbumRepository } from './album-repository';
|
||||
import { AuthUserDto } from '../../decorators/auth-user.decorator';
|
||||
import { BadRequestException, NotFoundException, ForbiddenException } from '@nestjs/common';
|
||||
import { AlbumEntity } from '@app/database/entities/album.entity';
|
||||
import { AlbumResponseDto } from './response-dto/album-response.dto';
|
||||
|
||||
describe('Album service', () => {
|
||||
let sut: AlbumService;
|
||||
let albumRepositoryMock: jest.Mocked<IAlbumRepository>;
|
||||
const authUser: AuthUserDto = Object.freeze({
|
||||
id: '1111',
|
||||
email: 'auth@test.com',
|
||||
});
|
||||
const albumId = '0001';
|
||||
const sharedAlbumOwnerId = '2222';
|
||||
const sharedAlbumSharedAlsoWithId = '3333';
|
||||
const ownedAlbumSharedWithId = '4444';
|
||||
|
||||
const _getOwnedAlbum = () => {
|
||||
const albumEntity = new AlbumEntity();
|
||||
albumEntity.ownerId = authUser.id;
|
||||
albumEntity.id = albumId;
|
||||
albumEntity.albumName = 'name';
|
||||
albumEntity.createdAt = 'date';
|
||||
albumEntity.sharedUsers = [];
|
||||
albumEntity.assets = [];
|
||||
|
||||
return albumEntity;
|
||||
};
|
||||
|
||||
const _getOwnedSharedAlbum = () => {
|
||||
const albumEntity = new AlbumEntity();
|
||||
albumEntity.ownerId = authUser.id;
|
||||
albumEntity.id = albumId;
|
||||
albumEntity.albumName = 'name';
|
||||
albumEntity.createdAt = 'date';
|
||||
albumEntity.assets = [];
|
||||
albumEntity.sharedUsers = [
|
||||
{
|
||||
id: '99',
|
||||
albumId,
|
||||
sharedUserId: ownedAlbumSharedWithId,
|
||||
//@ts-expect-error Partial stub
|
||||
albumInfo: {},
|
||||
//@ts-expect-error Partial stub
|
||||
userInfo: {
|
||||
id: ownedAlbumSharedWithId,
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
return albumEntity;
|
||||
};
|
||||
|
||||
const _getSharedWithAuthUserAlbum = () => {
|
||||
const albumEntity = new AlbumEntity();
|
||||
albumEntity.ownerId = sharedAlbumOwnerId;
|
||||
albumEntity.id = albumId;
|
||||
albumEntity.albumName = 'name';
|
||||
albumEntity.createdAt = 'date';
|
||||
albumEntity.assets = [];
|
||||
albumEntity.sharedUsers = [
|
||||
{
|
||||
id: '99',
|
||||
albumId,
|
||||
sharedUserId: authUser.id,
|
||||
//@ts-expect-error Partial stub
|
||||
albumInfo: {},
|
||||
//@ts-expect-error Partial stub
|
||||
userInfo: {
|
||||
id: authUser.id,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: '98',
|
||||
albumId,
|
||||
sharedUserId: sharedAlbumSharedAlsoWithId,
|
||||
//@ts-expect-error Partial stub
|
||||
albumInfo: {},
|
||||
//@ts-expect-error Partial stub
|
||||
userInfo: {
|
||||
id: sharedAlbumSharedAlsoWithId,
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
return albumEntity;
|
||||
};
|
||||
|
||||
const _getNotOwnedNotSharedAlbum = () => {
|
||||
const albumEntity = new AlbumEntity();
|
||||
albumEntity.ownerId = '5555';
|
||||
albumEntity.id = albumId;
|
||||
albumEntity.albumName = 'name';
|
||||
albumEntity.createdAt = 'date';
|
||||
albumEntity.sharedUsers = [];
|
||||
albumEntity.assets = [];
|
||||
|
||||
return albumEntity;
|
||||
};
|
||||
|
||||
beforeAll(() => {
|
||||
albumRepositoryMock = {
|
||||
addAssets: jest.fn(),
|
||||
addSharedUsers: jest.fn(),
|
||||
create: jest.fn(),
|
||||
delete: jest.fn(),
|
||||
get: jest.fn(),
|
||||
getList: jest.fn(),
|
||||
removeAssets: jest.fn(),
|
||||
removeUser: jest.fn(),
|
||||
updateAlbum: jest.fn(),
|
||||
};
|
||||
sut = new AlbumService(albumRepositoryMock);
|
||||
});
|
||||
|
||||
it('creates album', async () => {
|
||||
const albumEntity = _getOwnedAlbum();
|
||||
albumRepositoryMock.create.mockImplementation(() => Promise.resolve<AlbumEntity>(albumEntity));
|
||||
|
||||
const result = await sut.create(authUser, {
|
||||
albumName: albumEntity.albumName,
|
||||
});
|
||||
|
||||
expect(result.id).toEqual(albumEntity.id);
|
||||
expect(result.albumName).toEqual(albumEntity.albumName);
|
||||
});
|
||||
|
||||
it('gets list of albums for auth user', async () => {
|
||||
const ownedAlbum = _getOwnedAlbum();
|
||||
const ownedSharedAlbum = _getOwnedSharedAlbum();
|
||||
const sharedWithMeAlbum = _getSharedWithAuthUserAlbum();
|
||||
const albums: AlbumEntity[] = [ownedAlbum, ownedSharedAlbum, sharedWithMeAlbum];
|
||||
|
||||
albumRepositoryMock.getList.mockImplementation(() => Promise.resolve(albums));
|
||||
|
||||
const result = await sut.getAllAlbums(authUser, {});
|
||||
expect(result).toHaveLength(3);
|
||||
expect(result[0].id).toEqual(ownedAlbum.id);
|
||||
expect(result[1].id).toEqual(ownedSharedAlbum.id);
|
||||
expect(result[2].id).toEqual(sharedWithMeAlbum.id);
|
||||
});
|
||||
|
||||
it('gets an owned album', async () => {
|
||||
const ownerId = authUser.id;
|
||||
const albumId = '0001';
|
||||
|
||||
const albumEntity = _getOwnedAlbum();
|
||||
albumRepositoryMock.get.mockImplementation(() => Promise.resolve<AlbumEntity>(albumEntity));
|
||||
|
||||
const expectedResult: AlbumResponseDto = {
|
||||
albumName: 'name',
|
||||
albumThumbnailAssetId: undefined,
|
||||
createdAt: 'date',
|
||||
id: '0001',
|
||||
ownerId,
|
||||
shared: false,
|
||||
assets: [],
|
||||
sharedUsers: [],
|
||||
};
|
||||
await expect(sut.getAlbumInfo(authUser, albumId)).resolves.toEqual(expectedResult);
|
||||
});
|
||||
|
||||
it('gets a shared album', async () => {
|
||||
const albumEntity = _getSharedWithAuthUserAlbum();
|
||||
albumRepositoryMock.get.mockImplementation(() => Promise.resolve<AlbumEntity>(albumEntity));
|
||||
|
||||
const result = await sut.getAlbumInfo(authUser, albumId);
|
||||
expect(result.id).toEqual(albumId);
|
||||
expect(result.ownerId).toEqual(sharedAlbumOwnerId);
|
||||
expect(result.shared).toEqual(true);
|
||||
expect(result.sharedUsers).toHaveLength(2);
|
||||
expect(result.sharedUsers[0].id).toEqual(authUser.id);
|
||||
expect(result.sharedUsers[1].id).toEqual(sharedAlbumSharedAlsoWithId);
|
||||
});
|
||||
|
||||
it('prevents retrieving an album that is not owned or shared', async () => {
|
||||
const albumEntity = _getNotOwnedNotSharedAlbum();
|
||||
const albumId = albumEntity.id;
|
||||
|
||||
albumRepositoryMock.get.mockImplementation(() => Promise.resolve<AlbumEntity>(albumEntity));
|
||||
await expect(sut.getAlbumInfo(authUser, albumId)).rejects.toBeInstanceOf(ForbiddenException);
|
||||
});
|
||||
|
||||
it('throws a not found exception if the album is not found', async () => {
|
||||
albumRepositoryMock.get.mockImplementation(() => Promise.resolve(undefined));
|
||||
await expect(sut.getAlbumInfo(authUser, '0002')).rejects.toBeInstanceOf(NotFoundException);
|
||||
});
|
||||
|
||||
it('deletes an owned album', async () => {
|
||||
const albumEntity = _getOwnedAlbum();
|
||||
albumRepositoryMock.get.mockImplementation(() => Promise.resolve<AlbumEntity>(albumEntity));
|
||||
albumRepositoryMock.delete.mockImplementation(() => Promise.resolve());
|
||||
await sut.deleteAlbum(authUser, albumId);
|
||||
expect(albumRepositoryMock.delete).toHaveBeenCalledTimes(1);
|
||||
expect(albumRepositoryMock.delete).toHaveBeenCalledWith(albumEntity);
|
||||
});
|
||||
|
||||
it('prevents deleting a shared album (shared with auth user)', async () => {
|
||||
const albumEntity = _getSharedWithAuthUserAlbum();
|
||||
albumRepositoryMock.get.mockImplementation(() => Promise.resolve<AlbumEntity>(albumEntity));
|
||||
await expect(sut.deleteAlbum(authUser, albumId)).rejects.toBeInstanceOf(ForbiddenException);
|
||||
});
|
||||
|
||||
it('removes a shared user from an owned album', async () => {
|
||||
const albumEntity = _getOwnedSharedAlbum();
|
||||
albumRepositoryMock.get.mockImplementation(() => Promise.resolve<AlbumEntity>(albumEntity));
|
||||
albumRepositoryMock.removeUser.mockImplementation(() => Promise.resolve());
|
||||
await expect(sut.removeUserFromAlbum(authUser, albumEntity.id, ownedAlbumSharedWithId)).resolves.toBeUndefined();
|
||||
expect(albumRepositoryMock.removeUser).toHaveBeenCalledTimes(1);
|
||||
expect(albumRepositoryMock.removeUser).toHaveBeenCalledWith(albumEntity, ownedAlbumSharedWithId);
|
||||
});
|
||||
|
||||
it('prevents removing a shared user from a not owned album (shared with auth user)', async () => {
|
||||
const albumEntity = _getSharedWithAuthUserAlbum();
|
||||
const albumId = albumEntity.id;
|
||||
const userIdToRemove = sharedAlbumSharedAlsoWithId;
|
||||
|
||||
albumRepositoryMock.get.mockImplementation(() => Promise.resolve<AlbumEntity>(albumEntity));
|
||||
|
||||
await expect(sut.removeUserFromAlbum(authUser, albumId, userIdToRemove)).rejects.toBeInstanceOf(ForbiddenException);
|
||||
expect(albumRepositoryMock.removeUser).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('removes itself from a shared album', async () => {
|
||||
const albumEntity = _getSharedWithAuthUserAlbum();
|
||||
albumRepositoryMock.get.mockImplementation(() => Promise.resolve<AlbumEntity>(albumEntity));
|
||||
albumRepositoryMock.removeUser.mockImplementation(() => Promise.resolve());
|
||||
|
||||
await sut.removeUserFromAlbum(authUser, albumEntity.id, authUser.id);
|
||||
expect(albumRepositoryMock.removeUser).toHaveReturnedTimes(1);
|
||||
expect(albumRepositoryMock.removeUser).toHaveBeenCalledWith(albumEntity, authUser.id);
|
||||
});
|
||||
|
||||
it('removes itself from a shared album using "me" as id', async () => {
|
||||
const albumEntity = _getSharedWithAuthUserAlbum();
|
||||
albumRepositoryMock.get.mockImplementation(() => Promise.resolve<AlbumEntity>(albumEntity));
|
||||
albumRepositoryMock.removeUser.mockImplementation(() => Promise.resolve());
|
||||
|
||||
await sut.removeUserFromAlbum(authUser, albumEntity.id, 'me');
|
||||
expect(albumRepositoryMock.removeUser).toHaveReturnedTimes(1);
|
||||
expect(albumRepositoryMock.removeUser).toHaveBeenCalledWith(albumEntity, authUser.id);
|
||||
});
|
||||
|
||||
it('prevents removing itself from a owned album', async () => {
|
||||
const albumEntity = _getOwnedAlbum();
|
||||
albumRepositoryMock.get.mockImplementation(() => Promise.resolve<AlbumEntity>(albumEntity));
|
||||
|
||||
await expect(sut.removeUserFromAlbum(authUser, albumEntity.id, authUser.id)).rejects.toBeInstanceOf(
|
||||
BadRequestException,
|
||||
);
|
||||
});
|
||||
|
||||
it('updates a owned album', async () => {
|
||||
const albumEntity = _getOwnedAlbum();
|
||||
const albumId = albumEntity.id;
|
||||
const updatedAlbumName = 'new album name';
|
||||
|
||||
albumRepositoryMock.get.mockImplementation(() => Promise.resolve<AlbumEntity>(albumEntity));
|
||||
albumRepositoryMock.updateAlbum.mockImplementation(() =>
|
||||
Promise.resolve<AlbumEntity>({ ...albumEntity, albumName: updatedAlbumName }),
|
||||
);
|
||||
|
||||
const result = await sut.updateAlbumTitle(
|
||||
authUser,
|
||||
{
|
||||
albumName: updatedAlbumName,
|
||||
ownerId: 'this is not used and will be removed',
|
||||
},
|
||||
albumId,
|
||||
);
|
||||
|
||||
expect(result.id).toEqual(albumId);
|
||||
expect(result.albumName).toEqual(updatedAlbumName);
|
||||
expect(albumRepositoryMock.updateAlbum).toHaveBeenCalledTimes(1);
|
||||
expect(albumRepositoryMock.updateAlbum).toHaveBeenCalledWith(albumEntity, {
|
||||
albumName: updatedAlbumName,
|
||||
ownerId: 'this is not used and will be removed',
|
||||
});
|
||||
});
|
||||
|
||||
it('prevents updating a not owned album (shared with auth user)', async () => {
|
||||
const albumEntity = _getSharedWithAuthUserAlbum();
|
||||
const albumId = albumEntity.id;
|
||||
|
||||
albumRepositoryMock.get.mockImplementation(() => Promise.resolve<AlbumEntity>(albumEntity));
|
||||
|
||||
await expect(
|
||||
sut.updateAlbumTitle(
|
||||
authUser,
|
||||
{
|
||||
albumName: 'new album name',
|
||||
ownerId: 'this is not used and will be removed',
|
||||
},
|
||||
albumId,
|
||||
),
|
||||
).rejects.toBeInstanceOf(ForbiddenException);
|
||||
});
|
||||
|
||||
it('adds assets to owned album', async () => {
|
||||
const albumEntity = _getOwnedAlbum();
|
||||
const albumId = albumEntity.id;
|
||||
|
||||
albumRepositoryMock.get.mockImplementation(() => Promise.resolve<AlbumEntity>(albumEntity));
|
||||
albumRepositoryMock.addAssets.mockImplementation(() => Promise.resolve<AlbumEntity>(albumEntity));
|
||||
|
||||
const result = await sut.addAssetsToAlbum(
|
||||
authUser,
|
||||
{
|
||||
assetIds: ['1'],
|
||||
},
|
||||
albumId,
|
||||
);
|
||||
|
||||
// TODO: stub and expect album rendered
|
||||
expect(result.id).toEqual(albumId);
|
||||
});
|
||||
|
||||
it('adds assets to shared album (shared with auth user)', async () => {
|
||||
const albumEntity = _getSharedWithAuthUserAlbum();
|
||||
const albumId = albumEntity.id;
|
||||
|
||||
albumRepositoryMock.get.mockImplementation(() => Promise.resolve<AlbumEntity>(albumEntity));
|
||||
albumRepositoryMock.addAssets.mockImplementation(() => Promise.resolve<AlbumEntity>(albumEntity));
|
||||
|
||||
const result = await sut.addAssetsToAlbum(
|
||||
authUser,
|
||||
{
|
||||
assetIds: ['1'],
|
||||
},
|
||||
albumId,
|
||||
);
|
||||
|
||||
// TODO: stub and expect album rendered
|
||||
expect(result.id).toEqual(albumId);
|
||||
});
|
||||
|
||||
it('prevents adding assets to a not owned / shared album', async () => {
|
||||
const albumEntity = _getNotOwnedNotSharedAlbum();
|
||||
const albumId = albumEntity.id;
|
||||
|
||||
albumRepositoryMock.get.mockImplementation(() => Promise.resolve<AlbumEntity>(albumEntity));
|
||||
albumRepositoryMock.addAssets.mockImplementation(() => Promise.resolve<AlbumEntity>(albumEntity));
|
||||
|
||||
expect(
|
||||
sut.addAssetsToAlbum(
|
||||
authUser,
|
||||
{
|
||||
assetIds: ['1'],
|
||||
},
|
||||
albumId,
|
||||
),
|
||||
).rejects.toBeInstanceOf(ForbiddenException);
|
||||
});
|
||||
|
||||
it('removes assets from owned album', async () => {
|
||||
const albumEntity = _getOwnedAlbum();
|
||||
albumRepositoryMock.get.mockImplementation(() => Promise.resolve<AlbumEntity>(albumEntity));
|
||||
albumRepositoryMock.removeAssets.mockImplementation(() => Promise.resolve(true));
|
||||
|
||||
await expect(
|
||||
sut.removeAssetsFromAlbum(
|
||||
authUser,
|
||||
{
|
||||
assetIds: ['1'],
|
||||
},
|
||||
albumEntity.id,
|
||||
),
|
||||
).resolves.toBeUndefined();
|
||||
expect(albumRepositoryMock.removeAssets).toHaveBeenCalledTimes(1);
|
||||
expect(albumRepositoryMock.removeAssets).toHaveBeenCalledWith(albumEntity, {
|
||||
assetIds: ['1'],
|
||||
});
|
||||
});
|
||||
|
||||
it('removes assets from shared album (shared with auth user)', async () => {
|
||||
const albumEntity = _getOwnedSharedAlbum();
|
||||
albumRepositoryMock.get.mockImplementation(() => Promise.resolve<AlbumEntity>(albumEntity));
|
||||
albumRepositoryMock.removeAssets.mockImplementation(() => Promise.resolve(true));
|
||||
|
||||
await expect(
|
||||
sut.removeAssetsFromAlbum(
|
||||
authUser,
|
||||
{
|
||||
assetIds: ['1'],
|
||||
},
|
||||
albumEntity.id,
|
||||
),
|
||||
).resolves.toBeUndefined();
|
||||
expect(albumRepositoryMock.removeAssets).toHaveBeenCalledTimes(1);
|
||||
expect(albumRepositoryMock.removeAssets).toHaveBeenCalledWith(albumEntity, {
|
||||
assetIds: ['1'],
|
||||
});
|
||||
});
|
||||
|
||||
it('prevents removing assets from a not owned / shared album', async () => {
|
||||
const albumEntity = _getNotOwnedNotSharedAlbum();
|
||||
const albumId = albumEntity.id;
|
||||
|
||||
albumRepositoryMock.get.mockImplementation(() => Promise.resolve<AlbumEntity>(albumEntity));
|
||||
albumRepositoryMock.addAssets.mockImplementation(() => Promise.resolve<AlbumEntity>(albumEntity));
|
||||
|
||||
expect(
|
||||
sut.removeAssetsFromAlbum(
|
||||
authUser,
|
||||
{
|
||||
assetIds: ['1'],
|
||||
},
|
||||
albumId,
|
||||
),
|
||||
).rejects.toBeInstanceOf(ForbiddenException);
|
||||
});
|
||||
});
|
||||
113
server/apps/immich/src/api-v1/album/album.service.ts
Normal file
113
server/apps/immich/src/api-v1/album/album.service.ts
Normal file
@@ -0,0 +1,113 @@
|
||||
import { BadRequestException, Inject, Injectable, NotFoundException, ForbiddenException } from '@nestjs/common';
|
||||
import { AuthUserDto } from '../../decorators/auth-user.decorator';
|
||||
import { AddAssetsDto } from './dto/add-assets.dto';
|
||||
import { CreateAlbumDto } from './dto/create-album.dto';
|
||||
import { AlbumEntity } from '../../../../../libs/database/src/entities/album.entity';
|
||||
import { AddUsersDto } from './dto/add-users.dto';
|
||||
import { RemoveAssetsDto } from './dto/remove-assets.dto';
|
||||
import { UpdateAlbumDto } from './dto/update-album.dto';
|
||||
import { GetAlbumsDto } from './dto/get-albums.dto';
|
||||
import { AlbumResponseDto, mapAlbum } from './response-dto/album-response.dto';
|
||||
import { ALBUM_REPOSITORY, IAlbumRepository } from './album-repository';
|
||||
|
||||
@Injectable()
|
||||
export class AlbumService {
|
||||
constructor(@Inject(ALBUM_REPOSITORY) private _albumRepository: IAlbumRepository) {}
|
||||
|
||||
private async _getAlbum({
|
||||
authUser,
|
||||
albumId,
|
||||
validateIsOwner = true,
|
||||
}: {
|
||||
authUser: AuthUserDto;
|
||||
albumId: string;
|
||||
validateIsOwner?: boolean;
|
||||
}): Promise<AlbumEntity> {
|
||||
const album = await this._albumRepository.get(albumId);
|
||||
if (!album) {
|
||||
throw new NotFoundException('Album Not Found');
|
||||
}
|
||||
const isOwner = album.ownerId == authUser.id;
|
||||
|
||||
if (validateIsOwner && !isOwner) {
|
||||
throw new ForbiddenException('Unauthorized Album Access');
|
||||
} else if (!isOwner && !album.sharedUsers.some((user) => user.sharedUserId == authUser.id)) {
|
||||
throw new ForbiddenException('Unauthorized Album Access');
|
||||
}
|
||||
return album;
|
||||
}
|
||||
|
||||
async create(authUser: AuthUserDto, createAlbumDto: CreateAlbumDto): Promise<AlbumResponseDto> {
|
||||
const albumEntity = await this._albumRepository.create(authUser.id, createAlbumDto);
|
||||
return mapAlbum(albumEntity);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all shared album, including owned and shared one.
|
||||
* @param authUser AuthUserDto
|
||||
* @returns All Shared Album And Its Members
|
||||
*/
|
||||
async getAllAlbums(authUser: AuthUserDto, getAlbumsDto: GetAlbumsDto): Promise<AlbumResponseDto[]> {
|
||||
const albums = await this._albumRepository.getList(authUser.id, getAlbumsDto);
|
||||
return albums.map((album) => mapAlbum(album));
|
||||
}
|
||||
|
||||
async getAlbumInfo(authUser: AuthUserDto, albumId: string): Promise<AlbumResponseDto> {
|
||||
const album = await this._getAlbum({ authUser, albumId, validateIsOwner: false });
|
||||
return mapAlbum(album);
|
||||
}
|
||||
|
||||
async addUsersToAlbum(authUser: AuthUserDto, addUsersDto: AddUsersDto, albumId: string): Promise<AlbumResponseDto> {
|
||||
const album = await this._getAlbum({ authUser, albumId });
|
||||
const updatedAlbum = await this._albumRepository.addSharedUsers(album, addUsersDto);
|
||||
return mapAlbum(updatedAlbum);
|
||||
}
|
||||
|
||||
async deleteAlbum(authUser: AuthUserDto, albumId: string): Promise<void> {
|
||||
const album = await this._getAlbum({ authUser, albumId });
|
||||
await this._albumRepository.delete(album);
|
||||
}
|
||||
|
||||
async removeUserFromAlbum(authUser: AuthUserDto, albumId: string, userId: string | 'me'): Promise<void> {
|
||||
const sharedUserId = userId == 'me' ? authUser.id : userId;
|
||||
const album = await this._getAlbum({ authUser, albumId, validateIsOwner: false });
|
||||
if (album.ownerId != authUser.id && authUser.id != sharedUserId) {
|
||||
throw new ForbiddenException('Cannot remove a user from a album that is not owned');
|
||||
}
|
||||
if (album.ownerId == sharedUserId) {
|
||||
throw new BadRequestException('The owner of the album cannot be removed');
|
||||
}
|
||||
await this._albumRepository.removeUser(album, sharedUserId);
|
||||
}
|
||||
|
||||
// async removeUsersFromAlbum() {}
|
||||
|
||||
async removeAssetsFromAlbum(authUser: AuthUserDto, removeAssetsDto: RemoveAssetsDto, albumId: string): Promise<void> {
|
||||
const album = await this._getAlbum({ authUser, albumId });
|
||||
await this._albumRepository.removeAssets(album, removeAssetsDto);
|
||||
}
|
||||
|
||||
async addAssetsToAlbum(
|
||||
authUser: AuthUserDto,
|
||||
addAssetsDto: AddAssetsDto,
|
||||
albumId: string,
|
||||
): Promise<AlbumResponseDto> {
|
||||
const album = await this._getAlbum({ authUser, albumId, validateIsOwner: false });
|
||||
const updatedAlbum = await this._albumRepository.addAssets(album, addAssetsDto);
|
||||
return mapAlbum(updatedAlbum);
|
||||
}
|
||||
|
||||
async updateAlbumTitle(
|
||||
authUser: AuthUserDto,
|
||||
updateAlbumDto: UpdateAlbumDto,
|
||||
albumId: string,
|
||||
): Promise<AlbumResponseDto> {
|
||||
// TODO: this should not come from request DTO. To be removed from here and DTO
|
||||
// if (authUser.id != updateAlbumDto.ownerId) {
|
||||
// throw new BadRequestException('Unauthorized to change album info');
|
||||
// }
|
||||
const album = await this._getAlbum({ authUser, albumId });
|
||||
const updatedAlbum = await this._albumRepository.updateAlbum(album, updateAlbumDto);
|
||||
return mapAlbum(updatedAlbum);
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,6 @@
|
||||
import { IsNotEmpty } from 'class-validator';
|
||||
import { AssetEntity } from '../../asset/entities/asset.entity';
|
||||
|
||||
export class AddAssetsDto {
|
||||
@IsNotEmpty()
|
||||
albumId: string;
|
||||
|
||||
@IsNotEmpty()
|
||||
assetIds: string[];
|
||||
}
|
||||
@@ -1,9 +1,6 @@
|
||||
import { IsNotEmpty } from 'class-validator';
|
||||
|
||||
export class AddUsersDto {
|
||||
@IsNotEmpty()
|
||||
albumId: string;
|
||||
|
||||
@IsNotEmpty()
|
||||
sharedUserIds: string[];
|
||||
}
|
||||
12
server/apps/immich/src/api-v1/album/dto/create-album.dto.ts
Normal file
12
server/apps/immich/src/api-v1/album/dto/create-album.dto.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { IsNotEmpty, IsOptional } from 'class-validator';
|
||||
|
||||
export class CreateAlbumDto {
|
||||
@IsNotEmpty()
|
||||
albumName: string;
|
||||
|
||||
@IsOptional()
|
||||
sharedWithUserIds?: string[];
|
||||
|
||||
@IsOptional()
|
||||
assetIds?: string[];
|
||||
}
|
||||
21
server/apps/immich/src/api-v1/album/dto/get-albums.dto.ts
Normal file
21
server/apps/immich/src/api-v1/album/dto/get-albums.dto.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import { Transform } from 'class-transformer';
|
||||
import { IsOptional, IsBoolean } from 'class-validator';
|
||||
|
||||
export class GetAlbumsDto {
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
@Transform(({ value }) => {
|
||||
if (value == 'true') {
|
||||
return true;
|
||||
} else if (value == 'false') {
|
||||
return false;
|
||||
}
|
||||
return value;
|
||||
})
|
||||
/**
|
||||
* true: only shared albums
|
||||
* false: only non-shared own albums
|
||||
* undefined: shared and owned albums
|
||||
*/
|
||||
shared?: boolean;
|
||||
}
|
||||
@@ -1,9 +1,6 @@
|
||||
import { IsNotEmpty } from 'class-validator';
|
||||
|
||||
export class RemoveAssetsDto {
|
||||
@IsNotEmpty()
|
||||
albumId: string;
|
||||
|
||||
@IsNotEmpty()
|
||||
assetIds: string[];
|
||||
}
|
||||
@@ -1,9 +1,6 @@
|
||||
import { IsNotEmpty } from 'class-validator';
|
||||
|
||||
export class UpdateShareAlbumDto {
|
||||
@IsNotEmpty()
|
||||
albumId: string;
|
||||
|
||||
export class UpdateAlbumDto {
|
||||
@IsNotEmpty()
|
||||
albumName: string;
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { AlbumEntity } from '../../../../../../libs/database/src/entities/album.entity';
|
||||
import { User, mapUser } from '../../user/response-dto/user';
|
||||
import { AssetResponseDto, mapAsset } from '../../asset/response-dto/asset-response.dto';
|
||||
|
||||
export interface AlbumResponseDto {
|
||||
id: string;
|
||||
ownerId: string;
|
||||
albumName: string;
|
||||
createdAt: string;
|
||||
albumThumbnailAssetId: string | null;
|
||||
shared: boolean;
|
||||
sharedUsers: User[];
|
||||
assets: AssetResponseDto[];
|
||||
}
|
||||
|
||||
export function mapAlbum(entity: AlbumEntity): AlbumResponseDto {
|
||||
const sharedUsers = entity.sharedUsers?.map((userAlbum) => mapUser(userAlbum.userInfo)) || [];
|
||||
return {
|
||||
albumName: entity.albumName,
|
||||
albumThumbnailAssetId: entity.albumThumbnailAssetId,
|
||||
createdAt: entity.createdAt,
|
||||
id: entity.id,
|
||||
ownerId: entity.ownerId,
|
||||
sharedUsers,
|
||||
shared: sharedUsers.length > 0,
|
||||
assets: entity.assets?.map((assetAlbum) => mapAsset(assetAlbum.assetInfo)) || [],
|
||||
};
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user