Skip to content

Instantly share code, notes, and snippets.

@marcomontes
Last active August 29, 2015 14:22
Show Gist options
  • Save marcomontes/5dbaabed9ab644ccf150 to your computer and use it in GitHub Desktop.
Save marcomontes/5dbaabed9ab644ccf150 to your computer and use it in GitHub Desktop.
Funciones varias para extraer y validar info de youtube y crear thumbnails personalizados.
class YoutubeAdapter
def self.get_thumbnail(entry, size)
video_id = get_video_id entry.embed
case size
when 0 then "http://img.youtube.com/vi/#{video_id}/0.jpg"
when 1 then "http://img.youtube.com/vi/#{video_id}/1.jpg"
end
end
def self.get_video_id(embed_code)
urls = URI.extract embed_code
url_regex = Regexp.new("((https?|ftp|file):((//)|(\\\\))+[\w\d:\#@%/;$()~_?\+-=\\\\.&]*)")
if urls.blank?
return false
else
urls.each do |url|
unless (url =~ url_regex).nil?
url_data = URI.parse url
if url_data.host.present? && (url_data.host.include? "youtube.com")
return url_data.path.split('/')[2].split('&')[0]
break
else
return nil
break
end
end
end
end
end
def self.is_youtube_video?(code)
urls = URI.extract code
url_regex = Regexp.new("((https?|ftp|file):((//)|(\\\\))+[\w\d:\#@%/;$()~_?\+-=\\\\.&]*)")
if urls.blank?
return false
else
urls.each do |url|
unless (url =~ url_regex).nil?
url_data = URI.parse url
if url_data.host.present? && (url_data.host.include? "youtube.com")
return true
break
else
return false
break
end
end
end
end
end
def self.make_thumbnail(entry)
thumbnail_url = get_thumbnail(entry, 0)
#thumbnail_local_path = download_thumbnail(thumbnail_url)
thumbnail_file = add_play_button(thumbnail_url)
thumbnail_file
end
def self.download_thumbnail(url)
image_file = Tempfile.new("temp_image")
image_file.write(open(url).read)
image_file.close
image_file.path
end
def self.add_play_button(image_url)
image = Magick::ImageList.new(image_url)
play_image = Rails.root.join('public', 'images', 'icons', 'play-x100.png')
play_overlay = Magick::ImageList.new(play_image)
image.gravity = Magick::CenterGravity
video_image = image.composite_layers(play_overlay, Magick::OverCompositeOp)
video_image.format = "jpeg"
final_image = Tempfile.new("youthumb")
video_image.write final_image.path
image_file = File.open(final_image.path, 'rb')
image_file
# entry.update_attribute(:image, File.open(final_image.path, 'rb'))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment