From 84d5086cfaa1024b3e8ca1ba1cbe98941cc20e44 Mon Sep 17 00:00:00 2001 From: Dean Lofts Date: Sun, 11 Aug 2024 22:18:28 +1000 Subject: [PATCH 1/2] serve avatar locally --- app/models/user.rb | 31 ++++++++++++++++++++++--- app/views/links/user_links.html.erb | 7 +++++- lib/tasks/download_avatars.rake | 9 +++++++ public/avatars/avatar_1_1723378561.jpg | Bin 0 -> 22126 bytes 4 files changed, 43 insertions(+), 4 deletions(-) create mode 100644 lib/tasks/download_avatars.rake create mode 100644 public/avatars/avatar_1_1723378561.jpg diff --git a/app/models/user.rb b/app/models/user.rb index 9e5c3a8..585a608 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -9,11 +9,11 @@ class User < ApplicationRecord validates :full_name, presence: true before_validation :set_default_username, on: :create + after_save :generate_open_graph_image + after_save :download_and_store_avatar, if: :saved_change_to_avatar? serialize :tags, JSON - after_save :generate_open_graph_image - def parsed_tags if tags.is_a?(String) begin @@ -30,9 +30,34 @@ def generate_open_graph_image OpenGraphImageGenerator.new(self).generate end + def download_and_store_avatar + return unless avatar.present? && avatar.start_with?('http') + + require 'open-uri' + require 'fileutils' + + begin + avatar_dir = Rails.root.join('public', 'avatars') + FileUtils.mkdir_p(avatar_dir) unless File.directory?(avatar_dir) + + file = URI.open(avatar) + + filename = "avatar_#{id}_#{Time.now.to_i}#{File.extname(avatar)}" + filepath = File.join(avatar_dir, filename) + + File.open(filepath, 'wb') do |local_file| + local_file.write(file.read) + end + + update_column(:avatar, "/avatars/#{filename}") + rescue OpenURI::HTTPError, SocketError => e + Rails.logger.error "Failed to download avatar for user #{id}: #{e.message}" + end + end + private def set_default_username self.username ||= email.split('@').first end -end +end \ No newline at end of file diff --git a/app/views/links/user_links.html.erb b/app/views/links/user_links.html.erb index 0c7d868..3d26d92 100644 --- a/app/views/links/user_links.html.erb +++ b/app/views/links/user_links.html.erb @@ -3,7 +3,12 @@
- <%= @user.email %> + <% if @user.avatar.present? %> + <%= image_tag @user.avatar, alt: @user.email, class: "rounded-full border-4 border-white object-cover", style: "width: 8rem; height: auto;" %> + <% else %> + + <%= image_tag "default_avatar.png", alt: @user.email, class: "rounded-full border-4 border-white object-cover", style: "width: 8rem; height: auto;" %> + <% end %>