Compare commits

..

4 Commits

Author SHA1 Message Date
a25b4abdc1 added LICENSE 2025-11-21 15:46:59 +01:00
f1958b399a added README 2025-11-21 14:58:07 +01:00
239373d5a3 improved logging 2025-11-20 23:16:16 +01:00
0e47fb6983 renamed some structs to make the private 2025-11-20 15:44:28 +01:00
8 changed files with 305 additions and 59 deletions

201
LICENSE Normal file
View 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
View 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.

View File

@@ -1,7 +1,7 @@
package cmd package cmd
import ( import (
"log" "log/slog"
"os" "os"
"path/filepath" "path/filepath"
"runtime" "runtime"
@@ -17,13 +17,18 @@ type args struct {
DeviceID string `arg:"--device-id" default:"steam-immich" help:"Device ID of the uploads"` 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"` 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"` CacheFile string `arg:"--cache" default:"$XDG_CACHE_HOME/steam-immich.json" help:"Location of the cache file"`
Revalidate bool `args:"--revalidate" default:"false" help:"Only revalidate and fix the cache"` Revalidate bool `arg:"--revalidate" help:"Only revalidate and fix the cache"`
Verbose bool `arg:"-v,--verbose" help:"Toggle verbose logging"`
} }
func Run() { func Run() {
var args args var args args
arg.MustParse(&args) arg.MustParse(&args)
if args.Verbose {
slog.SetLogLoggerLevel(slog.LevelDebug)
}
var steamUserdataDir = "" var steamUserdataDir = ""
if args.UserdataDir != "" { if args.UserdataDir != "" {
@@ -33,12 +38,10 @@ func Run() {
} }
if steamUserdataDir == "" { if steamUserdataDir == "" {
log.Fatal("Can not find steam userdata dir. Please set with --steam-userdata-dir") slog.Error("Can not find steam userdata dir. Please set with --steam-userdata-dir")
os.Exit(1)
} }
// Disable timestamp in log
log.SetFlags(0)
config := steamimmich.Config{ config := steamimmich.Config{
APIKey: args.APIKey, APIKey: args.APIKey,
BaseURL: args.BaseURL, BaseURL: args.BaseURL,
@@ -49,9 +52,11 @@ func Run() {
} }
if args.Revalidate { if args.Revalidate {
steamimmich.Revalidate(config) statusCode := steamimmich.Revalidate(config)
os.Exit(statusCode)
} else { } else {
steamimmich.Run(config) statusCode := steamimmich.Run(config)
os.Exit(statusCode)
} }
} }

View File

@@ -7,7 +7,7 @@ import (
"os" "os"
) )
func hashFiles(assets []AssetState) (map[int]string, error) { func hashFiles(assets []assetState) (map[int]string, error) {
results := make(map[int]string) results := make(map[int]string)
for i, p := range assets { for i, p := range assets {

View File

@@ -41,18 +41,18 @@ type assetBulkUploadCheckResult struct {
Reason string // can be "duplicate" or "unsupportedFormat" (i don't know what they mean by this) Reason string // can be "duplicate" or "unsupportedFormat" (i don't know what they mean by this)
} }
type APIKeyTransport struct { type apiKeyTransport struct {
APIKey string APIKey string
} }
func (t *APIKeyTransport) RoundTrip(req *http.Request) (*http.Response, error) { func (t *apiKeyTransport) RoundTrip(req *http.Request) (*http.Response, error) {
req = req.Clone(req.Context()) req = req.Clone(req.Context())
req.Header.Add("x-api-key", t.APIKey) req.Header.Add("x-api-key", t.APIKey)
return http.DefaultTransport.RoundTrip(req) return http.DefaultTransport.RoundTrip(req)
} }
func newImmichHttpClient(apiKey string) http.Client { func newImmichHttpClient(apiKey string) http.Client {
transport := APIKeyTransport{ transport := apiKeyTransport{
APIKey: apiKey, APIKey: apiKey,
} }

View File

@@ -7,21 +7,21 @@ import (
"os" "os"
) )
type AssetState struct { type assetState struct {
FilePath string FilePath string
ImmichID string ImmichID string
} }
type LocalState struct { type localState struct {
Assets []AssetState Assets []assetState
GameIDs map[string]string GameIDs map[string]string
} }
func loadLocalState(filename string) (*LocalState, error) { func loadLocalState(filename string) (*localState, error) {
file, err := os.Open(filename) file, err := os.Open(filename)
if err != nil { if err != nil {
if errors.Is(err, os.ErrNotExist) { if errors.Is(err, os.ErrNotExist) {
return &LocalState{Assets: []AssetState{}, GameIDs: map[string]string{}}, nil return &localState{Assets: []assetState{}, GameIDs: map[string]string{}}, nil
} }
return nil, err return nil, err
} }
@@ -31,7 +31,7 @@ func loadLocalState(filename string) (*LocalState, error) {
return nil, err return nil, err
} }
var data LocalState var data localState
err = json.Unmarshal(content, &data) err = json.Unmarshal(content, &data)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -40,7 +40,7 @@ func loadLocalState(filename string) (*LocalState, error) {
return &data, nil return &data, nil
} }
func saveLocalState(filename string, state LocalState) error { func saveLocalState(filename string, state localState) error {
content, err := json.Marshal(state) content, err := json.Marshal(state)
if err != nil { if err != nil {
return err return err

View File

@@ -4,13 +4,13 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
"log" "log/slog"
"net/http" "net/http"
) )
const UNKOWN_GAME_GAME = "Unkown" const UNKOWN_GAME_GAME = "Unkown"
type SteamAPIResponse struct { type steamAPIResponse struct {
Success bool `json:"success"` Success bool `json:"success"`
Data struct { Data struct {
Name string `json:"name"` Name string `json:"name"`
@@ -24,7 +24,7 @@ func getGameName(appID string, cache map[string]string) string {
name, err := fetchGameName(appID) name, err := fetchGameName(appID)
if err != nil { if err != nil {
log.Printf("failed to fetch name for AppID: %s. Setting to Unknown", appID) slog.Warn("Failed to fetch name for AppID. Setting to Unknown", "appid", appID)
cache[appID] = UNKOWN_GAME_GAME cache[appID] = UNKOWN_GAME_GAME
return UNKOWN_GAME_GAME return UNKOWN_GAME_GAME
} }
@@ -46,7 +46,7 @@ func fetchGameName(appID string) (string, error) {
return "", fmt.Errorf("reading response for %s: %s", appID, err) 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 { if err := json.Unmarshal(body, &result); err != nil {
return "", fmt.Errorf("parsing response for %s: %s", appID, err) return "", fmt.Errorf("parsing response for %s: %s", appID, err)
} }

View File

@@ -2,7 +2,7 @@ package steamimmich
import ( import (
"fmt" "fmt"
"log" "log/slog"
"slices" "slices"
"sort" "sort"
"strconv" "strconv"
@@ -17,24 +17,25 @@ type Config struct {
CacheFile string CacheFile string
} }
func Run(config Config) { func Run(config Config) int {
screenshotFiles, err := listScreenshots(config.UserdataDir) screenshotFiles, err := listScreenshots(config.UserdataDir)
if err != nil { if err != nil {
log.Fatalf("Failed to scan for screenshots: %s", err) slog.Error("Failed to scan for screenshots", "err", err)
return return 1
} }
if len(screenshotFiles) == 0 { if len(screenshotFiles) == 0 {
log.Println("No screenshots found.") slog.Info("No screenshots found")
return return 0
} }
immichClient := newImmichHttpClient(config.APIKey) immichClient := newImmichHttpClient(config.APIKey)
localState, err := loadLocalState(config.CacheFile) localState, err := loadLocalState(config.CacheFile)
if err != nil { if err != nil {
log.Fatalf("Failed to load local state: %s", err) slog.Error("Failed to load local cache", "err", err)
return 1
} }
for appid, files := range screenshotFiles { for appid, files := range screenshotFiles {
@@ -43,65 +44,70 @@ func Run(config Config) {
for _, filepath := range files { for _, filepath := range files {
idx := slices.IndexFunc(localState.Assets, func(e AssetState) bool { return e.FilePath == filepath }) idx := slices.IndexFunc(localState.Assets, func(e assetState) bool { return e.FilePath == filepath })
if idx != -1 { if idx != -1 {
log.Printf("Asset already uploaded: %s", filepath) slog.Debug("Asset already uploaded", "path", filepath)
continue continue
} }
res, err := uploadToImmich(filepath, appid, config.BaseURL, config.DeiveID, &immichClient) res, err := uploadToImmich(filepath, appid, config.BaseURL, config.DeiveID, &immichClient)
if err != nil { if err != nil {
log.Fatalf("Failed to upload to immich: %s", err) slog.Error("Failed to upload to immich", "err", err)
return return 1
} }
log.Printf("Assest uploaded: %s (%s) %s with ID: %s", gameName, appid, filepath, res.ID) slog.Info("Assets uploaded", "path", filepath, "id", res.ID)
localState.Assets = append(localState.Assets, AssetState{FilePath: filepath, ImmichID: res.ID}) localState.Assets = append(localState.Assets, assetState{FilePath: filepath, ImmichID: res.ID})
assetsInGame = append(assetsInGame, res.ID) assetsInGame = append(assetsInGame, res.ID)
} }
err := setAssetMetadata(assetsInGame, fmt.Sprintf("Game: %s", gameName), config.BaseURL, immichClient) err := setAssetMetadata(assetsInGame, fmt.Sprintf("Game: %s", gameName), config.BaseURL, immichClient)
if err != nil { if err != nil {
log.Fatalf("Failed to set asset metadata: %s", err) slog.Error("Failed to set assets metadata", "err", err)
return return 1
} }
if config.Album != "" { if config.Album != "" {
err = addAssetsToAlbum(assetsInGame, config.Album, config.BaseURL, immichClient) err = addAssetsToAlbum(assetsInGame, config.Album, config.BaseURL, immichClient)
if err != nil { if err != nil {
log.Fatalf("Failed to add assets to album: %s", err) slog.Error("Failed to add assets to album", "err", err)
return return 1
} }
log.Printf("Added %d assets to album %s", len(assetsInGame), config.Album) if len(assetsInGame) > 0 {
slog.Info("Added assets to album", "count", len(assetsInGame))
}
} }
} }
log.Println("Finished uploading screenshots") slog.Info("Finished uploading screenshots")
err = saveLocalState(config.CacheFile, *localState) err = saveLocalState(config.CacheFile, *localState)
if err != nil { if err != nil {
log.Fatalf("Failed to save local cache: %s", err) slog.Error("Failed to save local cache", "err", err)
return return 1
}
} }
func Revalidate(config Config) { return 0
}
func Revalidate(config Config) int {
immichClient := newImmichHttpClient(config.APIKey) immichClient := newImmichHttpClient(config.APIKey)
localState, err := loadLocalState(config.CacheFile) localState, err := loadLocalState(config.CacheFile)
if err != nil { if err != nil {
log.Fatalf("Failed to load local state: %s", err) slog.Error("Failed to load local cache", "err", err)
return
return 1
} }
hashes, err := hashFiles(localState.Assets) hashes, err := hashFiles(localState.Assets)
if err != nil { if err != nil {
log.Fatalf("Failed to generate hashes: %s", err) slog.Error("Failed to generate hashes", "err", err)
return return 1
} }
idxToRemoveFromCache := []int{} idxToRemoveFromCache := []int{}
@@ -125,20 +131,21 @@ func Revalidate(config Config) {
results, err := bulkCheckAssets(idsToCheck, config.BaseURL, immichClient) results, err := bulkCheckAssets(idsToCheck, config.BaseURL, immichClient)
if err != nil { if err != nil {
log.Fatalf("Failed to bulk check hashes: %s", err) slog.Error("Failed to bulk check hashes", "err", err)
return 1
} }
for _, result := range results { for _, result := range results {
i, err := strconv.Atoi(result.Id) i, err := strconv.Atoi(result.Id)
if err != nil { if err != nil {
log.Fatalf("What ?: %s", err) slog.Error("What ? This should never happen", "err", err)
return return 1
} }
asset := localState.Assets[i] asset := localState.Assets[i]
if asset.ImmichID != result.AssetId { if asset.ImmichID != result.AssetId {
log.Printf("Asset %s had the wrong Immich ID. New %s", asset.FilePath, result.AssetId) slog.Info("Asset has the wrong Immich ID", "path", asset.FilePath, "id", result.AssetId)
localState.Assets[i].ImmichID = result.AssetId localState.Assets[i].ImmichID = result.AssetId
updated += 1 updated += 1
} }
@@ -159,13 +166,15 @@ func Revalidate(config Config) {
saveLocalState(config.CacheFile, *localState) saveLocalState(config.CacheFile, *localState)
log.Printf("Revalidated %d assets", len(results)) slog.Info("Revalidated assets", "count", len(localState.Assets))
log.Printf("Assets present on Immich: %d", rejected) slog.Info("Assets present on immich", "count", rejected)
log.Printf("Wrong metadata on cache: %d", updated) slog.Info("Wrong metadata on cache", "count", updated)
log.Printf("Missing on Immich: %d", missingFromImmich) slog.Info("Missing on Immich", "count", missingFromImmich)
log.Printf("Missing on local storage: %d", missingFile) slog.Info("Missing on local storage", "count", missingFile)
if (updated + missingFromImmich + missingFromImmich) > 0 { if (updated + missingFromImmich + missingFromImmich) > 0 {
log.Printf("Fixed cache. Run the normal upload command again. If error persists try removing cache file at: %s", config.CacheFile) slog.Info("Fixed cache. Run the normal upload command again. If error persists try removing cache file", "path", config.CacheFile)
} }
return 0
} }