From 16b573bf1ed7f98d233a64cd647626be4df69af7 Mon Sep 17 00:00:00 2001 From: BoHung Chiu Date: Mon, 10 Apr 2023 11:27:20 +0800 Subject: [PATCH] Store youtube thumb to local. --- app/models/video_image.rb | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/app/models/video_image.rb b/app/models/video_image.rb index c5daad7..c117421 100644 --- a/app/models/video_image.rb +++ b/app/models/video_image.rb @@ -1,5 +1,5 @@ require 'uri' - +require 'fileutils' class VideoImage include Mongoid::Document include Mongoid::Timestamps @@ -71,12 +71,18 @@ class VideoImage end if self.is_youtube begin - temp_file = Tempfile.new('0.jpg', encoding: 'ascii-8bit') - snapshot_content = Net::HTTP.get_response(URI.parse("http:"+self.get_snapshot_url)).body rescue nil - temp_file.write(snapshot_content) - temp_file.close - image = MiniMagick::Image.open(temp_file.path) - self.scale = (1.0 * image[:height] / image[:width] * 100).round(2) + youtube_img_url = "http:"+self.youtube_thumb + snapshot_content = Net::HTTP.get_response(URI.parse(youtube_img_url)).body rescue nil + if snapshot_content + self[:video_snapshot] = '0.jpg' + snapshot_file_path = self.video_snapshot.file.path + FileUtils.mkdir_p(File.dirname(snapshot_file_path)) + File.open(snapshot_file_path, 'wb'){|f| f.write(snapshot_content)} + image = MiniMagick::Image.open(snapshot_file_path) + self.scale = (1.0 * image[:height] / image[:width] * 100).round(2) + else + puts "cannot read #{youtube_img_url}" + end rescue => e puts e.to_s self.scale = nil @@ -231,7 +237,8 @@ class VideoImage end def get_snapshot_url - (self.is_youtube ? self.youtube_thumb : (self.video_snapshot.url)) + self.video_snapshot.url rescue "" + # (self.is_youtube ? self.youtube_thumb : (self.video_snapshot.url)) end protected