Skip to content

Commit 5874149

Browse files
authored
Merge pull request #74 from johnspade/api-key-file
Support file-based API key secrets
2 parents 7a517f0 + 0d8ce52 commit 5874149

File tree

3 files changed

+80
-31
lines changed

3 files changed

+80
-31
lines changed

README.md

Lines changed: 43 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -40,25 +40,29 @@ This script is mostly based on the following original script: [REDVM/immich_auto
4040
```
4141
3. Run the script
4242
```
43-
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] [-x SHARE_WITH] [-o {viewer,editor}] [-S {0,1,2}]
44-
[-O {False,asc,desc}] [-A] [-f PATH_FILTER] [--set-album-thumbnail {first,last,random,random-all,random-filtered}] [-v] [--find-archived-assets]
45-
root_path api_url api_key
43+
usage: immich_auto_album.py [-h] [-t {literal,file}] [-r ROOT_PATH] [-u] [-a ALBUM_LEVELS] [-s ALBUM_SEPARATOR] [-c CHUNK_SIZE] [-C FETCH_CHUNK_SIZE] [-l {CRITICAL,ERROR,WARNING,INFO,DEBUG}] [-k]
44+
[-i IGNORE] [-m {CREATE,CLEANUP,DELETE_ALL}] [-d] [-x SHARE_WITH] [-o {viewer,editor}] [-S {0,1,2}] [-O {False,asc,desc}] [-A] [-f PATH_FILTER]
45+
[--set-album-thumbnail {first,last,random,random-all,random-filtered}] [-v] [--find-archived-assets]
46+
root_path api_url api_key
4647

4748
Create Immich Albums from an external library path based on the top level folders
4849

4950
positional arguments:
50-
root_path The external libarary's root path in Immich
51+
root_path The external library's root path in Immich
5152
api_url The root API URL of immich, e.g. https://immich.mydomain.com/api/
52-
api_key The Immich API Key to use
53+
api_key The Immich API Key to use. Set --api-key-type to 'file' if a file path is provided.
5354
5455
options:
5556
-h, --help show this help message and exit
57+
-t {literal,file}, --api-key-type {literal,file}
58+
The type of the Immich API Key (default: literal)
5659
-r ROOT_PATH, --root-path ROOT_PATH
57-
Additional external libarary root path in Immich; May be specified multiple times for multiple import paths or external libraries. (default: None)
60+
Additional external library root path in Immich; May be specified multiple times for multiple import paths or external libraries. (default: None)
5861
-u, --unattended Do not ask for user confirmation after identifying albums. Set this flag to run script as a cronjob. (default: False)
5962
-a ALBUM_LEVELS, --album-levels ALBUM_LEVELS
60-
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
61-
must be separated by a comma like '<startLevel>,<endLevel>'. If negative levels are used in a range, <startLevel> must be less than or equal to <endLevel>. (default: 1)
63+
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
64+
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 '<startLevel>,<endLevel>'. If negative levels are used in
65+
a range, <startLevel> must be less than or equal to <endLevel>. (default: 1)
6266
-s ALBUM_SEPARATOR, --album-separator ALBUM_SEPARATOR
6367
Separator string to use for compound album names created from nested folders. Only effective if -a is set to a value > 1 (default: )
6468
-c CHUNK_SIZE, --chunk-size CHUNK_SIZE
@@ -69,30 +73,41 @@ This script is mostly based on the following original script: [REDVM/immich_auto
6973
Log level to use (default: INFO)
7074
-k, --insecure Set to true to ignore SSL verification (default: False)
7175
-i IGNORE, --ignore IGNORE
72-
Use either literals or glob-like patterns to ignore assets for album name creation. This filter is evaluated after any values passed with --path-filter. May be specified multiple times. (default: None)
76+
Use either literals or glob-like patterns to ignore assets for album name creation. This filter is evaluated after any values passed with --path-filter. May be specified
77+
multiple times. (default: None)
7378
-m {CREATE,CLEANUP,DELETE_ALL}, --mode {CREATE,CLEANUP,DELETE_ALL}
74-
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)
75-
-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)
79+
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,
80+
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
81+
-d/--delete-confirm option is set, otherwise only performs a dry-run. (default: CREATE)
82+
-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:
83+
False)
7684
-x SHARE_WITH, --share-with SHARE_WITH
77-
A user name (or email address of an existing user) to share newly created albums with. Sharing only happens if the album was actually created, not if new assets were added to an existing album. If the the share role should be specified by user, the format
78-
<userName>=<shareRole> must be used, where <shareRole> must be one of 'viewer' or 'editor'. May be specified multiple times to share albums with more than one user. (default: None)
85+
A user name (or email address of an existing user) to share newly created albums with. Sharing only happens if the album was actually created, not if new assets were added to an
86+
existing album. If the the share role should be specified by user, the format <userName>=<shareRole> must be used, where <shareRole> must be one of 'viewer' or 'editor'. May be
87+
specified multiple times to share albums with more than one user. (default: None)
7988
-o {viewer,editor}, --share-role {viewer,editor}
80-
The default share role for users newly created albums are shared with. Only effective if --share-with is specified at least once and the share role is not specified within --share-with. (default: viewer)
89+
The default share role for users newly created albums are shared with. Only effective if --share-with is specified at least once and the share role is not specified within
90+
--share-with. (default: viewer)
8191
-S {0,1,2}, --sync-mode {0,1,2}
82-
Synchronization mode to use. Synchronization mode helps synchronizing changes in external libraries structures to Immich after albums have already been created. Possible Modes: 0 = do nothing; 1 = Delete any empty albums; 2 = Delete offline assets AND any empty albums (default: 0)
92+
Synchronization mode to use. Synchronization mode helps synchronizing changes in external libraries structures to Immich after albums have already been created. Possible Modes:
93+
0 = do nothing; 1 = Delete any empty albums; 2 = Delete offline assets AND any empty albums (default: 0)
8394
-O {False,asc,desc}, --album-order {False,asc,desc}
8495
Set sorting order for newly created albums to newest or oldest file first, Immich defaults to newest file first (default: False)
8596
-A, --find-assets-in-albums
86-
By default, the script only finds assets that are not assigned to any album yet. Set this option to make the script discover assets that are already part of an album and handle them as usual. If --find-archived-assets is set as well, both options apply. (default:
87-
False)
97+
By default, the script only finds assets that are not assigned to any album yet. Set this option to make the script discover assets that are already part of an album and handle
98+
them as usual. If --find-archived-assets is set as well, both options apply. (default: False)
8899
-f PATH_FILTER, --path-filter PATH_FILTER
89-
Use either literals or glob-like patterns to filter assets before album name creation. This filter is evaluated before any values passed with --ignore. May be specified multiple times. (default: None)
100+
Use either literals or glob-like patterns to filter assets before album name creation. This filter is evaluated before any values passed with --ignore. May be specified multiple
101+
times. (default: None)
90102
--set-album-thumbnail {first,last,random,random-all,random-filtered}
91-
Set first/last/random image as thumbnail for newly created albums or albums assets have been added to. If set to random-filtered, thumbnails are shuffled for all albums whose assets would not be filtered out or ignored by the ignore or path-filter options, even if no assets were added during the run. If set to random-all, the thumbnails for ALL albums will be shuffled on every run. (default: None)
92-
-v, --archive Set this option to automatically archive all assets that were newly added to albums. If this option is set in combination with --mode = CLEANUP or DELETE_ALL, archived images of deleted albums will be unarchived. Archiving hides the assets from Immich's timeline.
93-
(default: False)
103+
Set first/last/random image as thumbnail for newly created albums or albums assets have been added to. If set to random-filtered, thumbnails are shuffled for all albums whose
104+
assets would not be filtered out or ignored by the ignore or path-filter options, even if no assets were added during the run. If set to random-all, the thumbnails for ALL
105+
albums will be shuffled on every run. (default: None)
106+
-v, --archive Set this option to automatically archive all assets that were newly added to albums. If this option is set in combination with --mode = CLEANUP or DELETE_ALL, archived images of
107+
deleted albums will be unarchived. Archiving hides the assets from Immich's timeline. (default: False)
94108
--find-archived-assets
95-
By default, the script only finds assets that are not archived in Immich. Set this option to make the script discover assets that are already archived. If -A/--find-assets-in-albums is set as well, both options apply. (default: False)
109+
By default, the script only finds assets that are not archived in Immich. Set this option to make the script discover assets that are already archived. If -A/--find-assets-in-
110+
albums is set as well, both options apply. (default: False)
96111
```
97112

98113
__Plain example without optional arguments:__
@@ -111,7 +126,8 @@ The environment variables are analoguous to the script's command line arguments.
111126
| :------------------- | :----------- | :------------ |
112127
| ROOT_PATH | yes | A single or a comma separated list of import paths for external libraries in Immich. <br>Refer to [Choosing the correct `root_path`](#choosing-the-correct-root_path).|
113128
| API_URL | yes | The root API URL of immich, e.g. https://immich.mydomain.com/api/ |
114-
| API_KEY | yes | The Immich API Key to use
129+
| API_KEY | no | The Immich API Key to use. Either `API_KEY` or `API_KEY_FILE` must be specified. The `API_KEY` variable takes precedence for ease of manual execution, but it is recommended to use `API_KEY_FILE`.
130+
| API_KEY_FILE | no | An absolute path (from the root of the container) to a file containing the Immich API Key. The file might be mounted into the container using a volume (e.g. `-v /path/to/api_key.secret:/immich_api_key.secret:ro`). The file must contain only the value. |
115131
| CRON_EXPRESSION | yes | A [crontab-style expression](https://crontab.guru/) (e.g. `0 * * * *`) to perform album creation on a schedule (e.g. every hour). |
116132
| 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. <br>Refer to [How it works](#how-it-works) for a detailed explanation and examples. |
117133
| 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: "` `") |
@@ -172,14 +188,15 @@ services:
172188
container_name: immich_server
173189
volumes:
174190
- /path/to/my/photos:/external_libs/photos
191+
- /path/to/secret/file:/immich_api_key.secret:ro
175192
...
176193
immich-folder-album-creator:
177194
container_name: immich_folder_album_creator
178195
image: salvoxia/immich-folder-album-creator:latest
179196
restart: unless-stopped
180197
environment:
181198
API_URL: http://immich_server:2283/api
182-
API_KEY: xxxxxxxxxxxxxxxxx
199+
API_KEY_FILE: /immich_api_key.secret
183200
ROOT_PATH: /external_libs/photos
184201
CRON_EXPRESSION: "0 * * * *"
185202
TZ: Europe/Berlin
@@ -479,14 +496,15 @@ services:
479496
container_name: immich_server
480497
volumes:
481498
- /path/to/my/photos:/external_libs/photos
499+
- /path/to/secret/file:/immich_api_key.secret:ro
482500
...
483501
immich-folder-album-creator:
484502
container_name: immich_folder_album_creator
485503
image: salvoxia/immich-folder-album-creator:latest
486504
restart: unless-stopped
487505
environment:
488506
API_URL: http://immich_server:2283/api
489-
API_KEY: xxxxxxxxxxxxxxxxx
507+
API_KEY_FILE: "/immich_api_key.secret"
490508
ROOT_PATH: /external_libs/photos
491509
CRON_EXPRESSION: "0 * * * *"
492510
TZ: Europe/Berlin

docker/immich_auto_album.sh

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,18 @@ if [ ! -z "$UNATTENDED" ]; then
5252
unattended="--unattended"
5353
fi
5454

55-
args="$unattended $main_root_path $API_URL $API_KEY"
55+
api_key=""
56+
api_key_type=""
57+
58+
if [ ! -z "$API_KEY" ]; then
59+
api_key=$API_KEY
60+
api_key_type="--api-key-type literal"
61+
elif [ ! -z "$API_KEY_FILE" ]; then
62+
api_key=$API_KEY_FILE
63+
api_key_type="--api-key-type file"
64+
fi
65+
66+
args="$api_key_type $unattended $main_root_path $API_URL $api_key"
5667

5768
if [ ! -z "$additional_root_paths" ]; then
5869
args="$additional_root_paths $args"
@@ -131,4 +142,4 @@ if [ ! -z "$ARCHIVE" ]; then
131142
fi
132143

133144
BASEDIR=$(dirname "$0")
134-
echo $args | xargs python3 -u $BASEDIR/immich_auto_album.py
145+
echo $args | xargs python3 -u $BASEDIR/immich_auto_album.py

immich_auto_album.py

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -68,10 +68,11 @@ def glob_to_re(pattern):
6868
}
6969

7070
parser = argparse.ArgumentParser(description="Create Immich Albums from an external library path based on the top level folders", formatter_class=argparse.ArgumentDefaultsHelpFormatter)
71-
parser.add_argument("root_path", action='append', help="The external libarary's root path in Immich")
71+
parser.add_argument("root_path", action='append', help="The external library's root path in Immich")
7272
parser.add_argument("api_url", help="The root API URL of immich, e.g. https://immich.mydomain.com/api/")
73-
parser.add_argument("api_key", help="The Immich API Key to use")
74-
parser.add_argument("-r", "--root-path", action="append", help="Additional external libarary root path in Immich; May be specified multiple times for multiple import paths or external libraries.")
73+
parser.add_argument("api_key", help="The Immich API Key to use. Set --api-key-type to 'file' if a file path is provided.")
74+
parser.add_argument("-t", "--api-key-type", default="literal", choices=['literal', 'file'], help="The type of the Immich API Key")
75+
parser.add_argument("-r", "--root-path", action="append", help="Additional external library root path in Immich; May be specified multiple times for multiple import paths or external libraries.")
7576
parser.add_argument("-u", "--unattended", action="store_true", help="Do not ask for user confirmation after identifying albums. Set this flag to run script as a cronjob.")
7677
parser.add_argument("-a", "--album-levels", default="1", type=str, help="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 '<startLevel>,<endLevel>'. If negative levels are used in a range, <startLevel> must be less than or equal to <endLevel>.")
7778
parser.add_argument("-s", "--album-separator", default=" ", type=str, help="Separator string to use for compound album names created from nested folders. Only effective if -a is set to a value > 1")
@@ -98,10 +99,29 @@ def glob_to_re(pattern):
9899
logging.basicConfig(level=args["log_level"], stream=sys.stdout, format='time=%(asctime)s level=%(levelname)s msg=%(message)s')
99100
logging.Formatter.formatTime = (lambda self, record, datefmt=None: datetime.datetime.fromtimestamp(record.created, datetime.timezone.utc).astimezone().isoformat(sep="T",timespec="milliseconds"))
100101

102+
def readApiKeyFromFile(file_path: str) -> str:
103+
try:
104+
with open(file_path, 'r') as secret_file:
105+
return secret_file.read().strip()
106+
except FileNotFoundError:
107+
logging.error("API Key file not found at %s", file_path)
108+
exit(1)
109+
except Exception as e:
110+
logging.error("Error reading API Key file: %s", e)
111+
exit(1)
112+
113+
def determine_api_key(api_key: str, key_type: str) -> str:
114+
if key_type == "literal":
115+
return api_key
116+
elif key_type == "file":
117+
return readApiKeyFromFile(api_key)
118+
else:
119+
logging.error("Unknown key type (-t, --key-type). Must be either 'literal' or 'file'.")
120+
exit(1)
101121

102122
root_paths = args["root_path"]
103123
root_url = args["api_url"]
104-
api_key = args["api_key"]
124+
api_key = determine_api_key(args["api_key"], args["api_key_type"])
105125
number_of_images_per_request = args["chunk_size"]
106126
number_of_assets_to_fetch_per_request = args["fetch_chunk_size"]
107127
unattended = args["unattended"]

0 commit comments

Comments
 (0)