Download and attach icons for web apps

This commit is contained in:
Râu Cao
2023-10-23 15:31:22 +02:00
parent e56c9bd0d5
commit d4f71e98ed
6 changed files with 84 additions and 32 deletions

View File

@@ -1,9 +1,20 @@
class AppCatalog::WebApp < ApplicationRecord
store :metadata, coder: JSON
has_one_attached :icon do |attachable|
attachable.variant :medium, resize_to_limit: [128,128]
attachable.variant :large, resize_to_limit: [256,256]
end
has_one_attached :apple_touch_icon
validates :url, presence: true, uniqueness: true
validates :url, format: { with: URI.regexp },
if: Proc.new { |a| a.url.present? }
# before_create :update_metadata
def update_metadata
AppCatalogManager::UpdateMetadata.call(self)
end
end

View File

@@ -1,26 +0,0 @@
require 'manifique'
module AppCatalogManager
class FetchMetadata < AppCatalogManagerService
def initialize(app)
@app = app
end
def call
agent = Manifique::Agent.new(url: @app.url)
metadata = agent.fetch_metadata
@app.name = metadata.name
[:name, :short_name, :description, :theme_color, :background_color,
:display, :start_url, :scope, :share_target].each do |prop|
@app.metadata[prop] = metadata.send(prop) if prop
end
rescue Manifique::Error => e
msg = "Fetching web app manifest failed for #{e.url}: #{e.type}"
Rails.logger.warn(msg)
Sentry.capture_message(msg) if Setting.sentry_enabled?
false
end
end
end

View File

@@ -0,0 +1,44 @@
require "manifique"
require "down"
module AppCatalogManager
class UpdateMetadata < AppCatalogManagerService
def initialize(app)
@app = app
end
def call
agent = Manifique::Agent.new(url: @app.url)
metadata = agent.fetch_metadata
@app.name = metadata.name
[:name, :short_name, :description, :theme_color, :background_color,
:display, :start_url, :scope, :share_target, :icons].each do |prop|
@app.metadata[prop] = metadata.send(prop) if prop
end
if icon = metadata.select_icon(sizes: "256x256")
attach_remote_image(:icon, icon)
end
if apple_touch_icon = metadata.select_icon(purpose: "apple-touch-icon")
attach_remote_image(:apple_touch_icon, apple_touch_icon)
end
byebug
rescue Manifique::Error => e
msg = "Fetching web app manifest failed for #{e.url}: #{e.type}"
Rails.logger.warn(msg)
Sentry.capture_message(msg) if Setting.sentry_enabled?
false
end
def attach_remote_image(attachment_name, icon)
download_url = "#{@app.url}/#{icon["src"].gsub(/^\//,'')}"
filename = "web_apps/#{@app.id}/icons/#{attachment_name}.png"
tempfile = Down.download(download_url)
@app.send(attachment_name).attach(io: tempfile, filename: filename)
end
end
end