Compare commits
17 Commits
6e46f52b52
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
a25b4abdc1
|
|||
|
f1958b399a
|
|||
|
239373d5a3
|
|||
|
0e47fb6983
|
|||
|
34f55eccf0
|
|||
|
ff2cb2335c
|
|||
|
8eb8d0b1db
|
|||
|
8cafd1a57d
|
|||
|
39307d92e2
|
|||
|
15b87e8c36
|
|||
|
4d772878bc
|
|||
|
06996a35d5
|
|||
|
510daabd8a
|
|||
|
004ffe70ea
|
|||
|
2ae7caf4eb
|
|||
|
c0eae078fa
|
|||
|
bc862a41ad
|
201
LICENSE
Normal file
201
LICENSE
Normal file
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
31
README.md
Normal file
31
README.md
Normal file
@@ -0,0 +1,31 @@
|
||||
Sync your steam screenshots to [Immich](https://immich.app/).
|
||||
|
||||
# Synopsis
|
||||
|
||||
```
|
||||
Usage: steam-immich --base-url BASE_URL --api-key API_KEY [--steam-userdata-dir USERDATA_DIR] [--device-id DEVICE-ID] [--album ALBUM] [--cache CACHE] [--revalidate] [--verbose]
|
||||
|
||||
Options:
|
||||
--base-url BASE_URL Base URL of the Immich instance e.g.: https://demo.immich.app
|
||||
--api-key API_KEY API Key. Needs asset.upload, asset.update, albumAsset.create
|
||||
--steam-userdata-dir USERDATA_DIR
|
||||
Steam userdata directory. If not set, search automaticly.
|
||||
--device-id DEVICE-ID
|
||||
Device ID of the uploads [default: steam-immich]
|
||||
--album ALBUM UUID of a album to upload to
|
||||
--cache CACHE Location of the cache file [default: $XDG_CACHE_HOME/steam-immich.json]
|
||||
--revalidate Only revalidate and fix the cache
|
||||
--verbose, -v Toggle verbose logging
|
||||
--help, -h display this help and exit
|
||||
```
|
||||
|
||||
# Usage
|
||||
|
||||
Running the command tries to find the Steam screenshots directory and uploads any screenshots to Immich.
|
||||
The game name will be put in the description of the image.
|
||||
|
||||
Optionally, you can specify an album in which the screenshots should be added.
|
||||
|
||||
Running the command again will only upload new screenshots since it saves the state locally.
|
||||
|
||||
You could automate uploading with a cron job or somehow run it at Steam startup. But thats outside the scope of this software.
|
||||
@@ -1,29 +1,108 @@
|
||||
package main
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
|
||||
steamimmich "git.kapelle.org/niklas/steam-immich/internal"
|
||||
"github.com/alexflint/go-arg"
|
||||
)
|
||||
|
||||
type args struct {
|
||||
BaseURL string `arg:"--base-url,required,env:BASE_URL" placeholder:"https://demo.immich.app"`
|
||||
APIKey string `arg:"--api-key,required,env:API_KEY" placeholder:"API_KEY"`
|
||||
UserdataDir string `arg:"--steam-userdata-dir,env:USERDATA_DIR" default:"$HOME/.var/app/com.valvesoftware.Steam/.local/share/Steam/userdata"`
|
||||
DeviceID string `arg:"--device-id,env:DEVICE_ID" default:"steam-immich"`
|
||||
Album string `arg:"--album,env:ALBUM"`
|
||||
BaseURL string `arg:"--base-url,required" placeholder:"BASE_URL" help:"Base URL of the Immich instance e.g.: https://demo.immich.app"`
|
||||
APIKey string `arg:"--api-key,required" placeholder:"API_KEY" help:"API Key. Needs asset.upload, asset.update, albumAsset.create"`
|
||||
UserdataDir string `arg:"--steam-userdata-dir" placeholder:"USERDATA_DIR" help:"Steam userdata directory. If not set, search automaticly."`
|
||||
DeviceID string `arg:"--device-id" default:"steam-immich" help:"Device ID of the uploads"`
|
||||
Album string `arg:"--album" help:"UUID of a album to upload to"`
|
||||
CacheFile string `arg:"--cache" default:"$XDG_CACHE_HOME/steam-immich.json" help:"Location of the cache file"`
|
||||
Revalidate bool `arg:"--revalidate" help:"Only revalidate and fix the cache"`
|
||||
Verbose bool `arg:"-v,--verbose" help:"Toggle verbose logging"`
|
||||
}
|
||||
|
||||
func main() {
|
||||
func Run() {
|
||||
var args args
|
||||
arg.MustParse(&args)
|
||||
|
||||
steamimmich.Run(steamimmich.Config{
|
||||
if args.Verbose {
|
||||
slog.SetLogLoggerLevel(slog.LevelDebug)
|
||||
}
|
||||
|
||||
var steamUserdataDir = ""
|
||||
|
||||
if args.UserdataDir != "" {
|
||||
steamUserdataDir = os.ExpandEnv(args.UserdataDir)
|
||||
} else {
|
||||
steamUserdataDir = findUserdataDir()
|
||||
}
|
||||
|
||||
if steamUserdataDir == "" {
|
||||
slog.Error("Can not find steam userdata dir. Please set with --steam-userdata-dir")
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
config := steamimmich.Config{
|
||||
APIKey: args.APIKey,
|
||||
BaseURL: args.BaseURL,
|
||||
UserdataDir: os.ExpandEnv(args.UserdataDir),
|
||||
UserdataDir: steamUserdataDir,
|
||||
DeiveID: args.DeviceID,
|
||||
Album: args.Album,
|
||||
})
|
||||
CacheFile: os.ExpandEnv(args.CacheFile),
|
||||
}
|
||||
|
||||
if args.Revalidate {
|
||||
statusCode := steamimmich.Revalidate(config)
|
||||
os.Exit(statusCode)
|
||||
} else {
|
||||
statusCode := steamimmich.Run(config)
|
||||
os.Exit(statusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func findUserdataDir() string {
|
||||
var candidates []string
|
||||
|
||||
switch runtime.GOOS {
|
||||
case "windows":
|
||||
// Common Steam install paths on Windows
|
||||
localAppData := os.Getenv("LOCALAPPDATA")
|
||||
programFiles := os.Getenv("ProgramFiles(x86)")
|
||||
if programFiles == "" {
|
||||
programFiles = os.Getenv("ProgramFiles")
|
||||
}
|
||||
|
||||
candidates = []string{
|
||||
filepath.Join(programFiles, "Steam"),
|
||||
filepath.Join(localAppData, "Steam"),
|
||||
}
|
||||
|
||||
case "linux":
|
||||
home := os.Getenv("HOME")
|
||||
|
||||
candidates = []string{
|
||||
filepath.Join(home, ".steam", "steam"), // standard
|
||||
filepath.Join(home, ".local", "share", "Steam"), // alternate
|
||||
filepath.Join(home, ".var", "app", "com.valvesoftware.Steam", "data", "Steam"), // Flatpak
|
||||
}
|
||||
case "darwin":
|
||||
// Common Steam install path on macOS
|
||||
home := os.Getenv("HOME")
|
||||
candidates = []string{
|
||||
filepath.Join(home, "Library", "Application Support", "Steam"),
|
||||
}
|
||||
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
|
||||
for _, base := range candidates {
|
||||
userdata := filepath.Join(base, "userdata")
|
||||
info, err := os.Stat(userdata)
|
||||
if err == nil && info.IsDir() {
|
||||
return userdata
|
||||
}
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
27
flake.lock
generated
Normal file
27
flake.lock
generated
Normal file
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"nodes": {
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1762363567,
|
||||
"narHash": "sha256-YRqMDEtSMbitIMj+JLpheSz0pwEr0Rmy5mC7myl17xs=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "ae814fd3904b621d8ab97418f1d0f2eb0d3716f4",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "NixOS",
|
||||
"ref": "nixos-unstable",
|
||||
"repo": "nixpkgs",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"root": {
|
||||
"inputs": {
|
||||
"nixpkgs": "nixpkgs"
|
||||
}
|
||||
}
|
||||
},
|
||||
"root": "root",
|
||||
"version": 7
|
||||
}
|
||||
39
flake.nix
Normal file
39
flake.nix
Normal file
@@ -0,0 +1,39 @@
|
||||
{
|
||||
description = "Steam screenshot to Immich";
|
||||
|
||||
inputs = {
|
||||
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
|
||||
};
|
||||
|
||||
outputs =
|
||||
{ nixpkgs, ... }:
|
||||
let
|
||||
systems = [
|
||||
"x86_64-linux"
|
||||
"aarch64-linux"
|
||||
"x86_64-darwin"
|
||||
"aarch64-darwin"
|
||||
];
|
||||
|
||||
forAllSystems = nixpkgs.lib.genAttrs systems;
|
||||
|
||||
nixpkgsFor = forAllSystems (system: import nixpkgs { inherit system; });
|
||||
in
|
||||
{
|
||||
packages = forAllSystems (
|
||||
system:
|
||||
let
|
||||
pkgs = nixpkgsFor.${system};
|
||||
in
|
||||
{
|
||||
default = pkgs.buildGoModule {
|
||||
pname = "steamimmich";
|
||||
version = "0.1.0";
|
||||
src = ./.;
|
||||
|
||||
vendorHash = "sha256-lZ6wO1k0zwhlxhzNTU1jJz+liC9ly00StqkyrnuWSQM=";
|
||||
};
|
||||
}
|
||||
);
|
||||
};
|
||||
}
|
||||
7
go.mod
7
go.mod
@@ -2,7 +2,6 @@ module git.kapelle.org/niklas/steam-immich
|
||||
|
||||
go 1.24.6
|
||||
|
||||
require (
|
||||
github.com/alexflint/go-arg v1.6.0 // indirect
|
||||
github.com/alexflint/go-scalar v1.2.0 // indirect
|
||||
)
|
||||
require github.com/alexflint/go-arg v1.6.0
|
||||
|
||||
require github.com/alexflint/go-scalar v1.2.0 // indirect
|
||||
|
||||
6
go.sum
6
go.sum
@@ -2,6 +2,12 @@ github.com/alexflint/go-arg v1.6.0 h1:wPP9TwTPO54fUVQl4nZoxbFfKCcy5E6HBCumj1XVRS
|
||||
github.com/alexflint/go-arg v1.6.0/go.mod h1:A7vTJzvjoaSTypg4biM5uYNTkJ27SkNTArtYXnlqVO8=
|
||||
github.com/alexflint/go-scalar v1.2.0 h1:WR7JPKkeNpnYIOfHRa7ivM21aWAdHD0gEWHCx+WQBRw=
|
||||
github.com/alexflint/go-scalar v1.2.0/go.mod h1:LoFvNMqS1CPrMVltza4LvnGKhaSpc3oyLEBUZVhhS2o=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
gopkg.in/yaml.v3 v3.0.0 h1:hjy8E9ON/egN1tAYqKb61G10WtihqetD4sz2H+8nIeA=
|
||||
gopkg.in/yaml.v3 v3.0.0/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
|
||||
31
internal/hasher.go
Normal file
31
internal/hasher.go
Normal file
@@ -0,0 +1,31 @@
|
||||
package steamimmich
|
||||
|
||||
import (
|
||||
"crypto/sha1"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
func hashFiles(assets []assetState) (map[int]string, error) {
|
||||
results := make(map[int]string)
|
||||
|
||||
for i, p := range assets {
|
||||
f, err := os.Open(p.FilePath)
|
||||
if err != nil {
|
||||
results[i] = ""
|
||||
continue
|
||||
}
|
||||
|
||||
h := sha1.New()
|
||||
if _, err := io.Copy(h, f); err != nil {
|
||||
f.Close()
|
||||
return nil, err
|
||||
}
|
||||
f.Close()
|
||||
|
||||
results[i] = fmt.Sprintf("%x", h.Sum(nil))
|
||||
}
|
||||
|
||||
return results, nil
|
||||
}
|
||||
@@ -28,7 +28,40 @@ type bulkIdResponseDto struct {
|
||||
Success bool `json:"success"`
|
||||
}
|
||||
|
||||
func uploadToImmich(filePath, appID, baseURL, apiKey, deviceID string) (*uploadResponse, error) {
|
||||
type assetBulkUploadCheckItem struct {
|
||||
Checksum string `json:"checksum"`
|
||||
Id string `json:"id"` // Not the assetID. Just a arbitrarily id string
|
||||
}
|
||||
|
||||
type assetBulkUploadCheckResult struct {
|
||||
Action string // can be "accept" or "reject"
|
||||
AssetId string
|
||||
Id string // Not the assetID. Just a arbitrary id string
|
||||
IsTrashed bool
|
||||
Reason string // can be "duplicate" or "unsupportedFormat" (i don't know what they mean by this)
|
||||
}
|
||||
|
||||
type apiKeyTransport struct {
|
||||
APIKey string
|
||||
}
|
||||
|
||||
func (t *apiKeyTransport) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
req = req.Clone(req.Context())
|
||||
req.Header.Add("x-api-key", t.APIKey)
|
||||
return http.DefaultTransport.RoundTrip(req)
|
||||
}
|
||||
|
||||
func newImmichHttpClient(apiKey string) http.Client {
|
||||
transport := apiKeyTransport{
|
||||
APIKey: apiKey,
|
||||
}
|
||||
|
||||
return http.Client{
|
||||
Transport: &transport,
|
||||
}
|
||||
}
|
||||
|
||||
func uploadToImmich(filePath, appID, baseURL, deviceID string, httpClient *http.Client) (*uploadResponse, error) {
|
||||
file, err := os.Open(filePath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open file: %w", err)
|
||||
@@ -40,11 +73,9 @@ func uploadToImmich(filePath, appID, baseURL, apiKey, deviceID string) (*uploadR
|
||||
return nil, fmt.Errorf("stat file: %w", err)
|
||||
}
|
||||
|
||||
// Create multipart form
|
||||
var body bytes.Buffer
|
||||
writer := multipart.NewWriter(&body)
|
||||
|
||||
// Attach the image file
|
||||
part, err := writer.CreateFormFile("assetData", filepath.Base(filePath))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create form file: %w", err)
|
||||
@@ -54,9 +85,8 @@ func uploadToImmich(filePath, appID, baseURL, apiKey, deviceID string) (*uploadR
|
||||
}
|
||||
|
||||
modTime := fileInfo.ModTime().UTC().Format(time.RFC3339)
|
||||
createTime := modTime // If you don't have a separate created time
|
||||
createTime := modTime
|
||||
|
||||
// Required metadata fields
|
||||
writer.WriteField("deviceAssetId", fmt.Sprintf("%s-%s", appID, filepath.Base(filePath)))
|
||||
writer.WriteField("deviceId", deviceID)
|
||||
writer.WriteField("fileCreatedAt", createTime)
|
||||
@@ -65,17 +95,15 @@ func uploadToImmich(filePath, appID, baseURL, apiKey, deviceID string) (*uploadR
|
||||
|
||||
writer.Close()
|
||||
|
||||
// Build request
|
||||
req, err := http.NewRequest("POST", fmt.Sprintf("%s/api/assets", baseURL), &body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create request: %w", err)
|
||||
}
|
||||
req.Header.Set("x-api-key", apiKey)
|
||||
|
||||
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
req.Header.Set("Accept", "application/json")
|
||||
|
||||
client := &http.Client{Timeout: 60 * time.Second}
|
||||
resp, err := client.Do(req)
|
||||
resp, err := httpClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("POST to Immich: %w", err)
|
||||
}
|
||||
@@ -88,13 +116,13 @@ func uploadToImmich(filePath, appID, baseURL, apiKey, deviceID string) (*uploadR
|
||||
|
||||
var result uploadResponse
|
||||
if err := json.Unmarshal(respBody, &result); err != nil {
|
||||
return nil, fmt.Errorf("Failed to parse immich response: %s", err)
|
||||
return nil, fmt.Errorf("parse immich response: %s", err)
|
||||
}
|
||||
|
||||
return &result, nil
|
||||
}
|
||||
|
||||
func setAssetMetadata(assets []string, description, baseURL, apiKey string) error {
|
||||
func setAssetMetadata(assets []string, description, baseURL string, httpClient http.Client) error {
|
||||
body, _ := json.Marshal(assetPutRequest{
|
||||
Ids: assets,
|
||||
Description: description,
|
||||
@@ -105,11 +133,10 @@ func setAssetMetadata(assets []string, description, baseURL, apiKey string) erro
|
||||
return err
|
||||
}
|
||||
|
||||
req.Header.Set("x-api-key", apiKey)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Accept", "application/json")
|
||||
|
||||
_, err = http.DefaultClient.Do(req)
|
||||
_, err = httpClient.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -117,7 +144,7 @@ func setAssetMetadata(assets []string, description, baseURL, apiKey string) erro
|
||||
return nil
|
||||
}
|
||||
|
||||
func addAssetsToAlbum(assets []string, album, baseURL, apiKey string) error {
|
||||
func addAssetsToAlbum(assets []string, album, baseURL string, httpClient http.Client) error {
|
||||
body, _ := json.Marshal(struct {
|
||||
IDs []string `json:"ids"`
|
||||
}{IDs: assets})
|
||||
@@ -127,11 +154,10 @@ func addAssetsToAlbum(assets []string, album, baseURL, apiKey string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
req.Header.Set("x-api-key", apiKey)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Accept", "application/json")
|
||||
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
res, err := httpClient.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -139,14 +165,49 @@ func addAssetsToAlbum(assets []string, album, baseURL, apiKey string) error {
|
||||
defer res.Body.Close()
|
||||
|
||||
respBody, _ := io.ReadAll(res.Body)
|
||||
if res.StatusCode >= 300 {
|
||||
return fmt.Errorf("Failed to add assets to album (%d): %s", res.StatusCode, string(respBody))
|
||||
if res.StatusCode != 200 {
|
||||
return fmt.Errorf("add assets to album (%d): %s", res.StatusCode, string(respBody))
|
||||
}
|
||||
|
||||
var result []bulkIdResponseDto
|
||||
if err := json.Unmarshal(respBody, &result); err != nil {
|
||||
return fmt.Errorf("Failed to parse immich response: %s", err)
|
||||
return fmt.Errorf("parse immich response: %s", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func bulkCheckAssets(assets []assetBulkUploadCheckItem, baseURL string, httpClient http.Client) ([]assetBulkUploadCheckResult, error) {
|
||||
body, _ := json.Marshal(struct {
|
||||
Assets []assetBulkUploadCheckItem `json:"assets"`
|
||||
}{Assets: assets})
|
||||
|
||||
req, err := http.NewRequest("POST", fmt.Sprintf("%s/api/assets/bulk-upload-check", baseURL), bytes.NewBuffer(body))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Accept", "application/json")
|
||||
|
||||
res, err := httpClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defer res.Body.Close()
|
||||
|
||||
respBody, _ := io.ReadAll(res.Body)
|
||||
if res.StatusCode != 200 {
|
||||
return nil, fmt.Errorf("buck check assets %d - %s ", res.StatusCode, string(respBody))
|
||||
}
|
||||
|
||||
var result struct {
|
||||
Results []assetBulkUploadCheckResult `json:"results"`
|
||||
}
|
||||
if err := json.Unmarshal(respBody, &result); err != nil {
|
||||
return nil, fmt.Errorf("parse immich response: %s", err)
|
||||
}
|
||||
|
||||
return result.Results, nil
|
||||
}
|
||||
|
||||
50
internal/localstate.go
Normal file
50
internal/localstate.go
Normal file
@@ -0,0 +1,50 @@
|
||||
package steamimmich
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
type assetState struct {
|
||||
FilePath string
|
||||
ImmichID string
|
||||
}
|
||||
|
||||
type localState struct {
|
||||
Assets []assetState
|
||||
GameIDs map[string]string
|
||||
}
|
||||
|
||||
func loadLocalState(filename string) (*localState, error) {
|
||||
file, err := os.Open(filename)
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return &localState{Assets: []assetState{}, GameIDs: map[string]string{}}, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
content, err := io.ReadAll(file)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var data localState
|
||||
err = json.Unmarshal(content, &data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &data, nil
|
||||
}
|
||||
|
||||
func saveLocalState(filename string, state localState) error {
|
||||
content, err := json.Marshal(state)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return os.WriteFile(filename, content, 0644)
|
||||
}
|
||||
@@ -4,52 +4,58 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
const UNKOWN_GAME_GAME = "Unkown"
|
||||
|
||||
type SteamAPIResponse struct {
|
||||
type steamAPIResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Data struct {
|
||||
Name string `json:"name"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
func getGameName(appid string, cache map[string]string) string {
|
||||
if name, ok := cache[appid]; ok {
|
||||
func getGameName(appID string, cache map[string]string) string {
|
||||
if name, ok := cache[appID]; ok {
|
||||
return name
|
||||
}
|
||||
|
||||
url := fmt.Sprintf("https://store.steampowered.com/api/appdetails?appids=%s", appid)
|
||||
name, err := fetchGameName(appID)
|
||||
if err != nil {
|
||||
slog.Warn("Failed to fetch name for AppID. Setting to Unknown", "appid", appID)
|
||||
cache[appID] = UNKOWN_GAME_GAME
|
||||
return UNKOWN_GAME_GAME
|
||||
}
|
||||
|
||||
cache[appID] = name
|
||||
return name
|
||||
}
|
||||
|
||||
func fetchGameName(appID string) (string, error) {
|
||||
url := fmt.Sprintf("https://store.steampowered.com/api/appdetails?appids=%s", appID)
|
||||
resp, err := http.Get(url)
|
||||
if err != nil {
|
||||
fmt.Printf("Error fetching app name for %s: %v\n", appid, err)
|
||||
cache[appid] = UNKOWN_GAME_GAME
|
||||
return cache[appid]
|
||||
return "", fmt.Errorf("fetching game name for %s: %s", appID, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
fmt.Printf("Error reading response for %s: %v\n", appid, err)
|
||||
cache[appid] = UNKOWN_GAME_GAME
|
||||
return cache[appid]
|
||||
return "", fmt.Errorf("reading response for %s: %s", appID, err)
|
||||
}
|
||||
|
||||
var result map[string]SteamAPIResponse
|
||||
var result map[string]steamAPIResponse
|
||||
if err := json.Unmarshal(body, &result); err != nil {
|
||||
fmt.Printf("Error parsing JSON for %s: %v\n", appid, err)
|
||||
cache[appid] = UNKOWN_GAME_GAME
|
||||
return cache[appid]
|
||||
return "", fmt.Errorf("parsing response for %s: %s", appID, err)
|
||||
}
|
||||
|
||||
if entry, ok := result[appid]; ok && entry.Success {
|
||||
name := entry.Data.Name
|
||||
cache[appid] = name
|
||||
return name
|
||||
entry, ok := result[appID]
|
||||
|
||||
if !ok || !entry.Success {
|
||||
return "", fmt.Errorf("game not found in response for %s", appID)
|
||||
}
|
||||
|
||||
cache[appid] = UNKOWN_GAME_GAME
|
||||
return cache[appid]
|
||||
return entry.Data.Name, nil
|
||||
}
|
||||
|
||||
@@ -2,7 +2,10 @@ package steamimmich
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"log/slog"
|
||||
"slices"
|
||||
"sort"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
@@ -10,57 +13,168 @@ type Config struct {
|
||||
APIKey string
|
||||
UserdataDir string
|
||||
DeiveID string
|
||||
Album string
|
||||
CacheFile string
|
||||
}
|
||||
|
||||
func Run(config Config) {
|
||||
func Run(config Config) int {
|
||||
screenshotFiles, err := listScreenshots(config.UserdataDir)
|
||||
|
||||
if err != nil {
|
||||
fmt.Println("Failed to scan for screenshots")
|
||||
os.Exit(1)
|
||||
slog.Error("Failed to scan for screenshots", "err", err)
|
||||
return 1
|
||||
}
|
||||
|
||||
if len(screenshotFiles) == 0 {
|
||||
fmt.Println("No screenshots found.")
|
||||
return
|
||||
slog.Info("No screenshots found")
|
||||
return 0
|
||||
}
|
||||
|
||||
gameNameCache := make(map[string]string)
|
||||
immichClient := newImmichHttpClient(config.APIKey)
|
||||
|
||||
localState, err := loadLocalState(config.CacheFile)
|
||||
if err != nil {
|
||||
slog.Error("Failed to load local cache", "err", err)
|
||||
return 1
|
||||
}
|
||||
|
||||
for appid, files := range screenshotFiles {
|
||||
gameName := getGameName(appid, gameNameCache)
|
||||
fmt.Printf("AppID: %s → %s\n", appid, gameName)
|
||||
|
||||
gameName := getGameName(appid, localState.GameIDs)
|
||||
assetsInGame := make([]string, 0)
|
||||
|
||||
for _, f := range files {
|
||||
fmt.Printf(" %s\n", f)
|
||||
for _, filepath := range files {
|
||||
|
||||
res, err := uploadToImmich(f, appid, config.BaseURL, config.APIKey, config.DeiveID)
|
||||
idx := slices.IndexFunc(localState.Assets, func(e assetState) bool { return e.FilePath == filepath })
|
||||
|
||||
if err != nil {
|
||||
fmt.Printf("Failed to upload to immich: %s", err)
|
||||
return
|
||||
if idx != -1 {
|
||||
slog.Debug("Asset already uploaded", "path", filepath)
|
||||
continue
|
||||
}
|
||||
|
||||
fmt.Printf("Done. ID: %s", res.ID)
|
||||
res, err := uploadToImmich(filepath, appid, config.BaseURL, config.DeiveID, &immichClient)
|
||||
|
||||
if err != nil {
|
||||
slog.Error("Failed to upload to immich", "err", err)
|
||||
return 1
|
||||
}
|
||||
|
||||
slog.Info("Assets uploaded", "path", filepath, "id", res.ID)
|
||||
|
||||
localState.Assets = append(localState.Assets, assetState{FilePath: filepath, ImmichID: res.ID})
|
||||
|
||||
assetsInGame = append(assetsInGame, res.ID)
|
||||
}
|
||||
|
||||
err := setAssetMetadata(assetsInGame, fmt.Sprintf("Game: %s", gameName), config.BaseURL, config.APIKey)
|
||||
err := setAssetMetadata(assetsInGame, fmt.Sprintf("Game: %s", gameName), config.BaseURL, immichClient)
|
||||
if err != nil {
|
||||
fmt.Printf("Stopped: %s", err)
|
||||
slog.Error("Failed to set assets metadata", "err", err)
|
||||
return 1
|
||||
}
|
||||
|
||||
if config.Album != "" {
|
||||
err = addAssetsToAlbum(assetsInGame, config.Album, config.BaseURL, config.APIKey)
|
||||
err = addAssetsToAlbum(assetsInGame, config.Album, config.BaseURL, immichClient)
|
||||
if err != nil {
|
||||
fmt.Printf("Stopped: %s", err)
|
||||
slog.Error("Failed to add assets to album", "err", err)
|
||||
return 1
|
||||
}
|
||||
|
||||
if len(assetsInGame) > 0 {
|
||||
slog.Info("Added assets to album", "count", len(assetsInGame))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Println()
|
||||
slog.Info("Finished uploading screenshots")
|
||||
err = saveLocalState(config.CacheFile, *localState)
|
||||
if err != nil {
|
||||
slog.Error("Failed to save local cache", "err", err)
|
||||
return 1
|
||||
}
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
func Revalidate(config Config) int {
|
||||
immichClient := newImmichHttpClient(config.APIKey)
|
||||
|
||||
localState, err := loadLocalState(config.CacheFile)
|
||||
if err != nil {
|
||||
slog.Error("Failed to load local cache", "err", err)
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
hashes, err := hashFiles(localState.Assets)
|
||||
if err != nil {
|
||||
slog.Error("Failed to generate hashes", "err", err)
|
||||
return 1
|
||||
}
|
||||
|
||||
idxToRemoveFromCache := []int{}
|
||||
|
||||
rejected := 0
|
||||
updated := 0
|
||||
missingFromImmich := 0
|
||||
missingFile := 0
|
||||
|
||||
// Prepare payload
|
||||
var idsToCheck = []assetBulkUploadCheckItem{}
|
||||
for i := range localState.Assets {
|
||||
hash := hashes[i]
|
||||
if hash == "" {
|
||||
idxToRemoveFromCache = append(idxToRemoveFromCache, i)
|
||||
missingFile += 1
|
||||
} else {
|
||||
idsToCheck = append(idsToCheck, assetBulkUploadCheckItem{Checksum: hashes[i], Id: strconv.Itoa(i)})
|
||||
}
|
||||
}
|
||||
|
||||
results, err := bulkCheckAssets(idsToCheck, config.BaseURL, immichClient)
|
||||
if err != nil {
|
||||
slog.Error("Failed to bulk check hashes", "err", err)
|
||||
return 1
|
||||
}
|
||||
|
||||
for _, result := range results {
|
||||
i, err := strconv.Atoi(result.Id)
|
||||
if err != nil {
|
||||
slog.Error("What ? This should never happen", "err", err)
|
||||
return 1
|
||||
}
|
||||
|
||||
asset := localState.Assets[i]
|
||||
|
||||
if asset.ImmichID != result.AssetId {
|
||||
slog.Info("Asset has the wrong Immich ID", "path", asset.FilePath, "id", result.AssetId)
|
||||
localState.Assets[i].ImmichID = result.AssetId
|
||||
updated += 1
|
||||
}
|
||||
|
||||
if result.Action == "reject" {
|
||||
rejected += 1
|
||||
} else {
|
||||
idxToRemoveFromCache = append(idxToRemoveFromCache, i)
|
||||
missingFromImmich += 1
|
||||
}
|
||||
}
|
||||
|
||||
sort.Sort(sort.Reverse(sort.IntSlice(idxToRemoveFromCache)))
|
||||
for _, idx := range idxToRemoveFromCache {
|
||||
localState.Assets[idx] = localState.Assets[len(localState.Assets)-1]
|
||||
localState.Assets = localState.Assets[:len(localState.Assets)-1]
|
||||
}
|
||||
|
||||
saveLocalState(config.CacheFile, *localState)
|
||||
|
||||
slog.Info("Revalidated assets", "count", len(localState.Assets))
|
||||
slog.Info("Assets present on immich", "count", rejected)
|
||||
slog.Info("Wrong metadata on cache", "count", updated)
|
||||
slog.Info("Missing on Immich", "count", missingFromImmich)
|
||||
slog.Info("Missing on local storage", "count", missingFile)
|
||||
|
||||
if (updated + missingFromImmich + missingFromImmich) > 0 {
|
||||
slog.Info("Fixed cache. Run the normal upload command again. If error persists try removing cache file", "path", config.CacheFile)
|
||||
}
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user