From 261f36065ba23b78d240b1d03b4c232790655b27 Mon Sep 17 00:00:00 2001 From: Salvoxia Date: Wed, 31 Jul 2024 20:59:59 +0200 Subject: [PATCH 1/7] Added option -m/--mode to either cleanup all albums created by the script or delete all albums for that user --- immich_auto_album.py | 71 ++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 68 insertions(+), 3 deletions(-) diff --git a/immich_auto_album.py b/immich_auto_album.py index 88b62a3..6e6abba 100644 --- a/immich_auto_album.py +++ b/immich_auto_album.py @@ -15,6 +15,15 @@ def is_integer(str): except ValueError: return False +# Constants holding script run modes +# Creat albums based on folder names and script arguments +SCRIPT_MODE_CREATE = "CREATE" +# Create album names based on folder names, but delete these albums +SCRIPT_MODE_CLEANUP = "CLEANUP" +# Delete ALL albums +SCRIPT_MODE_DELETE_ALL = "DELETE_ALL" + + parser = argparse.ArgumentParser(description="Create Immich Albums from an external library path based on the top level folders", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("root_path", action='append', help="The external libarary's root path in Immich") parser.add_argument("api_url", help="The root API URL of immich, e.g. https://immich.mydomain.com/api/") @@ -28,6 +37,7 @@ parser.add_argument("-C", "--fetch-chunk-size", default=5000, type=int, help="Ma parser.add_argument("-l", "--log-level", default="INFO", choices=['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG'], help="Log level to use") parser.add_argument("-k", "--insecure", action="store_true", help="Set to true to ignore SSL verification") parser.add_argument("-i", "--ignore", default="", type=str, help="A string containing a list of folders, sub-folder sequences or file names separated by ':' that will be ignored.") +parser.add_argument("-m", "--mode", default=SCRIPT_MODE_CREATE, choices=[SCRIPT_MODE_CREATE, SCRIPT_MODE_CLEANUP, SCRIPT_MODE_DELETE_ALL], help="Mode for the script to run with. CREATE = Create albums based on folder names and provided arguments; CLEANUP = Create album nmaes based on current images and script arguments, but delete albums if they exist; DELETE_ALL = Delete all albums. If the mode is anything but CREATE, --unattended does not have any effect.") args = vars(parser.parse_args()) # set up logger to log in logfmt format logging.basicConfig(level=args["log_level"], stream=sys.stdout, format='time=%(asctime)s level=%(levelname)s msg=%(message)s') @@ -45,6 +55,12 @@ album_levels_range_arr = () album_level_separator = args["album_separator"] insecure = args["insecure"] ignore_albums = args["ignore"] +mode = args["mode"] + +# Override unattended if we're running in destructive mode +if mode != SCRIPT_MODE_CREATE: + unattended = False + logging.debug("root_path = %s", root_paths) logging.debug("root_url = %s", root_url) logging.debug("api_key = %s", api_key) @@ -219,7 +235,11 @@ def fetchAssetsMinorV106(): assets = [] # prepare request body body = {} - body['isNotInAlbum'] = 'true' + # only request images that are not in any album if we are running in CREATE mode, + # otherwise we need all images, even if they are part of an album + if mode == SCRIPT_MODE_CREATE: + body['isNotInAlbum'] = 'true' + # This API call allows a maximum page size of 1000 number_of_assets_to_fetch_per_request_search = min(1000, number_of_assets_to_fetch_per_request) body['size'] = number_of_assets_to_fetch_per_request_search @@ -246,7 +266,7 @@ def fetchAssetsMinorV106(): return assets -# Fetches assets from the Immich API +# Fetches albums from the Immich API # Takes different API versions into account for compatibility def fetchAlbums(): apiEndpoint = 'albums' @@ -257,6 +277,20 @@ def fetchAlbums(): r.raise_for_status() return r.json() +# Deletes an album identified by album['id'] +# Takes different API versions into account for compatibility +# Returns False if the album could not be deleted, otherwise True +def deleteAlbum(album): + apiEndpoint = 'albums' + if version['major'] == 1 and version['minor'] <= 105: + apiEndpoint = 'album' + logging.debug("Album ID = %s, Album Name = %s", album['id'], album['albumName']) + r = requests.delete(root_url+apiEndpoint+'/'+album['id'], **requests_kwargs) + if r.status_code not in [200, 201]: + logging.error("Error deleting album %s: %s", album['albumName'], r.reason) + return False + return True + # Creates an album with the provided name and returns the ID of the # created album def createAlbum(albumName): @@ -309,6 +343,19 @@ if root_url[-1] != '/': root_url = root_url + '/' version = fetchServerVersion() +# Special case: Run Mode DELETE_ALL albums +if mode == SCRIPT_MODE_DELETE_ALL: + albums = fetchAlbums() + logging.info("%d existing albums identified", len(albums)) + print("Going to delete ALL albums! Press enter to proceed, Ctrl+C to abort") + input() + cpt = 0 + for album in albums: + if deleteAlbum(album): + logging.info("Deleted album %s", album['albumName']) + cpt += 1 + logging.info("Deleted %d/%d albums", cpt, len(albums)) + exit(0) logging.info("Requesting all assets") assets = fetchAssets() @@ -353,7 +400,10 @@ album_to_assets = {k:v for k, v in sorted(album_to_assets.items(), key=(lambda i logging.info("%d albums identified", len(album_to_assets)) logging.info("Album list: %s", list(album_to_assets.keys())) if not unattended: - print("Press Enter to continue, Ctrl+C to abort") + userHint = "Press enter to create these albums, Ctrl+C to abort" + if mode != SCRIPT_MODE_CREATE: + userHint = "Attention! Press enter to DELETE these albums (if they exist), Ctrl+C to abort" + print(userHint) input() @@ -365,7 +415,22 @@ albums = fetchAlbums() album_to_id = {album['albumName']:album['id'] for album in albums } logging.info("%d existing albums identified", len(albums)) +# mode CLEANUP +if mode == SCRIPT_MODE_CLEANUP: + cpt = 0 + for album in album_to_assets: + if album in album_to_id: + album_to_delete = dict() + album_to_delete['id'] = album_to_id[album] + album_to_delete['albumName'] = album + if deleteAlbum(album_to_delete): + logging.info("Deleted album %s", album_to_delete['albumName']) + cpt += 1 + logging.info("Deleted %d/%d albums", cpt, len(album_to_assets)) + exit(0) + +# mode CREATE logging.info("Creating albums if needed") cpt = 0 for album in album_to_assets: From b46c7ef9e62fc8900cb499aee12739dda71b7638 Mon Sep 17 00:00:00 2001 From: Salvoxia Date: Wed, 31 Jul 2024 21:08:08 +0200 Subject: [PATCH 2/7] README Added documentation for new -m/--mode option --- README.md | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index eb45896..732f069 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,8 @@ pip3 install -r requirements.txt ``` 3. Run the script ``` -usage: immich_auto_album.py [-h] [-r ROOT_PATH] [-u] [-a ALBUM_LEVELS] [-s ALBUM_SEPARATOR] [-c CHUNK_SIZE] [-C FETCH_CHUNK_SIZE] [-l {CRITICAL,ERROR,WARNING,INFO,DEBUG}] [-k] [-i IGNORE] root_path api_url api_key +usage: immich_auto_album.py [-h] [-r ROOT_PATH] [-u] [-a ALBUM_LEVELS] [-s ALBUM_SEPARATOR] [-c CHUNK_SIZE] [-C FETCH_CHUNK_SIZE] [-l {CRITICAL,ERROR,WARNING,INFO,DEBUG}] [-k] [-i IGNORE] [-m {CREATE,CLEANUP,DELETE_ALL}] + root_path api_url api_key Create Immich Albums from an external library path based on the top level folders @@ -43,8 +44,8 @@ options: Additional external libarary root path in Immich; May be specified multiple times for multiple import paths or external libraries. (default: None) -u, --unattended Do not ask for user confirmation after identifying albums. Set this flag to run script as a cronjob. (default: False) -a ALBUM_LEVELS, --album-levels ALBUM_LEVELS - Number of sub-folders or range of sub-folder levels below the root path used for album name creation. Positive numbers start from top of the folder structure, negative numbers from the bottom. Cannot be 0. If a range should be set, the - start level and end level must be separated by a comma like ','. If negative levels are used in a range, must be less than or equal to . (default: 1) + Number of sub-folders or range of sub-folder levels below the root path used for album name creation. Positive numbers start from top of the folder structure, negative numbers from the bottom. Cannot be 0. If a range + should be set, the start level and end level must be separated by a comma like ','. If negative levels are used in a range, must be less than or equal to . (default: 1) -s ALBUM_SEPARATOR, --album-separator ALBUM_SEPARATOR Separator string to use for compound album names created from nested folders. Only effective if -a is set to a value > 1 (default: ) -c CHUNK_SIZE, --chunk-size CHUNK_SIZE @@ -56,6 +57,13 @@ options: -k, --insecure Set to true to ignore SSL verification (default: False) -i IGNORE, --ignore IGNORE A string containing a list of folders, sub-folder sequences or file names separated by ':' that will be ignored. (default: ) + -m {CREATE,CLEANUP,DELETE_ALL}, --mode {CREATE,CLEANUP,DELETE_ALL} + Mode for the script to run with. + CREATE = Create albums based on folder names and provided arguments; + CLEANUP = Create album nmaes based on current images and script arguments, but delete albums if they exist; + DELETE_ALL = Delete all albums. + If the mode is anything but CREATE, --unattended does not have any effect. + (default: CREATE) ``` __Plain example without optional arguments:__ @@ -87,6 +95,7 @@ The environment variables are analoguous to the script's command line arguments. | LOG_LEVEL | no | Log level to use (default: INFO), allowed values: CRITICAL,ERROR,WARNING,INFO,DEBUG | | INSECURE | no | Set to `true` to disable SSL verification for the Immich API server, useful for self-signed certificates (default: `false`), allowed values: `true`, `false` | | INSECURE | no | A string containing a list of folders, sub-folder sequences or file names separated by ':' that will be ignored. | +| MODE | no | Mode for the script to run with.
__CREATE__ = Create albums based on folder names and provided arguments
__CLEANUP__ = Create album nmaes based on current images and script arguments, but delete albums if they exist
__DELETE_ALL__ = Delete all albums.
If the mode is anything but CREATE, --unattended does not have any effect.
(default: CREATE) | #### Run the container with Docker From a62a6d4faf5190ed2870efbbb55205cccb7a18e7 Mon Sep 17 00:00:00 2001 From: Salvoxia Date: Fri, 2 Aug 2024 19:34:24 +0200 Subject: [PATCH 3/7] Added new option -d/--delete-confirm to confirm album deletion in CLEANUP and DELETE_ALL modes --- immich_auto_album.py | 32 +++++++++++++++++++++++--------- 1 file changed, 23 insertions(+), 9 deletions(-) diff --git a/immich_auto_album.py b/immich_auto_album.py index 6e6abba..b69af71 100644 --- a/immich_auto_album.py +++ b/immich_auto_album.py @@ -1,3 +1,4 @@ + import requests import argparse import logging @@ -37,7 +38,8 @@ parser.add_argument("-C", "--fetch-chunk-size", default=5000, type=int, help="Ma parser.add_argument("-l", "--log-level", default="INFO", choices=['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG'], help="Log level to use") parser.add_argument("-k", "--insecure", action="store_true", help="Set to true to ignore SSL verification") parser.add_argument("-i", "--ignore", default="", type=str, help="A string containing a list of folders, sub-folder sequences or file names separated by ':' that will be ignored.") -parser.add_argument("-m", "--mode", default=SCRIPT_MODE_CREATE, choices=[SCRIPT_MODE_CREATE, SCRIPT_MODE_CLEANUP, SCRIPT_MODE_DELETE_ALL], help="Mode for the script to run with. CREATE = Create albums based on folder names and provided arguments; CLEANUP = Create album nmaes based on current images and script arguments, but delete albums if they exist; DELETE_ALL = Delete all albums. If the mode is anything but CREATE, --unattended does not have any effect.") +parser.add_argument("-m", "--mode", default=SCRIPT_MODE_CREATE, choices=[SCRIPT_MODE_CREATE, SCRIPT_MODE_CLEANUP, SCRIPT_MODE_DELETE_ALL], help="Mode for the script to run with. CREATE = Create albums based on folder names and provided arguments; CLEANUP = Create album nmaes based on current images and script arguments, but delete albums if they exist; DELETE_ALL = Delete all albums. If the mode is anything but CREATE, --unattended does not have any effect. Only performs deletion if -d/--delete-confirm option is set, otherwise only performs a dry-run.") +parser.add_argument("-d", "--delete-confirm", action="store_true", help="Confirm deletion of albums when running in mode"+SCRIPT_MODE_CLEANUP+" or "+SCRIPT_MODE_DELETE_ALL+". If this flag is not set, these modes will perform a dry run only. Has no effect in mode "+SCRIPT_MODE_CREATE) args = vars(parser.parse_args()) # set up logger to log in logfmt format logging.basicConfig(level=args["log_level"], stream=sys.stdout, format='time=%(asctime)s level=%(levelname)s msg=%(message)s') @@ -56,6 +58,7 @@ album_level_separator = args["album_separator"] insecure = args["insecure"] ignore_albums = args["ignore"] mode = args["mode"] +delete_confirm = args["delete_confirm"] # Override unattended if we're running in destructive mode if mode != SCRIPT_MODE_CREATE: @@ -72,6 +75,8 @@ logging.debug("album_levels = %s", album_levels) logging.debug("album_level_separator = %s", album_level_separator) logging.debug("insecure = %s", insecure) logging.debug("ignore = %s", ignore_albums) +logging.debug("mode = %s", mode) +logging.debug("delete_confirm = %s", delete_confirm) # Verify album levels if is_integer(album_levels) and album_levels == 0: @@ -347,8 +352,14 @@ version = fetchServerVersion() if mode == SCRIPT_MODE_DELETE_ALL: albums = fetchAlbums() logging.info("%d existing albums identified", len(albums)) - print("Going to delete ALL albums! Press enter to proceed, Ctrl+C to abort") - input() + # Delete Confirm check + if not delete_confirm: + album_names = [] + for album in albums: + album_names.append(album['albumName']) + print("Would delete the following albums (ALL albums!). Call with --delete-confirm to actually delete albums!") + print(album_names) + exit(0) cpt = 0 for album in albums: if deleteAlbum(album): @@ -399,13 +410,10 @@ album_to_assets = {k:v for k, v in sorted(album_to_assets.items(), key=(lambda i logging.info("%d albums identified", len(album_to_assets)) logging.info("Album list: %s", list(album_to_assets.keys())) -if not unattended: - userHint = "Press enter to create these albums, Ctrl+C to abort" - if mode != SCRIPT_MODE_CREATE: - userHint = "Attention! Press enter to DELETE these albums (if they exist), Ctrl+C to abort" - print(userHint) - input() +if not unattended and mode == SCRIPT_MODE_CREATE: + print("Press enter to create these albums, Ctrl+C to abort") + input() album_to_id = {} @@ -417,6 +425,12 @@ logging.info("%d existing albums identified", len(albums)) # mode CLEANUP if mode == SCRIPT_MODE_CLEANUP: + # Delete Confirm check + if not delete_confirm: + print("Would delete the following albums. Call with --delete-confirm to actually delete albums!") + print(list(album_to_id.keys())) + exit(0) + cpt = 0 for album in album_to_assets: if album in album_to_id: From 06ccbc728c8e85f2e250309f753db5d7dbb8e5e9 Mon Sep 17 00:00:00 2001 From: Salvoxia Date: Fri, 2 Aug 2024 19:35:31 +0200 Subject: [PATCH 4/7] Cron Call the script with env variable UNATTENDED set to 1 --- docker/setup_cron.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docker/setup_cron.sh b/docker/setup_cron.sh index ac5c831..114b673 100644 --- a/docker/setup_cron.sh +++ b/docker/setup_cron.sh @@ -1,7 +1,7 @@ #!/usr/bin/env sh if [ ! -z "$CRON_EXPRESSION" ]; then - CRONTAB="$CRON_EXPRESSION /script/immich_auto_album.sh > /proc/1/fd/1 2>/proc/1/fd/2" + CRONTAB="$CRON_EXPRESSION UNATTENDED=1 /script/immich_auto_album.sh > /proc/1/fd/1 2>/proc/1/fd/2" # Reset crontab crontab -r (crontab -l 2>/dev/null; echo "$CRONTAB") | crontab - From 2991df8a04df2dba12d37baaf0e39290fe5f5537 Mon Sep 17 00:00:00 2001 From: Salvoxia Date: Fri, 2 Aug 2024 19:36:05 +0200 Subject: [PATCH 5/7] Added support for MODE and DELETE_CONFIRM environment variables to Docker --- docker/immich_auto_album.sh | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/docker/immich_auto_album.sh b/docker/immich_auto_album.sh index 2fef497..069bb76 100644 --- a/docker/immich_auto_album.sh +++ b/docker/immich_auto_album.sh @@ -12,7 +12,12 @@ for path in ${root_paths}; do fi done -args="-u $main_root_path $API_URL $API_KEY" +unattended= +if [ ! -z "$UNATTENDED" ]; then + unattended="-u" +fi + +args="$unattended $main_root_path $API_URL $API_KEY" if [ ! -z "$additional_root_paths" ]; then args="$additional_root_paths $args" @@ -46,6 +51,13 @@ if [ ! -z "$IGNORE" ]; then args="-i \"$IGNORE\" $args" fi +if [ ! -z "$MODE" ]; then + args="-m \"$MODE\" $args" +fi + +if [ ! -z "$DELETE_CONFIRM" ]; then + args="-d $args" +fi BASEDIR=$(dirname "$0") echo $args | xargs python3 -u $BASEDIR/immich_auto_album.py \ No newline at end of file From 158182ef2efcef1308dbaf5bdbaafdb749ddc18c Mon Sep 17 00:00:00 2001 From: Salvoxia Date: Fri, 2 Aug 2024 19:37:37 +0200 Subject: [PATCH 6/7] Fixed typo in argparse help --- immich_auto_album.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/immich_auto_album.py b/immich_auto_album.py index b69af71..a220987 100644 --- a/immich_auto_album.py +++ b/immich_auto_album.py @@ -39,7 +39,7 @@ parser.add_argument("-l", "--log-level", default="INFO", choices=['CRITICAL', 'E parser.add_argument("-k", "--insecure", action="store_true", help="Set to true to ignore SSL verification") parser.add_argument("-i", "--ignore", default="", type=str, help="A string containing a list of folders, sub-folder sequences or file names separated by ':' that will be ignored.") parser.add_argument("-m", "--mode", default=SCRIPT_MODE_CREATE, choices=[SCRIPT_MODE_CREATE, SCRIPT_MODE_CLEANUP, SCRIPT_MODE_DELETE_ALL], help="Mode for the script to run with. CREATE = Create albums based on folder names and provided arguments; CLEANUP = Create album nmaes based on current images and script arguments, but delete albums if they exist; DELETE_ALL = Delete all albums. If the mode is anything but CREATE, --unattended does not have any effect. Only performs deletion if -d/--delete-confirm option is set, otherwise only performs a dry-run.") -parser.add_argument("-d", "--delete-confirm", action="store_true", help="Confirm deletion of albums when running in mode"+SCRIPT_MODE_CLEANUP+" or "+SCRIPT_MODE_DELETE_ALL+". If this flag is not set, these modes will perform a dry run only. Has no effect in mode "+SCRIPT_MODE_CREATE) +parser.add_argument("-d", "--delete-confirm", action="store_true", help="Confirm deletion of albums when running in mode "+SCRIPT_MODE_CLEANUP+" or "+SCRIPT_MODE_DELETE_ALL+". If this flag is not set, these modes will perform a dry run only. Has no effect in mode "+SCRIPT_MODE_CREATE) args = vars(parser.parse_args()) # set up logger to log in logfmt format logging.basicConfig(level=args["log_level"], stream=sys.stdout, format='time=%(asctime)s level=%(levelname)s msg=%(message)s') From 1f0332f1217d9e28e05056dccdb0084286cee06f Mon Sep 17 00:00:00 2001 From: Salvoxia Date: Fri, 2 Aug 2024 19:52:39 +0200 Subject: [PATCH 7/7] README Restructured README and added table of contents Added documentation of new cleanup feature --- README.md | 122 +++++++++++++++++++++++++++++++----------------------- 1 file changed, 70 insertions(+), 52 deletions(-) diff --git a/README.md b/README.md index 732f069..78067b8 100644 --- a/README.md +++ b/README.md @@ -14,67 +14,65 @@ __Current compatibility:__ Immich v1.111.x and below ## Disclaimer This script is mostly based on the following original script: [REDVM/immich_auto_album.py](https://gist.github.com/REDVM/d8b3830b2802db881f5b59033cf35702) -## Installation +# Table of Contents +1. [Usage (Bare Python Script)](#bare-python-script) +2. [Usage (Docker)](#docker) +3. [Choosing the correct `root_path`](#choosing-the-correct-root_path) +4. [How It Works (with Examples)](#how-it-works) +5. [Cleaning Up Albums](#cleaning-up-albums) +## Usage ### Bare Python Script 1. Download the script and its requirements -```bash -curl https://raw.githubusercontent.com/Salvoxia/immich-folder-album-creator/main/immich_auto_album.py -o immich_auto_album.py -curl https://raw.githubusercontent.com/Salvoxia/immich-folder-album-creator/main/requirements.txt -o requirements.txt -``` + ```bash + curl https://raw.githubusercontent.com/Salvoxia/immich-folder-album-creator/main/immich_auto_album.py -o immich_auto_album.py + curl https://raw.githubusercontent.com/Salvoxia/immich-folder-album-creator/main/requirements.txt -o requirements.txt + ``` 2. Install requirements -```bash -pip3 install -r requirements.txt -``` + ```bash + pip3 install -r requirements.txt + ``` 3. Run the script -``` -usage: immich_auto_album.py [-h] [-r ROOT_PATH] [-u] [-a ALBUM_LEVELS] [-s ALBUM_SEPARATOR] [-c CHUNK_SIZE] [-C FETCH_CHUNK_SIZE] [-l {CRITICAL,ERROR,WARNING,INFO,DEBUG}] [-k] [-i IGNORE] [-m {CREATE,CLEANUP,DELETE_ALL}] - root_path api_url api_key + ``` + usage: immich_auto_album.py [-h] [-r ROOT_PATH] [-u] [-a ALBUM_LEVELS] [-s ALBUM_SEPARATOR] [-c CHUNK_SIZE] [-C FETCH_CHUNK_SIZE] [-l {CRITICAL,ERROR,WARNING,INFO,DEBUG}] [-k] [-i IGNORE] [-m {CREATE,CLEANUP,DELETE_ALL}] [-d] root_path api_url api_key -Create Immich Albums from an external library path based on the top level folders + Create Immich Albums from an external library path based on the top level folders -positional arguments: - root_path The external libarary's root path in Immich - api_url The root API URL of immich, e.g. https://immich.mydomain.com/api/ - api_key The Immich API Key to use + positional arguments: + root_path The external libarary's root path in Immich + api_url The root API URL of immich, e.g. https://immich.mydomain.com/api/ + api_key The Immich API Key to use -options: - -h, --help show this help message and exit - -r ROOT_PATH, --root-path ROOT_PATH - Additional external libarary root path in Immich; May be specified multiple times for multiple import paths or external libraries. (default: None) - -u, --unattended Do not ask for user confirmation after identifying albums. Set this flag to run script as a cronjob. (default: False) - -a ALBUM_LEVELS, --album-levels ALBUM_LEVELS - Number of sub-folders or range of sub-folder levels below the root path used for album name creation. Positive numbers start from top of the folder structure, negative numbers from the bottom. Cannot be 0. If a range - should be set, the start level and end level must be separated by a comma like ','. If negative levels are used in a range, must be less than or equal to . (default: 1) - -s ALBUM_SEPARATOR, --album-separator ALBUM_SEPARATOR - Separator string to use for compound album names created from nested folders. Only effective if -a is set to a value > 1 (default: ) - -c CHUNK_SIZE, --chunk-size CHUNK_SIZE - Maximum number of assets to add to an album with a single API call (default: 2000) - -C FETCH_CHUNK_SIZE, --fetch-chunk-size FETCH_CHUNK_SIZE - Maximum number of assets to fetch with a single API call (default: 5000) - -l {CRITICAL,ERROR,WARNING,INFO,DEBUG}, --log-level {CRITICAL,ERROR,WARNING,INFO,DEBUG} - Log level to use (default: INFO) - -k, --insecure Set to true to ignore SSL verification (default: False) - -i IGNORE, --ignore IGNORE - A string containing a list of folders, sub-folder sequences or file names separated by ':' that will be ignored. (default: ) - -m {CREATE,CLEANUP,DELETE_ALL}, --mode {CREATE,CLEANUP,DELETE_ALL} - Mode for the script to run with. - CREATE = Create albums based on folder names and provided arguments; - CLEANUP = Create album nmaes based on current images and script arguments, but delete albums if they exist; - DELETE_ALL = Delete all albums. - If the mode is anything but CREATE, --unattended does not have any effect. - (default: CREATE) -``` + options: + -h, --help show this help message and exit + -r ROOT_PATH, --root-path ROOT_PATH + Additional external libarary root path in Immich; May be specified multiple times for multiple import paths or external libraries. (default: None) + -u, --unattended Do not ask for user confirmation after identifying albums. Set this flag to run script as a cronjob. (default: False) + -a ALBUM_LEVELS, --album-levels ALBUM_LEVELS + Number of sub-folders or range of sub-folder levels below the root path used for album name creation. Positive numbers start from top of the folder structure, negative numbers from the bottom. Cannot be 0. If a range should be set, the + start level and end level must be separated by a comma like ','. If negative levels are used in a range, must be less than or equal to . (default: 1) + -s ALBUM_SEPARATOR, --album-separator ALBUM_SEPARATOR + Separator string to use for compound album names created from nested folders. Only effective if -a is set to a value > 1 (default: ) + -c CHUNK_SIZE, --chunk-size CHUNK_SIZE + Maximum number of assets to add to an album with a single API call (default: 2000) + -C FETCH_CHUNK_SIZE, --fetch-chunk-size FETCH_CHUNK_SIZE + Maximum number of assets to fetch with a single API call (default: 5000) + -l {CRITICAL,ERROR,WARNING,INFO,DEBUG}, --log-level {CRITICAL,ERROR,WARNING,INFO,DEBUG} + Log level to use (default: INFO) + -k, --insecure Set to true to ignore SSL verification (default: False) + -i IGNORE, --ignore IGNORE + A string containing a list of folders, sub-folder sequences or file names separated by ':' that will be ignored. (default: ) + -m {CREATE,CLEANUP,DELETE_ALL}, --mode {CREATE,CLEANUP,DELETE_ALL} + Mode for the script to run with. CREATE = Create albums based on folder names and provided arguments; CLEANUP = Create album nmaes based on current images and script arguments, but delete albums if they exist; DELETE_ALL = Delete all + albums. If the mode is anything but CREATE, --unattended does not have any effect. Only performs deletion if -d/--delete-confirm option is set, otherwise only performs a dry-run. (default: CREATE) + -d, --delete-confirm Confirm deletion of albums when running in mode CLEANUP or DELETE_ALL. If this flag is not set, these modes will perform a dry run only. Has no effect in mode CREATE (default: False) + ``` __Plain example without optional arguments:__ ```bash python3 ./immich_auto_album.py /path/to/external/lib https://immich.mydomain.com/api thisIsMyApiKeyCopiedFromImmichWebGui ``` -#### The `root_path` -The root path `/path/to/external/lib/` is the path you have mounted your external library into the Immich container. -If you are following [Immich's External library Documentation](https://immich.app/docs/guides/external-library), you are using an environment variable called `${EXTERNAL_PATH}` which is mounted to `/usr/src/app/external` in the Immich container. Your `root_path` to pass to the script is `/usr/src/app/external`. - ### Docker A Docker image is provided to be used as a runtime environment. It can be used to either run the script manually, or via cronjob by providing a crontab expression to the container. The container can then be added to the Immich compose stack directly. @@ -84,26 +82,30 @@ The environment variables are analoguous to the script's command line arguments. | Environment varible | Mandatory? | Description | | :------------------- | :----------- | :------------ | -| ROOT_PATH | yes | A single or a comma separated list of import paths for external libraries in Immich. Refer to [The root_path](#the-root_path)| +| ROOT_PATH | yes | A single or a comma separated list of import paths for external libraries in Immich.
Refer to [Choosing the correct `root_path`](#choosing-the-correct-root_path).| | API_URL | yes | The root API URL of immich, e.g. https://immich.mydomain.com/api/ | | API_KEY | yes | The Immich API Key to use | CRON_EXPRESSION | yes | A [crontab-style expression](https://crontab.guru/) (e.g. "0 * * * *") to perform album creation on a schedule (e.g. every hour). | -| ALBUM_LEVELS | no | Number of sub-folders or range of sub-folder levels below the root path used for album name creation. Positive numbers start from top of the folder structure, negative numbers from the bottom. Cannot be 0. If a range should be set, the start level and end level must be separated by a comma. Refer to [How it works](#how-it-works) for a detailed explanation | +| ALBUM_LEVELS | no | Number of sub-folders or range of sub-folder levels below the root path used for album name creation. Positive numbers start from top of the folder structure, negative numbers from the bottom. Cannot be 0. If a range should be set, the start level and end level must be separated by a comma.
Refer to [How it works](#how-it-works) for a detailed explanation and examples. | | ALBUM_SEPARATOR | no | Separator string to use for compound album names created from nested folders. Only effective if -a is set to a value > 1 (default: " ") | | CHUNK_SIZE | no | Maximum number of assets to add to an album with a single API call (default: 2000) | | FETCH_CHUNK_SIZE | no | Maximum number of assets to fetch with a single API call (default: 5000) | | LOG_LEVEL | no | Log level to use (default: INFO), allowed values: CRITICAL,ERROR,WARNING,INFO,DEBUG | | INSECURE | no | Set to `true` to disable SSL verification for the Immich API server, useful for self-signed certificates (default: `false`), allowed values: `true`, `false` | | INSECURE | no | A string containing a list of folders, sub-folder sequences or file names separated by ':' that will be ignored. | -| MODE | no | Mode for the script to run with.
__CREATE__ = Create albums based on folder names and provided arguments
__CLEANUP__ = Create album nmaes based on current images and script arguments, but delete albums if they exist
__DELETE_ALL__ = Delete all albums.
If the mode is anything but CREATE, --unattended does not have any effect.
(default: CREATE) | +| MODE | no | Mode for the script to run with.
__CREATE__ = Create albums based on folder names and provided arguments
__CLEANUP__ = Create album nmaes based on current images and script arguments, but delete albums if they exist
__DELETE_ALL__ = Delete all albums.
If the mode is anything but CREATE, `--unattended` does not have any effect.
(default: CREATE).
Refer to [Cleaning Up Albums](#cleaning-up-albums). | +| DELETE_CONFIRM | no | Confirm deletion of albums when running in mode CLEANUP or DELETE_ALL. If this flag is not set, these modes will perform a dry run only. Has no effect in mode CREATE (default: False).
Refer to [Cleaning Up Albums](#cleaning-up-albums).| #### Run the container with Docker -To perform a manually triggered run, use the following command: - +To perform a manually triggered __dry run__ (only list albums that __would__ be created), use the following command: ```bash docker run -e API_URL="https://immich.mydomain.com/api/" -e API_KEY="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" -e ROOT_PATH="/external_libs/photos" salvoxia/immich-folder-album-creator:latest /script/immich_auto_album.sh ``` +To actually create albums after performing a dry run, use the following command (setting the `UNATTENDED` environment variable): +```bash +docker run -e UNATTENDED="1" -e API_URL="https://immich.mydomain.com/api/" -e API_KEY="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" -e ROOT_PATH="/external_libs/photos" salvoxia/immich-folder-album-creator:latest /script/immich_auto_album.sh +``` To set up the container to periodically run the script, give it a name, pass the TZ variable and a valid crontab expression as environment variable. This example runs the script every hour: ```bash @@ -150,6 +152,10 @@ services: ``` +## Choosing the correct `root_path` +The root path `/path/to/external/lib/` is the path you have mounted your external library into the Immich container. +If you are following [Immich's External library Documentation](https://immich.app/docs/guides/external-library), you are using an environment variable called `${EXTERNAL_PATH}` which is mounted to `/usr/src/app/external` in the Immich container. Your `root_path` to pass to the script is `/usr/src/app/external`. + ## How it works The script utilizies [Immich's REST API](https://immich.app/docs/api/) to query all images indexed by Immich, extract the folder for all images that are in the top level of any provided `root_path`, then creates albums with the names of these folders (if not yet exists) and adds the images to the correct albums. @@ -234,3 +240,15 @@ Albums created for `root_path = /external_libs/photos/Birthdays`: Since Immich does not support real nested albums ([yet?](https://github.com/immich-app/immich/discussions/2073)), neither does this script. +## Cleaning Up Albums + +The script supports differnt run modes (option -m/--mode or env variable `MODE` for Docker). The default mode is `CREATE`, which is used to create albums. +The other two modes are `CLEANUP` and `DELETE_ALL`: + - `CLEANUP`: The script will generate album names using the script's arguments and the assets found in Immich, but instead of creating the albums, it will delete them (if they exist). This is useful if a large number of albums was created with no/the wrong `--album-separator` or `--album-levels` settings. + - `DELETE_ALL`: ⚠️ As the name suggests, this mode blindly deletes ALL albums from Immich. Use with caution! + +To prevent accidental deletions, setting the mode to `CLEANUP` or `DELETE_ALL` alone will not actually delete any albums, but only perform a dry run. The dry run prints a list of albums that the script __would__ delete. +To actually delete albums, the option `-d/--delete-confirm` (or env variable `DELETE_CONFIRM` for Docker) must be set. + +__WARNING ⚠️__ +Deleting albums cannot be undone! The only option is to let the script run again and create new albums base on the passed arguments and current assets in Immich. \ No newline at end of file