Implement thumbnail fetching for photoprism

This commit is contained in:
Eugene Burmakin 2024-12-03 14:44:24 +01:00
parent 8849a5e0a5
commit bf569da921
5 changed files with 80 additions and 11 deletions

View file

@ -20,16 +20,7 @@ class Api::V1::PhotosController < ApiController
def fetch_cached_thumbnail(source)
Rails.cache.fetch("photo_thumbnail_#{params[:id]}", expires_in: 1.day) do
source_url = current_api_user.settings["#{source}_url"]
source_api_key = current_api_user.settings["#{source}_api_key"]
HTTParty.get(
"#{source_url}/api/assets/#{params[:id]}/thumbnail?size=preview",
headers: {
'x-api-key' => source_api_key,
'accept' => 'application/octet-stream'
}
)
Photos::Thumbnail.new(current_api_user, source, params[:id]).call
end
end

View file

@ -26,7 +26,7 @@ class Api::PhotoSerializer
attr_reader :photo, :source
def id
photo['id'] || photo['ID']
photo['id'] || photo['Hash']
end
def latitude

View file

@ -0,0 +1,16 @@
# frozen_string_literal: true
class Photoprism::CachePreviewToken
attr_reader :user, :preview_token
TOKEN_CACHE_KEY = 'dawarich/photoprism_preview_token'
def initialize(user, preview_token)
@user = user
@preview_token = preview_token
end
def call
Rails.cache.write("#{TOKEN_CACHE_KEY}_#{user.id}", preview_token)
end
end

View file

@ -53,6 +53,8 @@ class Photoprism::RequestPhotos
Rails.logger.debug "Photoprism API request params: #{request_params(offset).inspect}"
end
cache_preview_token(response.headers)
JSON.parse(response.body)
end
@ -86,4 +88,10 @@ class Photoprism::RequestPhotos
taken_at.between?(start_date.to_datetime, end_date.to_datetime)
end
end
def cache_preview_token(headers)
preview_token = headers['X-Preview-Token']
Photoprism::CachePreviewToken.new(user, preview_token).call
end
end

View file

@ -0,0 +1,54 @@
# frozen_string_literal: true
class Photos::Thumbnail
def initialize(user, source, id)
@user = user
@source = source
@id = id
end
def call
fetch_thumbnail_from_source
end
private
attr_reader :user, :source, :id
def source_url
user.settings["#{source}_url"]
end
def source_api_key
user.settings["#{source}_api_key"]
end
def source_path
case source
when 'immich'
"/api/assets/#{id}/thumbnail?size=preview"
when 'photoprism'
preview_token = Rails.cache.read("#{Photoprism::CachePreviewToken::TOKEN_CACHE_KEY}_#{user.id}")
"/api/v1/t/#{id}/#{preview_token}/tile_500"
else
raise "Unsupported source: #{source}"
end
end
def headers
request_headers = {
'accept' => 'application/octet-stream'
}
request_headers['X-Api-Key'] = source_api_key if source == 'immich'
request_headers
end
def fetch_thumbnail_from_source
url = "#{source_url}#{source_path}"
a = HTTParty.get(url, headers: headers)
pp url
a
end
end