Store youtube thumb to local.

This commit is contained in:
BoHung Chiu 2023-04-10 11:27:20 +08:00
parent 004a8c9eef
commit 16b573bf1e
1 changed files with 15 additions and 8 deletions

View File

@ -1,5 +1,5 @@
require 'uri' require 'uri'
require 'fileutils'
class VideoImage class VideoImage
include Mongoid::Document include Mongoid::Document
include Mongoid::Timestamps include Mongoid::Timestamps
@ -71,12 +71,18 @@ class VideoImage
end end
if self.is_youtube if self.is_youtube
begin begin
temp_file = Tempfile.new('0.jpg', encoding: 'ascii-8bit') youtube_img_url = "http:"+self.youtube_thumb
snapshot_content = Net::HTTP.get_response(URI.parse("http:"+self.get_snapshot_url)).body rescue nil snapshot_content = Net::HTTP.get_response(URI.parse(youtube_img_url)).body rescue nil
temp_file.write(snapshot_content) if snapshot_content
temp_file.close self[:video_snapshot] = '0.jpg'
image = MiniMagick::Image.open(temp_file.path) 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) self.scale = (1.0 * image[:height] / image[:width] * 100).round(2)
else
puts "cannot read #{youtube_img_url}"
end
rescue => e rescue => e
puts e.to_s puts e.to_s
self.scale = nil self.scale = nil
@ -231,7 +237,8 @@ class VideoImage
end end
def get_snapshot_url 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 end
protected protected