pax_global_header 0000666 0000000 0000000 00000000064 15230667036 0014522 g ustar 00root root 0000000 0000000 52 comment=f4ce8208fa8b5260cd9616af491f969d459ee63b
immich-archiver-0.1.7/ 0000775 0000000 0000000 00000000000 15230667036 0014576 5 ustar 00root root 0000000 0000000 immich-archiver-0.1.7/.github/ 0000775 0000000 0000000 00000000000 15230667036 0016136 5 ustar 00root root 0000000 0000000 immich-archiver-0.1.7/.github/dependabot.yml 0000664 0000000 0000000 00000000361 15230667036 0020766 0 ustar 00root root 0000000 0000000 version: 2
updates:
- package-ecosystem: "gomod"
directory: "/"
schedule:
interval: "weekly"
open-pull-requests-limit: 10
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
immich-archiver-0.1.7/.github/scripts/ 0000775 0000000 0000000 00000000000 15230667036 0017625 5 ustar 00root root 0000000 0000000 immich-archiver-0.1.7/.github/scripts/render_pages.py 0000664 0000000 0000000 00000006715 15230667036 0022646 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python3
"""Regenerate docs/index.html from the repo's GitHub Releases.
Run by .github/workflows/release.yml after GoReleaser publishes a release.
Requires GITHUB_TOKEN and REPO ("owner/name") in the environment.
"""
import html
import json
import os
import urllib.request
REPO = os.environ["REPO"]
TOKEN = os.environ["GITHUB_TOKEN"]
PLATFORM_LABELS = [
("linux_amd64", "Linux (x86_64)"),
("linux_arm64", "Linux (ARM64)"),
("darwin_amd64", "macOS (Intel)"),
("darwin_arm64", "macOS (Apple Silicon)"),
("windows_amd64", "Windows (x86_64)"),
]
def fetch_releases():
req = urllib.request.Request(
f"https://api.github.com/repos/{REPO}/releases",
headers={
"Authorization": f"Bearer {TOKEN}",
"Accept": "application/vnd.github+json",
},
)
with urllib.request.urlopen(req) as resp:
return json.load(resp)
def asset_for(assets, platform_key):
for a in assets:
if platform_key in a["name"]:
return a
return None
def render(releases):
releases = [r for r in releases if not r.get("draft")]
latest = releases[0] if releases else None
rows = []
if latest:
for key, label in PLATFORM_LABELS:
a = asset_for(latest["assets"], key)
if a:
rows.append(
f'
{html.escape(label)} '
f'({a["size"] // 1024 // 1024} MB)'
)
history_items = "".join(
f'{html.escape(r["tag_name"])} '
f'— {html.escape(r["published_at"] or "")}'
for r in releases[1:11]
)
latest_version = html.escape(latest["tag_name"]) if latest else "unreleased"
latest_url = html.escape(latest["html_url"]) if latest else "#"
downloads = "\n ".join(rows) if rows else "No release assets found."
return f"""
immich-archiver
immich-archiver
Mirror an Immich instance's timeline onto local disk.
"""
def main():
releases = fetch_releases()
os.makedirs("docs", exist_ok=True)
with open("docs/index.html", "w") as f:
f.write(render(releases))
if __name__ == "__main__":
main()
immich-archiver-0.1.7/.github/workflows/ 0000775 0000000 0000000 00000000000 15230667036 0020173 5 ustar 00root root 0000000 0000000 immich-archiver-0.1.7/.github/workflows/ci.yml 0000664 0000000 0000000 00000001127 15230667036 0021312 0 ustar 00root root 0000000 0000000 name: CI
on:
push:
branches: [main]
pull_request:
permissions:
contents: read
jobs:
test:
name: Build, vet, lint, unit test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version-file: go.mod
- name: go build
run: go build ./...
- name: go vet
run: go vet ./...
- name: golangci-lint
uses: golangci/golangci-lint-action@v9
with:
version: latest
- name: go test (mocked Immich API)
run: go test ./... -race -count=1
immich-archiver-0.1.7/.github/workflows/dependabot-automerge.yml 0000664 0000000 0000000 00000001711 15230667036 0025011 0 ustar 00root root 0000000 0000000 name: Dependabot auto-merge
# Patch and minor bumps: enable GitHub's native auto-merge, which completes
# once the required CI checks (see ci.yml) pass. Major bumps are left alone
# for manual review — they still run the full CI suite via the regular
# pull_request trigger, just never get an auto-merge request.
on: pull_request
permissions:
contents: write
pull-requests: write
jobs:
automerge:
if: github.actor == 'dependabot[bot]'
runs-on: ubuntu-latest
steps:
- name: Fetch Dependabot metadata
id: metadata
uses: dependabot/fetch-metadata@v3
with:
github-token: "${{ secrets.GITHUB_TOKEN }}"
- name: Enable auto-merge for patch/minor updates
if: steps.metadata.outputs.update-type != 'version-update:semver-major'
run: gh pr merge --auto --squash "$PR_URL"
env:
PR_URL: ${{ github.event.pull_request.html_url }}
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
immich-archiver-0.1.7/.github/workflows/integration.yml 0000664 0000000 0000000 00000001377 15230667036 0023251 0 ustar 00root root 0000000 0000000 name: Live Immich integration tests
# Non-blocking: runs against a real Immich instance on a schedule or by hand.
# Never required for PR checks or Dependabot auto-merge, since a flaky/
# offline home server shouldn't be able to block everyone else's merges.
on:
schedule:
- cron: "0 6 * * *"
workflow_dispatch: {}
permissions:
contents: read
jobs:
integration:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version-file: go.mod
- name: go test -tags integration
env:
IMMICH_TEST_URL: ${{ secrets.IMMICH_TEST_URL }}
IMMICH_TEST_API_KEY: ${{ secrets.IMMICH_TEST_API_KEY }}
run: go test -tags integration ./... -count=1 -v
immich-archiver-0.1.7/.github/workflows/release.yml 0000664 0000000 0000000 00000005726 15230667036 0022350 0 ustar 00root root 0000000 0000000 name: Release
# Fully automated: every push to main that passes CI gets a release. The
# patch version is auto-bumped (v0.1.0 -> v0.1.1 -> ...). To cut a minor or
# major release instead, push that tag yourself (e.g. `git tag v1.0.0 && git
# push --tags`) — the "push: tags" trigger below still fires for that, and
# auto-bumping then continues patch-incrementing from the new baseline.
on:
push:
tags:
- "v[0-9]+.[0-9]+.[0-9]+"
workflow_run:
workflows: ["CI"]
types: [completed]
branches: [main]
permissions:
contents: write
pages: write
id-token: write
jobs:
autotag:
if: github.event_name == 'workflow_run' && github.event.workflow_run.conclusion == 'success'
runs-on: ubuntu-latest
outputs:
tag: ${{ steps.tag.outputs.tag }}
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.workflow_run.head_sha }}
fetch-depth: 0
- name: Compute next patch version and tag it
id: tag
run: |
set -euo pipefail
last=$(git tag --list 'v[0-9]*.[0-9]*.[0-9]*' --sort=-v:refname | head -n1)
if [ -z "$last" ]; then
next="v0.1.0"
else
IFS='.' read -r major minor patch <<< "${last#v}"
next="v${major}.${minor}.$((patch + 1))"
fi
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git tag -a "$next" -m "Release $next"
git push origin "$next"
echo "tag=$next" >> "$GITHUB_OUTPUT"
goreleaser:
needs: [autotag]
if: always() && (github.event_name == 'push' || needs.autotag.result == 'success')
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
ref: ${{ needs.autotag.outputs.tag || github.ref }}
fetch-depth: 0
- uses: actions/setup-go@v5
with:
go-version-file: go.mod
- name: Run GoReleaser
uses: goreleaser/goreleaser-action@v7
with:
distribution: goreleaser
version: latest
args: release --clean
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
MACOS_SIGN_P12: ${{ secrets.MACOS_SIGN_P12 }}
MACOS_SIGN_PASSWORD: ${{ secrets.MACOS_SIGN_PASSWORD }}
MACOS_NOTARY_ISSUER_ID: ${{ secrets.MACOS_NOTARY_ISSUER_ID }}
MACOS_NOTARY_KEY_ID: ${{ secrets.MACOS_NOTARY_KEY_ID }}
MACOS_NOTARY_KEY: ${{ secrets.MACOS_NOTARY_KEY }}
pages:
needs: goreleaser
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Render download page
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
REPO: ${{ github.repository }}
run: python3 .github/scripts/render_pages.py
- name: Upload Pages artifact
uses: actions/upload-pages-artifact@v5
with:
path: docs
- name: Deploy to GitHub Pages
uses: actions/deploy-pages@v5
immich-archiver-0.1.7/.gitignore 0000664 0000000 0000000 00000000037 15230667036 0016566 0 ustar 00root root 0000000 0000000 /dist/
/immich-archiver
*.part
immich-archiver-0.1.7/.goreleaser.yaml 0000664 0000000 0000000 00000002210 15230667036 0017663 0 ustar 00root root 0000000 0000000 version: 2
before:
hooks:
- go mod tidy
builds:
- id: immich-archiver
main: .
binary: immich-archiver
env:
- CGO_ENABLED=0
goos:
- linux
- windows
- darwin
goarch:
- amd64
- arm64
ignore:
- goos: windows
goarch: arm64
ldflags:
- -s -w -X github.com/pixelunioneu/immich-archiver/cmd.version={{.Version}}
notarize:
macos:
- enabled: '{{ isEnvSet "MACOS_SIGN_P12" }}'
ids:
- immich-archiver
sign:
certificate: "{{.Env.MACOS_SIGN_P12}}"
password: "{{.Env.MACOS_SIGN_PASSWORD}}"
notarize:
issuer_id: "{{.Env.MACOS_NOTARY_ISSUER_ID}}"
key_id: "{{.Env.MACOS_NOTARY_KEY_ID}}"
key: "{{.Env.MACOS_NOTARY_KEY}}"
wait: true
timeout: 20m
archives:
- id: immich-archiver
formats: [binary]
name_template: >-
{{ .ProjectName }}_{{ .Version }}_{{ .Os }}_{{ .Arch }}
checksum:
name_template: "checksums.txt"
changelog:
sort: asc
filters:
exclude:
- "^docs:"
- "^test:"
- "^ci:"
release:
github:
owner: pixelunioneu
name: immich-archiver
immich-archiver-0.1.7/CONTRIBUTING.md 0000664 0000000 0000000 00000004052 15230667036 0017030 0 ustar 00root root 0000000 0000000 # Contributing to immich-archiver
Thanks for considering a contribution. This is a small, focused tool — keep changes scoped and
avoid adding abstractions or config surface the project doesn't need yet.
## Getting set up
The repo pins its Go toolchain via [mise](https://mise.jdx.dev):
```sh
mise install # installs the pinned Go version
mise run build # builds ./immich-archiver
mise run test # unit tests, mocked Immich API, no network required
mise run check # vet + lint + test
```
Without mise, any Go matching the version in `go.mod` works fine with plain `go build`/`go test`.
## Before opening a PR
- `mise run check` (or `go vet ./... && golangci-lint run && go test ./... -race`) passes locally.
- New behavior has unit test coverage. Sync/download logic is tested against a mocked Immich API
or an in-memory fake `archive.Source` — see `internal/immich/client_test.go` and
`internal/archive/sync_test.go` for the patterns. You should not need a real Immich server to
write or run tests; the live-server suite (`go test -tags integration ./...`) is a separate,
non-blocking CI job and isn't required for a PR to merge.
- Keep PRs small and single-purpose. If a change touches CLI flags, update the flag table in
`README.md` too.
## Commit messages
Plain, descriptive commit messages explaining *why* a change was made. No enforced format.
## Reporting bugs / requesting features
Open a GitHub issue. Include your Immich server version and the exact command you ran when
reporting a bug — most issues in a tool like this come down to a specific asset shape (missing
EXIF, an unusual Live Photo pairing, a large library edge case) that's easiest to fix with a
reproducible example.
## Security
Found a vulnerability (e.g. something that could leak an API key, or a path traversal in how
filenames/sidecars are written)? Please report it privately rather than opening a public issue —
see [SECURITY.md](SECURITY.md).
## License
By contributing, you agree your contribution is licensed under the project's
[AGPL-3.0](LICENSE).
immich-archiver-0.1.7/LICENSE 0000664 0000000 0000000 00000103333 15230667036 0015606 0 ustar 00root root 0000000 0000000 GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
.
immich-archiver-0.1.7/README.md 0000664 0000000 0000000 00000005370 15230667036 0016062 0 ustar 00root root 0000000 0000000 # immich-archiver
A small Go CLI, built by PixelUnion, that mirrors an [Immich](https://immich.app) instance's
timeline onto local disk — photos and videos organized into date-based folders, each with an
Immich-go-style sidecar JSON carrying the full original asset metadata.
## Usage
```sh
export IMMICH_URL=https://photos.example.com
export IMMICH_API_KEY=your-user-api-key
export IMMICH_DIR=/path/to/archive
immich-archiver
# or, without env vars:
immich-archiver --url https://photos.example.com --api-key your-user-api-key --dir /path/to/archive
```
On a second run, assets already present on disk (verified by filename + a matching asset ID in
the sidecar) are skipped, so re-running is cheap.
### Layout
By default, assets land in `/{year}/{year}-{month}/`, e.g.:
```
/path/to/archive/2005/2005-06/IMG_0001.jpg
/path/to/archive/2005/2005-06/IMG_0001.jpg.json
```
Override the structure with `--path-template`, using `{year}`, `{month}`, `{day}` tokens, e.g.
`--path-template "{year}/{month}/{day}"`. Assets missing a usable date fall into `unknown-date/`.
Live Photos are downloaded as a still + a paired motion video sharing the same base filename.
### Flags
| Flag | Default | Description |
|---|---|---|
| `--url` | *(required)* | Immich server URL (env `IMMICH_URL`) |
| `--api-key` | *(required)* | Immich user API key (env `IMMICH_API_KEY`) |
| `--dir` | *(required)* | destination root directory (env `IMMICH_DIR`) |
| `--path-template` | `{year}/{year}-{month}` | folder structure template |
| `--include-shared` | `false` | also mirror assets from albums shared with you |
| `--shared-dir` | `/shared-with-me` | destination root for shared assets |
| `--shared-path-template` | same as `--path-template` | folder structure template for shared assets |
| `--concurrency` | `4` | parallel downloads |
| `--retries` | `3` | retry attempts on network/server errors |
| `--dry-run` | `false` | preview without writing |
| `--verbose` / `-v` | `false` | log one line per asset instead of a progress summary |
## Development
```sh
go build ./...
go test ./... # unit tests only, against a mocked Immich API
go test -tags integration ./... # requires IMMICH_TEST_URL / IMMICH_TEST_API_KEY
```
## Releases
Fully automated: every push to `main` that passes CI gets a release, with the patch version
auto-bumped (`v0.1.0` -> `v0.1.1` -> ...). [GoReleaser](https://goreleaser.com) then builds
binaries for Linux, macOS, and Windows (amd64/arm64) and publishes a GitHub Release. The latest
release is always listed at the project's GitHub Pages site.
To cut a minor or major release instead of the next patch, push that tag yourself
(`git tag v1.0.0 && git push --tags`) — auto-bumping picks up from the new baseline afterward.
## License
[AGPL-3.0](LICENSE)
immich-archiver-0.1.7/SECURITY.md 0000664 0000000 0000000 00000001435 15230667036 0016372 0 ustar 00root root 0000000 0000000 # Security Policy
## Reporting a vulnerability
Please **do not** open a public GitHub issue for security vulnerabilities (e.g. anything that
could leak an Immich API key, a path traversal via crafted filenames/sidecars, or SSRF via the
`--url` flag).
Instead, report it privately via [GitHub Security Advisories](https://github.com/pixelunioneu/immich-archiver/security/advisories/new)
for this repository, or email security@pixelunion.eu.
Please include:
- A description of the issue and its impact
- Steps to reproduce (a minimal example is ideal)
- The version/commit affected
We'll acknowledge reports within a few business days and aim to publish a fix and advisory before
any public disclosure.
## Supported versions
Only the latest released version is supported with security fixes.
immich-archiver-0.1.7/cmd/ 0000775 0000000 0000000 00000000000 15230667036 0015341 5 ustar 00root root 0000000 0000000 immich-archiver-0.1.7/cmd/progress.go 0000664 0000000 0000000 00000003311 15230667036 0017532 0 ustar 00root root 0000000 0000000 package cmd
import (
"fmt"
"io"
"sync"
"sync/atomic"
"github.com/pixelunioneu/immich-archiver/internal/archive"
)
// progress renders sync feedback: a single self-overwriting status line by
// default, or one line per asset under --verbose.
type progress struct {
out io.Writer
verbose bool
dryRun bool
mu sync.Mutex
downloaded int64
skipped int64
failed int64
}
func newProgress(out io.Writer, verbose, dryRun bool) *progress {
return &progress{out: out, verbose: verbose, dryRun: dryRun}
}
func (p *progress) report(e archive.Event) {
switch e.Action {
case archive.ActionDownloaded, archive.ActionWouldFetch:
atomic.AddInt64(&p.downloaded, 1)
case archive.ActionSkipped:
atomic.AddInt64(&p.skipped, 1)
case archive.ActionFailed:
atomic.AddInt64(&p.failed, 1)
}
p.mu.Lock()
defer p.mu.Unlock()
if p.verbose {
verb := "downloaded"
if p.dryRun {
verb = "would download"
}
switch e.Action {
case archive.ActionDownloaded, archive.ActionWouldFetch:
_, _ = fmt.Fprintf(p.out, "%s %s\n", verb, e.Filename)
case archive.ActionSkipped:
_, _ = fmt.Fprintf(p.out, "skipped (already present) %s\n", e.Filename)
case archive.ActionFailed:
_, _ = fmt.Fprintf(p.out, "FAILED %s: %v\n", e.Filename, e.Err)
}
return
}
_, _ = fmt.Fprintf(p.out, "\rdownloaded %d, skipped %d, failed %d",
atomic.LoadInt64(&p.downloaded), atomic.LoadInt64(&p.skipped), atomic.LoadInt64(&p.failed))
}
func (p *progress) finish(stats archive.Stats) {
if !p.verbose {
_, _ = fmt.Fprintln(p.out)
}
verb := "Downloaded"
if p.dryRun {
verb = "Would download"
}
_, _ = fmt.Fprintf(p.out, "%s: %d, skipped: %d, failed: %d\n", verb, stats.Downloaded, stats.Skipped, stats.Failed)
}
immich-archiver-0.1.7/cmd/root.go 0000664 0000000 0000000 00000010272 15230667036 0016655 0 ustar 00root root 0000000 0000000 package cmd
import (
"context"
"fmt"
"os"
"strings"
"time"
"github.com/pixelunioneu/immich-archiver/internal/archive"
"github.com/pixelunioneu/immich-archiver/internal/immich"
"github.com/spf13/cobra"
)
// version is set at build time via -ldflags "-X .../cmd.version=v1.2.3".
var version = "dev"
type flags struct {
url string
apiKey string
dir string
pathTemplate string
includeShared bool
sharedDir string
sharedPathTemplate string
concurrency int
retries int
dryRun bool
verbose bool
}
// Execute builds and runs the root command.
func Execute() error {
return newRootCmd().Execute()
}
func newRootCmd() *cobra.Command {
f := &flags{}
cmd := &cobra.Command{
Use: "immich-archiver",
Short: "Mirror an Immich instance's timeline onto local disk",
Version: version,
SilenceUsage: true,
SilenceErrors: true,
PreRunE: func(cmd *cobra.Command, args []string) error {
return validateFlags(cmd, f)
},
RunE: func(cmd *cobra.Command, args []string) error {
return runSync(cmd, f)
},
}
cmd.Flags().StringVar(&f.url, "url", os.Getenv("IMMICH_URL"), "Immich server URL (env IMMICH_URL)")
cmd.Flags().StringVar(&f.apiKey, "api-key", os.Getenv("IMMICH_API_KEY"), "Immich user API key (env IMMICH_API_KEY)")
cmd.Flags().StringVar(&f.dir, "dir", os.Getenv("IMMICH_DIR"), "destination root directory (required, env IMMICH_DIR)")
cmd.Flags().StringVar(&f.pathTemplate, "path-template", archive.DefaultPathTemplate, "folder structure template; supports {year}, {month}, {day}")
cmd.Flags().BoolVar(&f.includeShared, "include-shared", false, "also mirror assets shared with you into a separate folder")
cmd.Flags().StringVar(&f.sharedDir, "shared-dir", "", "destination root for shared assets (default: /shared-with-me)")
cmd.Flags().StringVar(&f.sharedPathTemplate, "shared-path-template", "", "folder structure template for shared assets (default: same as --path-template)")
cmd.Flags().IntVar(&f.concurrency, "concurrency", 4, "number of assets to download in parallel")
cmd.Flags().IntVar(&f.retries, "retries", 3, "number of retry attempts for failed downloads/requests")
cmd.Flags().BoolVar(&f.dryRun, "dry-run", false, "list what would be downloaded without writing anything")
cmd.Flags().BoolVarP(&f.verbose, "verbose", "v", false, "log a line per asset instead of showing a progress bar")
return cmd
}
// validateFlags checks required inputs before RunE. Failures print the full
// usage/help text (unlike runtime errors from RunE, which stay terse) so a
// missing/misspelled flag is immediately actionable.
func validateFlags(cmd *cobra.Command, f *flags) error {
var missing []string
if f.dir == "" {
missing = append(missing, "--dir (or IMMICH_DIR)")
}
if f.url == "" {
missing = append(missing, "--url (or IMMICH_URL)")
}
if f.apiKey == "" {
missing = append(missing, "--api-key (or IMMICH_API_KEY)")
}
if len(missing) == 0 {
return nil
}
_, _ = fmt.Fprintln(cmd.OutOrStderr(), cmd.UsageString())
return fmt.Errorf("missing required flag(s): %s", strings.Join(missing, ", "))
}
func runSync(cmd *cobra.Command, f *flags) error {
client := immich.NewClient(f.url, f.apiKey)
client.Retries = f.retries
ctx, cancel := context.WithCancel(cmd.Context())
defer cancel()
if err := client.Ping(ctx); err != nil {
return fmt.Errorf("could not reach %s: %w", f.url, err)
}
sharedDir := f.sharedDir
if sharedDir == "" {
sharedDir = f.dir + string(os.PathSeparator) + "shared-with-me"
}
p := newProgress(cmd.OutOrStdout(), f.verbose, f.dryRun)
s := &archive.Syncer{
Source: client,
Options: archive.Options{
RootDir: f.dir,
PathTemplate: f.pathTemplate,
IncludeShared: f.includeShared,
SharedRootDir: sharedDir,
SharedPathTemplate: f.sharedPathTemplate,
Concurrency: f.concurrency,
Retries: f.retries,
RetryDelay: 2 * time.Second,
DryRun: f.dryRun,
},
Reporter: p.report,
}
stats, err := s.Run(ctx)
p.finish(stats)
if err != nil {
return err
}
if stats.Failed > 0 {
return fmt.Errorf("%d asset(s) failed to sync", stats.Failed)
}
return nil
}
immich-archiver-0.1.7/go.mod 0000664 0000000 0000000 00000000321 15230667036 0015700 0 ustar 00root root 0000000 0000000 module github.com/pixelunioneu/immich-archiver
go 1.23
require github.com/spf13/cobra v1.10.2
require (
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/spf13/pflag v1.0.9 // indirect
)
immich-archiver-0.1.7/go.sum 0000664 0000000 0000000 00000001604 15230667036 0015732 0 ustar 00root root 0000000 0000000 github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY=
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
immich-archiver-0.1.7/internal/ 0000775 0000000 0000000 00000000000 15230667036 0016412 5 ustar 00root root 0000000 0000000 immich-archiver-0.1.7/internal/archive/ 0000775 0000000 0000000 00000000000 15230667036 0020033 5 ustar 00root root 0000000 0000000 immich-archiver-0.1.7/internal/archive/destination.go 0000664 0000000 0000000 00000003430 15230667036 0022703 0 ustar 00root root 0000000 0000000 package archive
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
)
// sidecarName returns the sidecar filename for a given asset filename, e.g.
// "IMG_0001.jpg" -> "IMG_0001.jpg.json".
func sidecarName(filename string) string {
return filename + ".json"
}
// sidecarAssetID peeks at an existing sidecar file's "id" field, returning
// "" if the file doesn't exist or can't be parsed.
func sidecarAssetID(path string) string {
data, err := os.ReadFile(path)
if err != nil {
return ""
}
var v struct {
ID string `json:"id"`
}
if err := json.Unmarshal(data, &v); err != nil {
return ""
}
return v.ID
}
// ResolveDestination decides the on-disk filename for assetID/originalName
// within dir. "Already downloaded" is determined purely from the
// filesystem: if a file with the candidate name exists and its sidecar's
// recorded asset id matches assetID, the asset is considered already
// present. If the name is taken by a *different* asset, a numeric suffix
// (_1, _2, ...) is appended to originalName until a free or matching name is
// found.
func ResolveDestination(dir, originalName, assetID string) (filename string, alreadyExists bool, err error) {
ext := filepath.Ext(originalName)
base := strings.TrimSuffix(originalName, ext)
for n := 0; ; n++ {
candidate := originalName
if n > 0 {
candidate = fmt.Sprintf("%s_%d%s", base, n, ext)
}
fullPath := filepath.Join(dir, candidate)
if _, statErr := os.Stat(fullPath); statErr != nil {
if os.IsNotExist(statErr) {
return candidate, false, nil
}
return "", false, fmt.Errorf("checking %s: %w", fullPath, statErr)
}
if sidecarAssetID(filepath.Join(dir, sidecarName(candidate))) == assetID {
return candidate, true, nil
}
// Name taken by a different asset; try the next suffix.
}
}
immich-archiver-0.1.7/internal/archive/destination_test.go 0000664 0000000 0000000 00000005411 15230667036 0023743 0 ustar 00root root 0000000 0000000 package archive
import (
"os"
"path/filepath"
"testing"
)
func TestResolveDestinationNewFile(t *testing.T) {
dir := t.TempDir()
name, exists, err := ResolveDestination(dir, "IMG_0001.jpg", "asset-1")
if err != nil {
t.Fatalf("ResolveDestination: %v", err)
}
if exists {
t.Fatal("expected new file to not already exist")
}
if name != "IMG_0001.jpg" {
t.Fatalf("got %q, want IMG_0001.jpg", name)
}
}
func TestResolveDestinationAlreadyDownloaded(t *testing.T) {
dir := t.TempDir()
writeFile(t, filepath.Join(dir, "IMG_0001.jpg"), "data")
writeFile(t, filepath.Join(dir, "IMG_0001.jpg.json"), `{"id":"asset-1"}`)
name, exists, err := ResolveDestination(dir, "IMG_0001.jpg", "asset-1")
if err != nil {
t.Fatalf("ResolveDestination: %v", err)
}
if !exists {
t.Fatal("expected asset to be detected as already downloaded")
}
if name != "IMG_0001.jpg" {
t.Fatalf("got %q, want IMG_0001.jpg", name)
}
}
func TestResolveDestinationCollisionDifferentAsset(t *testing.T) {
dir := t.TempDir()
writeFile(t, filepath.Join(dir, "IMG_0001.jpg"), "data")
writeFile(t, filepath.Join(dir, "IMG_0001.jpg.json"), `{"id":"asset-OTHER"}`)
name, exists, err := ResolveDestination(dir, "IMG_0001.jpg", "asset-1")
if err != nil {
t.Fatalf("ResolveDestination: %v", err)
}
if exists {
t.Fatal("expected collision with a different asset to not be treated as already-downloaded")
}
if name != "IMG_0001_1.jpg" {
t.Fatalf("got %q, want IMG_0001_1.jpg", name)
}
}
func TestResolveDestinationMultipleCollisions(t *testing.T) {
dir := t.TempDir()
writeFile(t, filepath.Join(dir, "IMG_0001.jpg"), "data")
writeFile(t, filepath.Join(dir, "IMG_0001.jpg.json"), `{"id":"asset-OTHER-1"}`)
writeFile(t, filepath.Join(dir, "IMG_0001_1.jpg"), "data")
writeFile(t, filepath.Join(dir, "IMG_0001_1.jpg.json"), `{"id":"asset-OTHER-2"}`)
name, exists, err := ResolveDestination(dir, "IMG_0001.jpg", "asset-1")
if err != nil {
t.Fatalf("ResolveDestination: %v", err)
}
if exists {
t.Fatal("expected no match")
}
if name != "IMG_0001_2.jpg" {
t.Fatalf("got %q, want IMG_0001_2.jpg", name)
}
}
func TestResolveDestinationMissingSidecarTreatedAsCollision(t *testing.T) {
dir := t.TempDir()
// File exists but no sidecar at all (e.g. foreign file dropped in the folder).
writeFile(t, filepath.Join(dir, "IMG_0001.jpg"), "data")
name, exists, err := ResolveDestination(dir, "IMG_0001.jpg", "asset-1")
if err != nil {
t.Fatalf("ResolveDestination: %v", err)
}
if exists {
t.Fatal("expected no match since sidecar is missing")
}
if name != "IMG_0001_1.jpg" {
t.Fatalf("got %q, want IMG_0001_1.jpg", name)
}
}
func writeFile(t *testing.T, path, content string) {
t.Helper()
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
t.Fatalf("writing %s: %v", path, err)
}
}
immich-archiver-0.1.7/internal/archive/download.go 0000664 0000000 0000000 00000005427 15230667036 0022201 0 ustar 00root root 0000000 0000000 package archive
import (
"context"
"fmt"
"io"
"os"
"path/filepath"
"time"
)
// FileFetcher downloads an asset's original bytes. Satisfied by
// *immich.Client.DownloadOriginal.
type FileFetcher func(ctx context.Context, assetID string) (io.ReadCloser, error)
// DownloadToFile fetches assetID via fetch and writes it to
// filepath.Join(dir, filename), downloading into a ".part"
// temp file first and atomically renaming it into place only once the
// full transfer succeeds. This guarantees a crash or interrupted run never
// leaves a truncated file under the final name, which would otherwise be
// mistaken for a complete download on the next sync.
//
// The transfer (fetch + copy) is retried up to retries times on failure,
// waiting delay between attempts.
func DownloadToFile(ctx context.Context, fetch FileFetcher, assetID, dir, filename string, retries int, delay time.Duration) error {
finalPath := filepath.Join(dir, filename)
tempPath := finalPath + ".part"
if err := os.MkdirAll(dir, 0o755); err != nil {
return fmt.Errorf("creating directory %s: %w", dir, err)
}
var lastErr error
for attempt := 0; attempt <= retries; attempt++ {
if attempt > 0 {
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(delay):
}
}
if err := attemptDownload(ctx, fetch, assetID, tempPath); err != nil {
lastErr = err
_ = os.Remove(tempPath)
continue
}
if err := os.Rename(tempPath, finalPath); err != nil {
return fmt.Errorf("finalizing %s: %w", finalPath, err)
}
return nil
}
return fmt.Errorf("downloading asset %s after %d attempts: %w", assetID, retries+1, lastErr)
}
func attemptDownload(ctx context.Context, fetch FileFetcher, assetID, tempPath string) error {
rc, err := fetch(ctx, assetID)
if err != nil {
return fmt.Errorf("fetching asset %s: %w", assetID, err)
}
defer func() { _ = rc.Close() }()
f, err := os.Create(tempPath)
if err != nil {
return fmt.Errorf("creating temp file %s: %w", tempPath, err)
}
defer func() { _ = f.Close() }()
if _, err := io.Copy(f, rc); err != nil {
return fmt.Errorf("writing %s: %w", tempPath, err)
}
return nil
}
// WriteSidecar writes rawJSON to filepath.Join(dir, sidecarName(filename)),
// via the same temp+rename pattern as DownloadToFile so a crash mid-write
// can't leave a truncated sidecar that ResolveDestination would then fail
// to parse as a match.
func WriteSidecar(dir, filename string, rawJSON []byte) error {
finalPath := filepath.Join(dir, sidecarName(filename))
tempPath := finalPath + ".part"
if err := os.WriteFile(tempPath, rawJSON, 0o644); err != nil {
return fmt.Errorf("writing temp sidecar %s: %w", tempPath, err)
}
if err := os.Rename(tempPath, finalPath); err != nil {
return fmt.Errorf("finalizing sidecar %s: %w", finalPath, err)
}
return nil
}
immich-archiver-0.1.7/internal/archive/download_test.go 0000664 0000000 0000000 00000006035 15230667036 0023234 0 ustar 00root root 0000000 0000000 package archive
import (
"context"
"errors"
"io"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
func fetcher(data string, failTimes int) (FileFetcher, *int) {
calls := 0
return func(ctx context.Context, assetID string) (io.ReadCloser, error) {
calls++
if calls <= failTimes {
return nil, errors.New("simulated network failure")
}
return io.NopCloser(strings.NewReader(data)), nil
}, &calls
}
func TestDownloadToFileSuccess(t *testing.T) {
dir := t.TempDir()
fetch, _ := fetcher("hello world", 0)
err := DownloadToFile(context.Background(), fetch, "asset-1", dir, "photo.jpg", 3, time.Millisecond)
if err != nil {
t.Fatalf("DownloadToFile: %v", err)
}
data, err := os.ReadFile(filepath.Join(dir, "photo.jpg"))
if err != nil {
t.Fatalf("reading result: %v", err)
}
if string(data) != "hello world" {
t.Fatalf("got %q", data)
}
if _, err := os.Stat(filepath.Join(dir, "photo.jpg.part")); !os.IsNotExist(err) {
t.Fatal("expected .part temp file to be gone after success")
}
}
func TestDownloadToFileRetriesThenSucceeds(t *testing.T) {
dir := t.TempDir()
fetch, calls := fetcher("data", 2)
err := DownloadToFile(context.Background(), fetch, "asset-1", dir, "photo.jpg", 3, time.Millisecond)
if err != nil {
t.Fatalf("DownloadToFile: %v", err)
}
if *calls != 3 {
t.Fatalf("expected 3 attempts, got %d", *calls)
}
}
func TestDownloadToFileExhaustsRetries(t *testing.T) {
dir := t.TempDir()
fetch, calls := fetcher("data", 100)
err := DownloadToFile(context.Background(), fetch, "asset-1", dir, "photo.jpg", 2, time.Millisecond)
if err == nil {
t.Fatal("expected error after exhausting retries")
}
if *calls != 3 { // initial + 2 retries
t.Fatalf("expected 3 attempts, got %d", *calls)
}
if _, err := os.Stat(filepath.Join(dir, "photo.jpg")); !os.IsNotExist(err) {
t.Fatal("expected no final file to exist after total failure")
}
if _, err := os.Stat(filepath.Join(dir, "photo.jpg.part")); !os.IsNotExist(err) {
t.Fatal("expected no leftover .part file after total failure")
}
}
func TestDownloadToFileNeverExposesPartialFileUnderFinalName(t *testing.T) {
dir := t.TempDir()
// A fetch that fails mid-copy is hard to simulate with a plain reader,
// but we can at least assert the final name never appears until the
// fetch succeeds outright.
fetch, _ := fetcher("data", 1)
done := make(chan struct{})
go func() {
defer close(done)
if err := DownloadToFile(context.Background(), fetch, "asset-1", dir, "photo.jpg", 3, time.Millisecond); err != nil {
t.Error(err)
}
}()
<-done
if _, err := os.Stat(filepath.Join(dir, "photo.jpg")); err != nil {
t.Fatalf("expected final file to exist after eventual success: %v", err)
}
}
func TestWriteSidecar(t *testing.T) {
dir := t.TempDir()
if err := WriteSidecar(dir, "photo.jpg", []byte(`{"id":"asset-1"}`)); err != nil {
t.Fatalf("WriteSidecar: %v", err)
}
data, err := os.ReadFile(filepath.Join(dir, "photo.jpg.json"))
if err != nil {
t.Fatalf("reading sidecar: %v", err)
}
if string(data) != `{"id":"asset-1"}` {
t.Fatalf("got %q", data)
}
}
immich-archiver-0.1.7/internal/archive/pathtemplate.go 0000664 0000000 0000000 00000001563 15230667036 0023057 0 ustar 00root root 0000000 0000000 package archive
import (
"fmt"
"strings"
"time"
)
// DefaultPathTemplate is applied when the user doesn't override it via flag.
const DefaultPathTemplate = "{year}/{year}-{month}"
var pathTokens = map[string]string{
"{year}": "2006",
"{month}": "01",
"{day}": "02",
}
// RenderPath expands a friendly token template (e.g. "{year}/{year}-{month}")
// against t, returning a slash-separated relative directory path.
func RenderPath(tmpl string, t time.Time) (string, error) {
if tmpl == "" {
return "", fmt.Errorf("path template must not be empty")
}
out := tmpl
for token, layout := range pathTokens {
out = strings.ReplaceAll(out, token, t.Format(layout))
}
if strings.Contains(out, "{") || strings.Contains(out, "}") {
return "", fmt.Errorf("path template %q contains unknown token(s); supported tokens: {year}, {month}, {day}", tmpl)
}
return out, nil
}
immich-archiver-0.1.7/internal/archive/pathtemplate_test.go 0000664 0000000 0000000 00000001643 15230667036 0024115 0 ustar 00root root 0000000 0000000 package archive
import (
"testing"
"time"
)
func TestRenderPathDefaultTemplate(t *testing.T) {
tm := time.Date(2005, 6, 15, 0, 0, 0, 0, time.UTC)
got, err := RenderPath(DefaultPathTemplate, tm)
if err != nil {
t.Fatalf("RenderPath: %v", err)
}
want := "2005/2005-06"
if got != want {
t.Fatalf("got %q, want %q", got, want)
}
}
func TestRenderPathWithDayToken(t *testing.T) {
tm := time.Date(2005, 6, 5, 0, 0, 0, 0, time.UTC)
got, err := RenderPath("{year}/{month}/{day}", tm)
if err != nil {
t.Fatalf("RenderPath: %v", err)
}
if got != "2005/06/05" {
t.Fatalf("got %q", got)
}
}
func TestRenderPathUnknownToken(t *testing.T) {
_, err := RenderPath("{year}/{bogus}", time.Now())
if err == nil {
t.Fatal("expected error for unknown token")
}
}
func TestRenderPathEmptyTemplate(t *testing.T) {
_, err := RenderPath("", time.Now())
if err == nil {
t.Fatal("expected error for empty template")
}
}
immich-archiver-0.1.7/internal/archive/sync.go 0000664 0000000 0000000 00000017626 15230667036 0021352 0 ustar 00root root 0000000 0000000 package archive
import (
"context"
"fmt"
"io"
"path/filepath"
"strings"
"sync"
"time"
"github.com/pixelunioneu/immich-archiver/internal/immich"
)
// Source is the subset of the Immich client the syncer depends on. Defined
// as an interface so tests can substitute an in-memory fake.
type Source interface {
SearchAssets(ctx context.Context, query immich.SearchMetadataQuery, fn func(*immich.Asset) error) error
DownloadOriginal(ctx context.Context, assetID string) (io.ReadCloser, error)
GetAsset(ctx context.Context, assetID string) (*immich.Asset, error)
ListAlbums(ctx context.Context, sharedOnly bool) ([]immich.Album, error)
GetAlbum(ctx context.Context, albumID string) (*immich.AlbumDetail, error)
}
// Options configures a sync run.
type Options struct {
RootDir string
PathTemplate string
IncludeShared bool
SharedRootDir string
SharedPathTemplate string
Concurrency int
Retries int
RetryDelay time.Duration
DryRun bool
}
const unknownDateDir = "unknown-date"
// Action describes what happened to one asset during the run, reported via
// Options-independent Reporter callbacks so callers can render progress.
type Action string
const (
ActionDownloaded Action = "downloaded"
ActionSkipped Action = "skipped" // already present on disk
ActionWouldFetch Action = "would-fetch" // dry-run
ActionFailed Action = "failed"
)
// Event is reported once per processed asset (and once more per paired
// live-photo video component).
type Event struct {
AssetID string
Filename string
Action Action
Err error
}
// Reporter receives one Event per asset processed. May be called
// concurrently from multiple workers.
type Reporter func(Event)
// Stats summarizes a completed run.
type Stats struct {
Downloaded int
Skipped int
Failed int
}
// Syncer mirrors an Immich instance's assets onto local disk per Options.
type Syncer struct {
Source Source
Options Options
Reporter Reporter
downloadLocks keyedMutex
}
// keyedMutex hands out a per-key lock so callers can serialize work on the
// same key without blocking unrelated keys. Its zero value is ready to use.
//
// This exists because a live-photo video asset can be referenced by more
// than one still asset (common in Google Takeout imports with duplicated
// motion-photo pairs). Without per-asset locking, two workers could race to
// download the same video into the same ".part" temp file: one
// worker's successful rename would remove the temp file out from under the
// other, which then failed with "no such file or directory".
type keyedMutex struct {
mu sync.Mutex
locks map[string]*sync.Mutex
}
// Lock blocks until key is uncontended, then returns a function to release it.
func (k *keyedMutex) Lock(key string) func() {
k.mu.Lock()
if k.locks == nil {
k.locks = make(map[string]*sync.Mutex)
}
l, ok := k.locks[key]
if !ok {
l = &sync.Mutex{}
k.locks[key] = l
}
k.mu.Unlock()
l.Lock()
return l.Unlock
}
// Run walks the owned library (and, if enabled, shared albums) and
// downloads every asset not already present on disk.
func (s *Syncer) Run(ctx context.Context) (Stats, error) {
var stats Stats
var mu sync.Mutex
report := func(e Event) {
mu.Lock()
switch e.Action {
case ActionDownloaded, ActionWouldFetch:
stats.Downloaded++
case ActionSkipped:
stats.Skipped++
case ActionFailed:
stats.Failed++
}
mu.Unlock()
if s.Reporter != nil {
s.Reporter(e)
}
}
concurrency := s.Options.Concurrency
if concurrency < 1 {
concurrency = 1
}
jobs := make(chan *immich.Asset)
var wg sync.WaitGroup
for i := 0; i < concurrency; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for a := range jobs {
s.processAsset(ctx, a, s.Options.RootDir, s.Options.PathTemplate, report)
}
}()
}
err := s.Source.SearchAssets(ctx, immich.SearchMetadataQuery{WithDeleted: false, IsArchived: nil}, func(a *immich.Asset) error {
if a.IsTrashed {
return nil
}
select {
case jobs <- a:
case <-ctx.Done():
return ctx.Err()
}
return nil
})
close(jobs)
wg.Wait()
if err != nil {
return stats, fmt.Errorf("listing assets: %w", err)
}
if s.Options.IncludeShared {
if err := s.runShared(ctx, report); err != nil {
return stats, fmt.Errorf("syncing shared assets: %w", err)
}
}
return stats, nil
}
func (s *Syncer) runShared(ctx context.Context, report func(Event)) error {
albums, err := s.Source.ListAlbums(ctx, true)
if err != nil {
return err
}
seen := make(map[string]bool)
tmpl := s.Options.SharedPathTemplate
if tmpl == "" {
tmpl = s.Options.PathTemplate
}
for _, album := range albums {
detail, err := s.Source.GetAlbum(ctx, album.ID)
if err != nil {
return fmt.Errorf("getting shared album %s: %w", album.ID, err)
}
for _, a := range detail.Assets {
if a.IsTrashed || seen[a.ID] {
continue
}
seen[a.ID] = true
s.processAsset(ctx, a, s.Options.SharedRootDir, tmpl, report)
}
}
return nil
}
func (s *Syncer) processAsset(ctx context.Context, a *immich.Asset, rootDir, tmpl string, report func(Event)) {
dir, err := destinationDir(rootDir, tmpl, a)
if err != nil {
report(Event{AssetID: a.ID, Filename: a.OriginalFileName, Action: ActionFailed, Err: err})
return
}
s.downloadOne(ctx, a, dir, a.OriginalFileName, report)
if a.LivePhotoVideoID != "" {
video, err := s.Source.GetAsset(ctx, a.LivePhotoVideoID)
if err != nil {
report(Event{AssetID: a.LivePhotoVideoID, Filename: a.OriginalFileName, Action: ActionFailed, Err: fmt.Errorf("fetching live-photo video for %s: %w", a.ID, err)})
return
}
ext := filepath.Ext(video.OriginalFileName)
base := strings.TrimSuffix(a.OriginalFileName, filepath.Ext(a.OriginalFileName))
s.downloadOne(ctx, video, dir, base+ext, report)
}
}
func (s *Syncer) downloadOne(ctx context.Context, a *immich.Asset, dir, desiredName string, report func(Event)) {
// Lock on the target namespace, not just the asset ID: ResolveDestination
// does a check-then-act filesystem scan, so two different assets that
// want the same desiredName (e.g. duplicate stills sharing one
// live-photo video, or literal duplicate imports) can otherwise race on
// the same candidate path just as easily as two calls for the same
// asset ID can.
unlock := s.downloadLocks.Lock(filepath.Join(dir, desiredName))
defer unlock()
filename, exists, err := ResolveDestination(dir, desiredName, a.ID)
if err != nil {
report(Event{AssetID: a.ID, Filename: desiredName, Action: ActionFailed, Err: err})
return
}
if exists {
report(Event{AssetID: a.ID, Filename: filename, Action: ActionSkipped})
return
}
if s.Options.DryRun {
report(Event{AssetID: a.ID, Filename: filename, Action: ActionWouldFetch})
return
}
if err := DownloadToFile(ctx, s.Source.DownloadOriginal, a.ID, dir, filename, s.Options.Retries, s.Options.RetryDelay); err != nil {
report(Event{AssetID: a.ID, Filename: filename, Action: ActionFailed, Err: err})
return
}
if err := WriteSidecar(dir, filename, a.RawJSON); err != nil {
report(Event{AssetID: a.ID, Filename: filename, Action: ActionFailed, Err: err})
return
}
report(Event{AssetID: a.ID, Filename: filename, Action: ActionDownloaded})
}
// dateLayout is Immich's timestamp format, e.g. "2005-06-15T10:30:00.000Z".
const dateLayout = time.RFC3339
func destinationDir(rootDir, tmpl string, a *immich.Asset) (string, error) {
t, ok := assetTime(a)
if !ok {
return filepath.Join(rootDir, unknownDateDir), nil
}
rel, err := RenderPath(tmpl, t)
if err != nil {
return "", err
}
return filepath.Join(rootDir, rel), nil
}
// assetTime resolves the timestamp used for foldering: fileCreatedAt,
// falling back to fileModifiedAt, falling back to "no usable date".
func assetTime(a *immich.Asset) (time.Time, bool) {
if t, err := time.Parse(dateLayout, a.FileCreatedAt); err == nil {
return t, true
}
if t, err := time.Parse(dateLayout, a.FileModifiedAt); err == nil {
return t, true
}
return time.Time{}, false
}
immich-archiver-0.1.7/internal/archive/sync_test.go 0000664 0000000 0000000 00000024642 15230667036 0022405 0 ustar 00root root 0000000 0000000 package archive
import (
"context"
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/pixelunioneu/immich-archiver/internal/immich"
)
// fakeSource is an in-memory Source for exercising Syncer without HTTP.
type fakeSource struct {
assets []*immich.Asset
byID map[string]*immich.Asset
files map[string]string // asset id -> file content
albums []immich.Album
albumAsts map[string][]*immich.Asset
}
func newFakeSource() *fakeSource {
return &fakeSource{
byID: map[string]*immich.Asset{},
files: map[string]string{},
albumAsts: map[string][]*immich.Asset{},
}
}
func mustAsset(t *testing.T, id, name, fileCreatedAt string, extra map[string]any) *immich.Asset {
t.Helper()
m := map[string]any{
"id": id,
"originalFileName": name,
"fileCreatedAt": fileCreatedAt,
}
for k, v := range extra {
m[k] = v
}
data, err := json.Marshal(m)
if err != nil {
t.Fatal(err)
}
var a immich.Asset
if err := json.Unmarshal(data, &a); err != nil {
t.Fatal(err)
}
return &a
}
func (f *fakeSource) add(a *immich.Asset, content string) {
f.assets = append(f.assets, a)
f.byID[a.ID] = a
f.files[a.ID] = content
}
func (f *fakeSource) SearchAssets(ctx context.Context, query immich.SearchMetadataQuery, fn func(*immich.Asset) error) error {
for _, a := range f.assets {
if err := fn(a); err != nil {
return err
}
}
return nil
}
func (f *fakeSource) DownloadOriginal(ctx context.Context, assetID string) (io.ReadCloser, error) {
content, ok := f.files[assetID]
if !ok {
return nil, fmt.Errorf("no such asset %s", assetID)
}
return io.NopCloser(strings.NewReader(content)), nil
}
func (f *fakeSource) GetAsset(ctx context.Context, assetID string) (*immich.Asset, error) {
a, ok := f.byID[assetID]
if !ok {
return nil, fmt.Errorf("no such asset %s", assetID)
}
return a, nil
}
func (f *fakeSource) ListAlbums(ctx context.Context, sharedOnly bool) ([]immich.Album, error) {
return f.albums, nil
}
func (f *fakeSource) GetAlbum(ctx context.Context, albumID string) (*immich.AlbumDetail, error) {
for _, al := range f.albums {
if al.ID == albumID {
return &immich.AlbumDetail{Album: al, Assets: f.albumAsts[albumID]}, nil
}
}
return nil, fmt.Errorf("no such album %s", albumID)
}
func baseOptions(rootDir string) Options {
return Options{
RootDir: rootDir,
PathTemplate: DefaultPathTemplate,
Concurrency: 2,
Retries: 1,
RetryDelay: time.Millisecond,
}
}
func TestSyncerDownloadsAndWritesSidecar(t *testing.T) {
dir := t.TempDir()
src := newFakeSource()
src.add(mustAsset(t, "a1", "IMG_0001.jpg", "2005-06-15T10:00:00.000Z", nil), "photo-bytes")
s := &Syncer{Source: src, Options: baseOptions(dir)}
stats, err := s.Run(context.Background())
if err != nil {
t.Fatalf("Run: %v", err)
}
if stats.Downloaded != 1 {
t.Fatalf("stats = %+v", stats)
}
want := filepath.Join(dir, "2005", "2005-06", "IMG_0001.jpg")
data, err := os.ReadFile(want)
if err != nil {
t.Fatalf("expected file at %s: %v", want, err)
}
if string(data) != "photo-bytes" {
t.Fatalf("got %q", data)
}
sidecar, err := os.ReadFile(want + ".json")
if err != nil {
t.Fatalf("expected sidecar: %v", err)
}
var decoded map[string]any
if err := json.Unmarshal(sidecar, &decoded); err != nil || decoded["id"] != "a1" {
t.Fatalf("sidecar content wrong: %s", sidecar)
}
}
func TestSyncerSkipsAlreadyDownloaded(t *testing.T) {
dir := t.TempDir()
src := newFakeSource()
src.add(mustAsset(t, "a1", "IMG_0001.jpg", "2005-06-15T10:00:00.000Z", nil), "photo-bytes")
s := &Syncer{Source: src, Options: baseOptions(dir)}
if _, err := s.Run(context.Background()); err != nil {
t.Fatalf("first run: %v", err)
}
stats, err := s.Run(context.Background())
if err != nil {
t.Fatalf("second run: %v", err)
}
if stats.Skipped != 1 || stats.Downloaded != 0 {
t.Fatalf("stats = %+v, want 1 skipped", stats)
}
}
func TestSyncerUnknownDateBucket(t *testing.T) {
dir := t.TempDir()
src := newFakeSource()
src.add(mustAsset(t, "a1", "scan.jpg", "", nil), "bytes")
s := &Syncer{Source: src, Options: baseOptions(dir)}
if _, err := s.Run(context.Background()); err != nil {
t.Fatalf("Run: %v", err)
}
if _, err := os.Stat(filepath.Join(dir, unknownDateDir, "scan.jpg")); err != nil {
t.Fatalf("expected file under unknown-date/: %v", err)
}
}
func TestSyncerSkipsTrashed(t *testing.T) {
dir := t.TempDir()
src := newFakeSource()
src.add(mustAsset(t, "a1", "trashed.jpg", "2005-06-15T10:00:00.000Z", map[string]any{"isTrashed": true}), "bytes")
s := &Syncer{Source: src, Options: baseOptions(dir)}
stats, err := s.Run(context.Background())
if err != nil {
t.Fatalf("Run: %v", err)
}
if stats.Downloaded != 0 || stats.Skipped != 0 {
t.Fatalf("expected trashed asset to be entirely ignored, got %+v", stats)
}
}
func TestSyncerDryRunWritesNothing(t *testing.T) {
dir := t.TempDir()
src := newFakeSource()
src.add(mustAsset(t, "a1", "IMG_0001.jpg", "2005-06-15T10:00:00.000Z", nil), "photo-bytes")
opts := baseOptions(dir)
opts.DryRun = true
s := &Syncer{Source: src, Options: opts}
stats, err := s.Run(context.Background())
if err != nil {
t.Fatalf("Run: %v", err)
}
if stats.Downloaded != 1 {
t.Fatalf("stats = %+v", stats)
}
if _, err := os.Stat(filepath.Join(dir, "2005", "2005-06", "IMG_0001.jpg")); !os.IsNotExist(err) {
t.Fatal("expected dry-run to not write any file")
}
}
func TestSyncerLivePhotoPairing(t *testing.T) {
dir := t.TempDir()
src := newFakeSource()
still := mustAsset(t, "still-1", "IMG_1234.heic", "2005-06-15T10:00:00.000Z", map[string]any{"livePhotoVideoId": "video-1"})
video := mustAsset(t, "video-1", "IMG_1234.mov", "2005-06-15T10:00:00.000Z", nil)
src.add(still, "still-bytes")
src.byID["video-1"] = video
src.files["video-1"] = "video-bytes"
s := &Syncer{Source: src, Options: baseOptions(dir)}
stats, err := s.Run(context.Background())
if err != nil {
t.Fatalf("Run: %v", err)
}
if stats.Downloaded != 2 {
t.Fatalf("stats = %+v, want 2 downloads (still + video)", stats)
}
subdir := filepath.Join(dir, "2005", "2005-06")
if _, err := os.Stat(filepath.Join(subdir, "IMG_1234.heic")); err != nil {
t.Fatalf("missing still: %v", err)
}
if _, err := os.Stat(filepath.Join(subdir, "IMG_1234.mov")); err != nil {
t.Fatalf("missing paired video: %v", err)
}
}
// TestSyncerSharedLivePhotoVideoNotRaced reproduces a Google-Takeout-style
// import where multiple still assets reference the same live-photo video
// asset ID. Without per-asset locking, the two workers race to write
// ".part" for the shared video: whichever worker renames it into
// place first removes the temp file, so the other worker's rename fails
// with "no such file or directory" instead of the second still simply
// seeing the video already downloaded.
func TestSyncerSharedLivePhotoVideoNotRaced(t *testing.T) {
dir := t.TempDir()
src := newFakeSource()
video := mustAsset(t, "video-1", "PXL_shared.MP.mp4", "2005-06-15T10:00:00.000Z", nil)
src.byID["video-1"] = video
src.files["video-1"] = "video-bytes"
// Two distinct assets with the *same* original filename (a duplicated
// Takeout import) both referencing the same live-photo video. The video's
// target filename is derived from each still's original filename, so both
// workers compute the identical target for the shared video even though
// the stills themselves get deduped to different on-disk names.
for _, id := range []string{"still-1", "still-2"} {
still := mustAsset(t, id, "PXL_shared.MP.jpg", "2005-06-15T10:00:00.000Z", map[string]any{"livePhotoVideoId": "video-1"})
src.add(still, fmt.Sprintf("still-bytes-%s", id))
}
opts := baseOptions(dir)
opts.Concurrency = 8
s := &Syncer{Source: src, Options: opts}
stats, err := s.Run(context.Background())
if err != nil {
t.Fatalf("Run: %v", err)
}
if stats.Failed != 0 {
t.Fatalf("expected no failures racing on the shared video, got %+v", stats)
}
// 2 stills + 1 shared video downloaded once (the second still's video
// download is a skip once the lock is released).
if stats.Downloaded != 3 || stats.Skipped != 1 {
t.Fatalf("stats = %+v, want 3 downloaded + 1 skipped", stats)
}
}
func TestSyncerSharedAlbumsIntoSeparateRoot(t *testing.T) {
rootDir := t.TempDir()
sharedDir := filepath.Join(rootDir, "shared-with-me")
src := newFakeSource()
shared := mustAsset(t, "shared-1", "friend.jpg", "2010-01-05T10:00:00.000Z", nil)
src.byID["shared-1"] = shared
src.files["shared-1"] = "shared-bytes"
src.albums = []immich.Album{{ID: "al1", AlbumName: "From Alice", Shared: true}}
src.albumAsts["al1"] = []*immich.Asset{shared}
opts := baseOptions(rootDir)
opts.IncludeShared = true
opts.SharedRootDir = sharedDir
s := &Syncer{Source: src, Options: opts}
stats, err := s.Run(context.Background())
if err != nil {
t.Fatalf("Run: %v", err)
}
if stats.Downloaded != 1 {
t.Fatalf("stats = %+v", stats)
}
want := filepath.Join(sharedDir, "2010", "2010-01", "friend.jpg")
if _, err := os.Stat(want); err != nil {
t.Fatalf("expected shared asset at %s: %v", want, err)
}
}
func TestSyncerSharedAlbumDedupesAcrossAlbums(t *testing.T) {
rootDir := t.TempDir()
sharedDir := filepath.Join(rootDir, "shared-with-me")
src := newFakeSource()
shared := mustAsset(t, "shared-1", "friend.jpg", "2010-01-05T10:00:00.000Z", nil)
src.byID["shared-1"] = shared
src.files["shared-1"] = "shared-bytes"
src.albums = []immich.Album{
{ID: "al1", AlbumName: "From Alice", Shared: true},
{ID: "al2", AlbumName: "From Bob", Shared: true},
}
src.albumAsts["al1"] = []*immich.Asset{shared}
src.albumAsts["al2"] = []*immich.Asset{shared} // same asset shared in two albums
opts := baseOptions(rootDir)
opts.IncludeShared = true
opts.SharedRootDir = sharedDir
s := &Syncer{Source: src, Options: opts}
stats, err := s.Run(context.Background())
if err != nil {
t.Fatalf("Run: %v", err)
}
if stats.Downloaded != 1 {
t.Fatalf("expected the duplicate shared asset to be downloaded once, got %+v", stats)
}
}
func TestSyncerNotIncludeSharedByDefault(t *testing.T) {
rootDir := t.TempDir()
src := newFakeSource()
src.albums = []immich.Album{{ID: "al1", Shared: true}}
src.albumAsts["al1"] = []*immich.Asset{mustAsset(t, "shared-1", "friend.jpg", "2010-01-05T10:00:00.000Z", nil)}
s := &Syncer{Source: src, Options: baseOptions(rootDir)}
stats, err := s.Run(context.Background())
if err != nil {
t.Fatalf("Run: %v", err)
}
if stats.Downloaded != 0 {
t.Fatalf("expected shared assets untouched without --include-shared, got %+v", stats)
}
}
immich-archiver-0.1.7/internal/immich/ 0000775 0000000 0000000 00000000000 15230667036 0017660 5 ustar 00root root 0000000 0000000 immich-archiver-0.1.7/internal/immich/client.go 0000664 0000000 0000000 00000014650 15230667036 0021473 0 ustar 00root root 0000000 0000000 package immich
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
)
// Client talks to a single Immich server, authenticated with a user API key.
type Client struct {
BaseURL string
APIKey string
HTTPClient *http.Client
Retries int
RetryDelay time.Duration
}
// NewClient builds a Client with sane defaults. baseURL may or may not
// include a trailing "/api" path segment; both are accepted.
func NewClient(baseURL, apiKey string) *Client {
return &Client{
BaseURL: strings.TrimRight(baseURL, "/"),
APIKey: apiKey,
HTTPClient: &http.Client{Timeout: 60 * time.Second},
Retries: 3,
RetryDelay: 2 * time.Second,
}
}
func (c *Client) apiURL(path string) string {
base := c.BaseURL
if !strings.HasSuffix(base, "/api") {
base += "/api"
}
return base + path
}
// doJSON issues an HTTP request and, on success, decodes the JSON response
// body into out (if non-nil). It retries on network errors and 5xx
// responses, honoring Client.Retries/RetryDelay.
func (c *Client) doJSON(ctx context.Context, method, path string, body, out any) error {
var bodyBytes []byte
if body != nil {
b, err := json.Marshal(body)
if err != nil {
return fmt.Errorf("encoding request body: %w", err)
}
bodyBytes = b
}
var lastErr error
attempts := c.Retries + 1
for attempt := 0; attempt < attempts; attempt++ {
if attempt > 0 {
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(c.RetryDelay):
}
}
var reqBody io.Reader
if bodyBytes != nil {
reqBody = bytes.NewReader(bodyBytes)
}
req, err := http.NewRequestWithContext(ctx, method, c.apiURL(path), reqBody)
if err != nil {
return fmt.Errorf("building request: %w", err)
}
req.Header.Set("x-api-key", c.APIKey)
req.Header.Set("Accept", "application/json")
if bodyBytes != nil {
req.Header.Set("Content-Type", "application/json")
}
resp, err := c.HTTPClient.Do(req)
if err != nil {
lastErr = fmt.Errorf("request failed: %w", err)
continue
}
if resp.StatusCode >= 500 {
_ = resp.Body.Close()
lastErr = fmt.Errorf("server returned %s for %s %s", resp.Status, method, path)
continue
}
if resp.StatusCode >= 400 {
data, _ := io.ReadAll(resp.Body)
_ = resp.Body.Close()
return fmt.Errorf("%s %s: %s: %s", method, path, resp.Status, string(data))
}
defer func() { _ = resp.Body.Close() }()
if out != nil {
if err := json.NewDecoder(resp.Body).Decode(out); err != nil {
return fmt.Errorf("decoding response from %s %s: %w", method, path, err)
}
}
return nil
}
return fmt.Errorf("giving up after %d attempts: %w", attempts, lastErr)
}
// downloadOriginal streams GET /assets/{id}/original with the same
// retry policy as doJSON, since large binary downloads see the same
// class of transient network/5xx failures.
func (c *Client) downloadWithRetry(ctx context.Context, path string) (io.ReadCloser, error) {
var lastErr error
attempts := c.Retries + 1
for attempt := 0; attempt < attempts; attempt++ {
if attempt > 0 {
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(c.RetryDelay):
}
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.apiURL(path), nil)
if err != nil {
return nil, fmt.Errorf("building request: %w", err)
}
req.Header.Set("x-api-key", c.APIKey)
req.Header.Set("Accept", "application/octet-stream")
resp, err := c.HTTPClient.Do(req)
if err != nil {
lastErr = fmt.Errorf("request failed: %w", err)
continue
}
if resp.StatusCode >= 500 {
_ = resp.Body.Close()
lastErr = fmt.Errorf("server returned %s for GET %s", resp.Status, path)
continue
}
if resp.StatusCode >= 400 {
data, _ := io.ReadAll(resp.Body)
_ = resp.Body.Close()
return nil, fmt.Errorf("GET %s: %s: %s", path, resp.Status, string(data))
}
return resp.Body, nil
}
return nil, fmt.Errorf("giving up after %d attempts: %w", attempts, lastErr)
}
// Ping verifies the server is reachable and the API key is valid.
func (c *Client) Ping(ctx context.Context) error {
var out struct {
Res string `json:"res"`
}
return c.doJSON(ctx, http.MethodGet, "/server/ping", nil, &out)
}
const searchPageSize = 1000
// SearchAssets streams all assets matching the query across every page,
// invoking fn for each one. Iteration stops early if fn returns an error.
func (c *Client) SearchAssets(ctx context.Context, query SearchMetadataQuery, fn func(*Asset) error) error {
query.Size = searchPageSize
page := 1
for {
query.Page = page
var resp searchMetadataResponse
if err := c.doJSON(ctx, http.MethodPost, "/search/metadata", query, &resp); err != nil {
return fmt.Errorf("searching metadata (page %d): %w", page, err)
}
for _, a := range resp.Assets.Items {
if err := fn(a); err != nil {
return err
}
}
if resp.Assets.NextPage == "" {
return nil
}
next, err := strconv.Atoi(resp.Assets.NextPage)
if err != nil {
return fmt.Errorf("parsing nextPage %q: %w", resp.Assets.NextPage, err)
}
page = next
}
}
// DownloadOriginal returns a stream of the asset's original file bytes.
// The caller must close the returned reader.
func (c *Client) DownloadOriginal(ctx context.Context, assetID string) (io.ReadCloser, error) {
return c.downloadWithRetry(ctx, "/assets/"+assetID+"/original")
}
// GetAsset returns a single asset's full metadata by ID. Used to resolve the
// linked video component of a Live Photo, which Immich's search/metadata
// endpoint omits from normal listings.
func (c *Client) GetAsset(ctx context.Context, assetID string) (*Asset, error) {
var a Asset
if err := c.doJSON(ctx, http.MethodGet, "/assets/"+assetID, nil, &a); err != nil {
return nil, fmt.Errorf("getting asset %s: %w", assetID, err)
}
return &a, nil
}
// ListAlbums returns every album visible to the current user.
func (c *Client) ListAlbums(ctx context.Context, sharedOnly bool) ([]Album, error) {
path := "/albums"
if sharedOnly {
path += "?shared=true"
}
var albums []Album
if err := c.doJSON(ctx, http.MethodGet, path, nil, &albums); err != nil {
return nil, fmt.Errorf("listing albums: %w", err)
}
return albums, nil
}
// GetAlbum returns an album's full detail, including its assets.
func (c *Client) GetAlbum(ctx context.Context, albumID string) (*AlbumDetail, error) {
var detail AlbumDetail
if err := c.doJSON(ctx, http.MethodGet, "/albums/"+albumID, nil, &detail); err != nil {
return nil, fmt.Errorf("getting album %s: %w", albumID, err)
}
return &detail, nil
}
immich-archiver-0.1.7/internal/immich/client_test.go 0000664 0000000 0000000 00000011527 15230667036 0022532 0 ustar 00root root 0000000 0000000 package immich
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"time"
)
func newTestClient(t *testing.T, handler http.HandlerFunc) (*Client, *httptest.Server) {
t.Helper()
srv := httptest.NewServer(handler)
t.Cleanup(srv.Close)
c := NewClient(srv.URL, "test-key")
c.RetryDelay = time.Millisecond
return c, srv
}
func TestSearchAssetsPaginates(t *testing.T) {
pages := [][]byte{
[]byte(`{"assets":{"total":2,"count":1,"items":[{"id":"a1","originalFileName":"a1.jpg"}],"nextPage":"2"}}`),
[]byte(`{"assets":{"total":2,"count":1,"items":[{"id":"a2","originalFileName":"a2.jpg"}],"nextPage":null}}`),
}
var call int32
c, _ := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost || r.URL.Path != "/api/search/metadata" {
t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
}
if got := r.Header.Get("x-api-key"); got != "test-key" {
t.Fatalf("missing/incorrect x-api-key header: %q", got)
}
idx := atomic.AddInt32(&call, 1) - 1
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write(pages[idx])
})
var got []string
err := c.SearchAssets(context.Background(), SearchMetadataQuery{}, func(a *Asset) error {
got = append(got, a.ID)
return nil
})
if err != nil {
t.Fatalf("SearchAssets: %v", err)
}
if len(got) != 2 || got[0] != "a1" || got[1] != "a2" {
t.Fatalf("got %v, want [a1 a2]", got)
}
if call != 2 {
t.Fatalf("expected 2 requests, got %d", call)
}
}
func TestSearchAssetsPreservesRawJSON(t *testing.T) {
body := `{"assets":{"total":1,"count":1,"items":[{"id":"a1","originalFileName":"a1.jpg","exifInfo":{"make":"Canon"}}],"nextPage":null}}`
c, _ := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte(body))
})
var raw json.RawMessage
err := c.SearchAssets(context.Background(), SearchMetadataQuery{}, func(a *Asset) error {
raw = a.RawJSON
return nil
})
if err != nil {
t.Fatalf("SearchAssets: %v", err)
}
var decoded map[string]any
if err := json.Unmarshal(raw, &decoded); err != nil {
t.Fatalf("raw JSON not preserved: %v", err)
}
exif, ok := decoded["exifInfo"].(map[string]any)
if !ok || exif["make"] != "Canon" {
t.Fatalf("expected exifInfo.make=Canon preserved in raw JSON, got %v", decoded)
}
}
func TestDoJSONRetriesOn5xxThenSucceeds(t *testing.T) {
var call int32
c, _ := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
if atomic.AddInt32(&call, 1) <= 2 {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"res":"pong"}`))
})
c.Retries = 3
if err := c.Ping(context.Background()); err != nil {
t.Fatalf("Ping: %v", err)
}
if call != 3 {
t.Fatalf("expected 3 requests (2 failures + 1 success), got %d", call)
}
}
func TestDoJSONGivesUpAfterConfiguredRetries(t *testing.T) {
var call int32
c, _ := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
atomic.AddInt32(&call, 1)
w.WriteHeader(http.StatusInternalServerError)
})
c.Retries = 2
if err := c.Ping(context.Background()); err == nil {
t.Fatal("expected error after exhausting retries")
}
if call != 3 { // initial attempt + 2 retries
t.Fatalf("expected 3 requests, got %d", call)
}
}
func TestDoJSONDoesNotRetryOn4xx(t *testing.T) {
var call int32
c, _ := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
atomic.AddInt32(&call, 1)
w.WriteHeader(http.StatusUnauthorized)
_, _ = w.Write([]byte(`{"message":"invalid api key"}`))
})
c.Retries = 3
if err := c.Ping(context.Background()); err == nil {
t.Fatal("expected error")
}
if call != 1 {
t.Fatalf("expected exactly 1 request for a 4xx (no retry), got %d", call)
}
}
func TestDownloadOriginal(t *testing.T) {
want := []byte("fake-image-bytes")
c, _ := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/api/assets/asset-123/original" {
t.Fatalf("unexpected path: %s", r.URL.Path)
}
_, _ = w.Write(want)
})
rc, err := c.DownloadOriginal(context.Background(), "asset-123")
if err != nil {
t.Fatalf("DownloadOriginal: %v", err)
}
defer func() { _ = rc.Close() }()
got, err := io.ReadAll(rc)
if err != nil {
t.Fatalf("reading body: %v", err)
}
if string(got) != string(want) {
t.Fatalf("got %q, want %q", got, want)
}
}
func TestListAlbumsSharedFilter(t *testing.T) {
c, _ := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Get("shared") != "true" {
t.Fatalf("expected shared=true query param, got %s", r.URL.RawQuery)
}
_, _ = w.Write([]byte(`[{"id":"al1","albumName":"Family","shared":true}]`))
})
albums, err := c.ListAlbums(context.Background(), true)
if err != nil {
t.Fatalf("ListAlbums: %v", err)
}
if len(albums) != 1 || albums[0].ID != "al1" {
t.Fatalf("unexpected albums: %+v", albums)
}
}
immich-archiver-0.1.7/internal/immich/integration_test.go 0000664 0000000 0000000 00000002416 15230667036 0023574 0 ustar 00root root 0000000 0000000 //go:build integration
package immich
import (
"context"
"errors"
"os"
"testing"
"time"
)
var errStopEarly = errors.New("stop early")
// These tests hit a real, live Immich instance and are excluded from the
// default `go test ./...` run (and therefore never gate Dependabot
// auto-merge or PR checks). They run only in the scheduled/manual
// "integration" GitHub Actions workflow, which supplies
// IMMICH_TEST_URL/IMMICH_TEST_API_KEY as repository secrets.
func testClient(t *testing.T) *Client {
t.Helper()
url := os.Getenv("IMMICH_TEST_URL")
key := os.Getenv("IMMICH_TEST_API_KEY")
if url == "" || key == "" {
t.Skip("IMMICH_TEST_URL / IMMICH_TEST_API_KEY not set")
}
c := NewClient(url, key)
c.HTTPClient.Timeout = 30 * time.Second
return c
}
func TestIntegrationPing(t *testing.T) {
c := testClient(t)
if err := c.Ping(context.Background()); err != nil {
t.Fatalf("Ping against live server: %v", err)
}
}
func TestIntegrationSearchAssetsFirstPage(t *testing.T) {
c := testClient(t)
count := 0
err := c.SearchAssets(context.Background(), SearchMetadataQuery{}, func(a *Asset) error {
count++
if count >= 5 {
return errStopEarly
}
return nil
})
if err != nil && err != errStopEarly {
t.Fatalf("SearchAssets against live server: %v", err)
}
}
immich-archiver-0.1.7/internal/immich/types.go 0000664 0000000 0000000 00000004721 15230667036 0021357 0 ustar 00root root 0000000 0000000 // Package immich is a minimal client for the Immich REST API, covering only
// what immich-archiver needs: paginated asset search, original-file download,
// and shared-album/shared-library listing.
package immich
import "encoding/json"
// Asset mirrors the subset of Immich's asset JSON we rely on for sync
// decisions. RawJSON preserves the full server response verbatim so it can be
// written out as the sidecar without loss.
type Asset struct {
ID string `json:"id"`
OriginalFileName string `json:"originalFileName"`
OriginalPath string `json:"originalPath"`
Type string `json:"type"` // "IMAGE" or "VIDEO"
IsArchived bool `json:"isArchived"`
IsTrashed bool `json:"isTrashed"`
IsFavorite bool `json:"isFavorite"`
FileCreatedAt string `json:"fileCreatedAt"`
FileModifiedAt string `json:"fileModifiedAt"`
LivePhotoVideoID string `json:"livePhotoVideoId"`
OwnerID string `json:"ownerId"`
// RawJSON is the untouched raw asset object as returned by the server,
// used verbatim as sidecar content.
RawJSON json.RawMessage `json:"-"`
}
// UnmarshalJSON captures the raw bytes alongside the parsed fields.
func (a *Asset) UnmarshalJSON(data []byte) error {
type alias Asset
var v alias
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*a = Asset(v)
a.RawJSON = append(json.RawMessage(nil), data...)
return nil
}
// SearchMetadataQuery is the request body for POST /search/metadata.
type SearchMetadataQuery struct {
Page int `json:"page"`
Size int `json:"size,omitempty"`
WithExif bool `json:"withExif,omitempty"`
WithDeleted bool `json:"withDeleted,omitempty"`
IsArchived *bool `json:"isArchived,omitempty"`
PersonalOwn bool `json:"-"` // filtered client-side, Immich search has no such flag
AlbumIDs string `json:"albumIds,omitempty"`
}
type searchMetadataResponse struct {
Assets struct {
Total int `json:"total"`
Count int `json:"count"`
Items []*Asset `json:"items"`
NextPage string `json:"nextPage"`
} `json:"assets"`
}
// Album is the subset of Immich's album JSON we need to discover shared
// albums and their assets.
type Album struct {
ID string `json:"id"`
AlbumName string `json:"albumName"`
Shared bool `json:"shared"`
OwnerID string `json:"ownerId"`
}
// AlbumDetail is the response of GET /albums/{id}, including its assets.
type AlbumDetail struct {
Album
Assets []*Asset `json:"assets"`
}
immich-archiver-0.1.7/main.go 0000664 0000000 0000000 00000000307 15230667036 0016051 0 ustar 00root root 0000000 0000000 package main
import (
"fmt"
"os"
"github.com/pixelunioneu/immich-archiver/cmd"
)
func main() {
if err := cmd.Execute(); err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
}
}
immich-archiver-0.1.7/mise.toml 0000664 0000000 0000000 00000001204 15230667036 0016425 0 ustar 00root root 0000000 0000000 [tools]
go = "1.25.5"
[tasks.build]
description = "Build the immich-archiver binary"
run = "go build -o immich-archiver ."
[tasks.test]
description = "Run unit tests (mocked Immich API only)"
run = "go test ./... -race -count=1"
[tasks."test:integration"]
description = "Run tests against a live Immich instance (needs IMMICH_TEST_URL / IMMICH_TEST_API_KEY)"
run = "go test -tags integration ./... -count=1 -v"
[tasks.vet]
description = "Run go vet"
run = "go vet ./..."
[tasks.lint]
description = "Run golangci-lint"
run = "golangci-lint run"
[tasks.check]
description = "Run vet, lint, and unit tests"
depends = ["vet", "lint", "test"]