Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add memories asset bucket #266

Merged
merged 7 commits into from
Jan 14, 2025
Merged

add memories asset bucket #266

merged 7 commits into from
Jan 14, 2025

Conversation

damongolding
Copy link
Owner

@damongolding damongolding commented Jan 14, 2025

Summary by CodeRabbit

Release Notes

  • New Features

    • Added memory lane functionality to retrieve and display images from past memories.
    • Introduced configuration option to enable memory-based image selection.
  • Improvements

    • Enhanced image source handling to support memory lane assets.
    • Updated metadata display to show memory lane source information.
    • Improved URL path construction and date range parsing.
  • Technical Updates

    • Added new API response type for memory lane data.
    • Introduced new source type for memory-based image selection.
    • Added new environment variable for memory display configuration.

@damongolding damongolding added the enhancement New feature or request label Jan 14, 2025
Copy link
Contributor

coderabbitai bot commented Jan 14, 2025

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 golangci-lint (1.62.2)

level=warning msg="[runner] Can't run linter goanalysis_metalinter: buildir: failed to load package : could not load export data: no export data for "github.com/damongolding/immich-kiosk/internal/templates/components/image""
level=error msg="Running error: can't run linter goanalysis_metalinter\nbuildir: failed to load package : could not load export data: no export data for "github.com/damongolding/immich-kiosk/internal/templates/components/image""

Walkthrough

This pull request introduces enhancements for memory lane functionality within the application. It includes the addition of a new boolean field, Memories, to the Config struct, enabling users to manage the display of memory-related features. The implementation spans multiple files, introducing methods for fetching memory lane data, counting assets, and selecting random images from memories. Additionally, the metadata display logic is updated to accommodate memories as a new source of images, thereby expanding the application's capabilities in handling user input regarding memories.

Changes

File Change Summary
internal/config/config.go Added Memories bool field to Config struct and updated ConfigWithOverrides method for query handling.
internal/immich/immich.go Introduced MemoryLaneResponse type and updated ImmichApiResponse interface.
internal/immich/immich_album.go Refactored path construction and converted countAssetsInAlbums to a standalone function.
internal/immich/immich_date.go Fixed date parsing in randomImageInDateRange method.
internal/immich/immich_memories.go Added methods for memory lane functionality, including fetching and counting assets.
internal/kiosk/kiosk.go Added SourceMemories constant.
internal/routes/routes_image_helpers.go Added logic to handle memory lane asset retrieval.
internal/templates/components/image/metadata.templ Updated metadata display logic for memory sources.
README.md Added KIOSK_MEMORIES configuration option.
config.example.yaml Added memories: false configuration option.

Sequence Diagram

sequenceDiagram
    participant User
    participant Config
    participant ImmichAsset
    participant API
    
    User->>Config: Request images with Memories=true
    Config->>ImmichAsset: Call MemoryLaneAssetsCount
    ImmichAsset->>API: Fetch memory lane data
    API-->>ImmichAsset: Return memories
    ImmichAsset->>ImmichAsset: Select random memory image
    ImmichAsset-->>User: Return memory lane image
Loading

Possibly related PRs

  • album ordering #265: The changes in this PR introduce a new field AlbumOrder to the Config struct, which is related to the configuration management enhancements in the main PR that adds the Memories field to the same struct. Both PRs modify the Config struct to manage different aspects of the application's configuration.

Poem

🐰 Memories dance, pixels take flight,
A rabbit's tale of digital delight!
Through albums and years, images gleam,
Nostalgia woven in a pixelated dream.
Code hops, memories unfold with glee! 🖼️

Finishing Touches

  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (2)
internal/immich/immich_memories.go (1)

32-33: Correct typographical errors in comments

There are typographical errors in the comments: "seperate" should be "separate", and "becasue" should be "because".

Apply this diff to correct the typos:

-    // If we want the memories assets count we will use a seperate cache entry
-    // becasue Kiosk removes used assets from the normal cache entry
+    // If we want the memories assets count, we will use a separate cache entry
+    // because Kiosk removes used assets from the normal cache entry
internal/config/config.go (1)

207-208: LGTM! Consider adding documentation.

The Memories field is well-integrated with appropriate tags. Consider adding a documentation comment to describe its purpose and behaviour, following the pattern used for other fields in the struct.

Add this documentation above the field:

+	// Memories enables the display of memory lane assets
 	Memories bool `json:"memories" mapstructure:"memories" query:"memories" form:"memories" default:"false"`
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d701ae9 and f9e99ff.

📒 Files selected for processing (8)
  • internal/config/config.go (2 hunks)
  • internal/immich/immich.go (2 hunks)
  • internal/immich/immich_album.go (3 hunks)
  • internal/immich/immich_date.go (1 hunks)
  • internal/immich/immich_memories.go (1 hunks)
  • internal/kiosk/kiosk.go (1 hunks)
  • internal/routes/routes_image_helpers.go (2 hunks)
  • internal/templates/components/image/metadata.templ (2 hunks)
🔇 Additional comments (11)
internal/kiosk/kiosk.go (1)

15-15: Looks good!

The addition of SourceMemories correctly extends the Source type to include memories as a new source.

internal/immich/immich_date.go (1)

42-47: Looks good!

The date parsing logic has been corrected to properly extract the start and end dates from the dateRange string.

internal/templates/components/image/metadata.templ (2)

Line range hint 123-131: LGTM! The function name change better reflects its purpose.

The renaming from shouldShowAlbumPersonName to shouldShowSourceName and the inclusion of SourceMemories in the album source check aligns well with the broader scope of source types.


137-141: LGTM! Variable name updated for consistency.

The variable renaming from showAlbumPersonName to showSourceName maintains consistency with the function name change.

internal/immich/immich_album.go (2)

30-30: LGTM! More robust URL path construction.

Using path.Join is a more robust way to construct URL paths as it handles path separators correctly.


Line range hint 105-110: LGTM! Function scope change improves code organisation.

Moving countAssetsInAlbums from a method to a standalone function is appropriate as it doesn't require access to the receiver's state.

internal/immich/immich.go (2)

221-225: LGTM! Well-structured type definition for memory lane data.

The MemoryLaneResponse type effectively models the memory lane data structure with appropriate JSON tags.


236-236: LGTM! Interface updated to support new response type.

The ImmichApiResponse interface has been correctly updated to include MemoryLaneResponse.

internal/routes/routes_image_helpers.go (2)

85-94: LGTM! Memory lane asset handling is well-implemented.

The implementation correctly:

  • Checks the configuration flag
  • Handles the error case of zero assets
  • Adds appropriate weighting for memory lane assets

150-151: LGTM! Memory lane image retrieval case added.

The new case for SourceMemories aligns well with the existing pattern of source-specific image retrieval.

internal/config/config.go (1)

414-414: LGTM! Consistent handling of query parameters.

The addition of the memories parameter to the condition maintains consistency with how other image source parameters are handled.

internal/immich/immich_memories.go Show resolved Hide resolved
internal/immich/immich_memories.go Outdated Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (1)
internal/immich/immich_memories.go (1)

25-26: ⚠️ Potential issue

Avoid using log.Fatal in library code; return error instead

Using log.Fatal(err) will terminate the entire application upon encountering an error, which may not be appropriate in library code. Instead, return the error to allow the caller to handle it gracefully.

Apply this diff to handle the error properly:

     if err != nil {
-        log.Fatal(err)
+        return memoryLane, "", err
     }
🧹 Nitpick comments (3)
internal/immich/immich_memories.go (3)

38-38: Fix typo in comment: 'becasue' → 'because'

There is a typo in the comment; correcting it improves readability.

Apply this diff to correct the typo:

-	// becasue Kiosk removes used assets from the normal cache entry
+	// because Kiosk removes used assets from the normal cache entry

58-58: Fix typo in comment: 'sepetate' → 'separate'

There is a typo in the comment; correcting it improves readability.

Apply this diff to correct the typo:

-// that counts the total assets in memory lane using a sepetate cache entry
+// that counts the total assets in memory lane using a separate cache entry

118-118: Clarify comment for asset filtering condition

The comment can be improved for clarity. Suggest rephrasing to enhance readability.

Apply this diff to rephrase the comment:

-		// We only want images and that are not trashed or archived (unless wanted by user)
+		// We only want images that are not trashed or archived (unless desired by user)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f9e99ff and db11e04.

📒 Files selected for processing (3)
  • README.md (2 hunks)
  • config.example.yaml (1 hunks)
  • internal/immich/immich_memories.go (1 hunks)
🔇 Additional comments (5)
internal/immich/immich_memories.go (2)

6-6: ⚠️ Potential issue

Correct import path for 'math/rand' package

The import statement import ("math/rand/v2") may be incorrect, as the standard library's math/rand package does not use a versioned path. Unless you are using a specific versioned package, you should import math/rand directly to prevent compile errors.

Apply this diff to fix the import statement:

-import (
-	"math/rand/v2"
+import (
+	"math/rand"

Likely invalid or redundant comment.


88-88: Verify that MaxRetries is defined and properly scoped

Ensure that MaxRetries is defined and accessible within this context to avoid undefined variable errors.

Run the following script to check for the definition of MaxRetries:

✅ Verification successful

MaxRetries constant is properly defined and accessible

The constant is defined in internal/immich/immich.go with a value of 3 and is correctly accessible within the package scope.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for the definition of MaxRetries in the codebase

# Expected: MaxRetries should be defined and accessible in the package

# Search for MaxRetries definition
rg -A 2 -B 2 'const\s+MaxRetries\s*='

Length of output: 39


Script:

#!/bin/bash
# Search for any MaxRetries declarations or assignments
rg -i "maxretries\s*[=:]" -A 2 -B 2

# Search for any MaxRetries usage to understand context
rg -i "\bmaxretries\b" -A 2 -B 2

# Use ast-grep to find variable declarations
ast-grep --pattern 'var MaxRetries = $_'
ast-grep --pattern 'const MaxRetries = $_'

Length of output: 1406

config.example.yaml (1)

37-37: Addition of 'memories' configuration option looks good

The new memories: false # show memories configuration option is correctly added and properly commented.

README.md (2)

250-250: New configuration option 'KIOSK_MEMORIES' added correctly

The addition of KIOSK_MEMORIES: false to the environment variables in the Docker Compose example is accurate and follows the existing format.


355-355: Configuration table updated with 'memories' option appropriately

The memories option has been correctly added to the configuration table, including its description and default value.

Comment on lines 125 to 127
assetsToCache := memories
assetsToCache[pickedMemoryIndex].Assets = append(assetsToCache[pickedMemoryIndex].Assets[:assetIndex], assetsToCache[pickedMemoryIndex].Assets[assetIndex+1:]...)

Copy link
Contributor

@coderabbitai coderabbitai bot Jan 14, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Avoid modifying shared data when updating cache

Assigning assetsToCache := memories copies the slice headers but shares the underlying data. Modifying assetsToCache[pickedMemoryIndex].Assets will also modify memories[pickedMemoryIndex].Assets, which might lead to unintended side effects. To prevent this, create deep copies of the memories before modifying them.

Consider using the following approach to deep copy the memories slice:

// Create a deep copy of memories
assetsToCache := make(MemoryLaneResponse, len(memories))
for i, memory := range memories {
	assetsToCache[i].YearsAgo = memory.YearsAgo
	assetsToCache[i].Title = memory.Title
	assetsToCache[i].Assets = make([]ImmichAsset, len(memory.Assets))
	copy(assetsToCache[i].Assets, memory.Assets)
}

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can I use the copy func?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@damongolding The built-in copy function performs a shallow copy, which means it would still share the underlying data for nested slices. However, you can use it in combination with new slice allocation to achieve a deep copy:

// Create a deep copy of memories
assetsToCache := make(MemoryLaneResponse, len(memories))
for i, memory := range memories {
    assetsToCache[i].YearsAgo = memory.YearsAgo
    assetsToCache[i].Title = memory.Title
    // Create a new slice and use copy
    assetsToCache[i].Assets = make([]ImmichAsset, len(memory.Assets))
    copy(assetsToCache[i].Assets, memory.Assets)
}

This ensures that modifying assetsToCache won't affect the original memories slice.

(_/)
(•.•)
(>🔍)>

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (4)
internal/immich/immich_memories.go (4)

30-35: Consider extracting API path components as constants

The API path components could be extracted as package-level constants to improve maintainability and reduce the risk of typos.

+const (
+    apiBasePath    = "api"
+    assetsPath     = "assets"
+    memoryLanePath = "memory-lane"
+)

     apiUrl := url.URL{
         Scheme:   u.Scheme,
         Host:     u.Host,
-        Path:     path.Join("api", "assets", "memory-lane"),
+        Path:     path.Join(apiBasePath, assetsPath, memoryLanePath),
         RawQuery: fmt.Sprintf("month=%d&day=%d", now.Month(), now.Day()),
     }

68-72: Consider logging errors before returning 0

Silently returning 0 on error might mask issues. Consider logging the error for debugging purposes.

     m, _, err := i.memories(requestID, deviceID, true)
     if err != nil {
+        log.Debug("Failed to fetch memory lane assets count", "error", err, "requestID", requestID)
         return 0
     }

123-152: Consider extracting cache update logic to a separate method

The caching logic is complex enough to warrant its own method. This would improve readability and maintainability.

Consider extracting the cache update logic to a new method like updateMemoryLaneCache(memories MemoryLaneResponse, pickedMemoryIndex, assetIndex int, apiCacheKey string) error.


148-150: Improve error logging for cache update failure

The debug log for cache update failure should include the error details.

     err = cache.Replace(apiCacheKey, jsonBytes)
     if err != nil {
-        log.Debug("Failed to update device cache for memories", "deviceID", deviceID)
+        log.Debug("Failed to update device cache for memories", "error", err, "deviceID", deviceID)
     }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between db11e04 and e6d56b2.

📒 Files selected for processing (1)
  • internal/immich/immich_memories.go (1 hunks)
🔇 Additional comments (2)
internal/immich/immich_memories.go (2)

23-26: Replace log.Fatal with proper error handling

Using log.Fatal will terminate the entire application upon encountering an error, which isn't appropriate for library code. The caller should handle the error gracefully.

Apply this diff:

     u, err := url.Parse(requestConfig.ImmichUrl)
     if err != nil {
-        log.Fatal(err)
+        return memoryLane, "", fmt.Errorf("failed to parse Immich URL: %w", err)
     }

59-65: Implementation looks good!

The function correctly calculates the total number of assets across all memories.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (1)
internal/immich/immich_memories.go (1)

24-26: ⚠️ Potential issue

Replace log.Fatal with proper error handling

Using log.Fatal will terminate the entire application upon encountering an error, which isn't appropriate for library code. Return the error to allow the caller to handle it gracefully.

Apply this diff:

    if err != nil {
-        log.Fatal(err)
+        return memoryLane, "", fmt.Errorf("failed to parse Immich URL: %w", err)
    }
🧹 Nitpick comments (3)
internal/immich/immich_memories.go (3)

68-75: Consider logging errors before returning 0

Silent error handling might mask issues from users. Consider logging the error with appropriate context before returning 0.

    m, _, err := i.memories(requestID, deviceID, true)
    if err != nil {
+        log.Debug("Failed to fetch memory lane assets count", 
+            "error", err,
+            "requestID", requestID,
+            "deviceID", deviceID)
        return 0
    }

148-150: Improve error logging for cache updates

The debug message could be more descriptive and include the actual error.

    err = cache.Replace(apiCacheKey, jsonBytes)
    if err != nil {
-        log.Debug("Failed to update device cache for memories", "deviceID", deviceID)
+        log.Debug("Failed to update device cache for memories",
+            "error", err,
+            "deviceID", deviceID,
+            "apiCacheKey", apiCacheKey)
    }

154-156: Consider using a constructor or setter method instead of direct assignment

Direct modification of the receiver state can be error-prone and harder to maintain. Consider using a dedicated method for updating the asset state.

-    *i = asset
-    i.KioskSourceName = memories[pickedMemoryIndex].Title
+    i.updateFromMemoryAsset(asset, memories[pickedMemoryIndex].Title)

// Add this method:
func (i *ImmichAsset) updateFromMemoryAsset(asset ImmichAsset, title string) {
    *i = asset
    i.KioskSourceName = title
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e6d56b2 and 7b7683b.

📒 Files selected for processing (1)
  • internal/immich/immich_memories.go (1 hunks)
🔇 Additional comments (1)
internal/immich/immich_memories.go (1)

59-65: LGTM! Clean and efficient implementation

The function is well-focused and correctly implements the asset counting logic.

@damongolding damongolding changed the title Feature/memories add memories asset bucket Jan 14, 2025
@damongolding damongolding merged commit f6caea6 into task/release Jan 14, 2025
3 checks passed
@damongolding damongolding deleted the feature/memories branch January 14, 2025 13:30
This was referenced Jan 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant