how to show thumbnails for vimeo and youtube embedded links in ruby on rails? - youtube

I have embedded the youtube and vimeo links in my site and trying to show the thumbnail of the video as a link to play while on click.
i tried the gem "has_vimeo_video" but it only accepts the vimeo videos.So i want to show the thumbnails of both the videos i.e youtube and vimeo.
Please need solution.
Thanks

the video_info gem is great for fetching thumbnails:
https://github.com/thibaudgg/video_info

I found out yesterday that there was carrierwave-video-thumbnailer which is pretty cool. It basically does what you want
A thumbnailer plugin for Carrierwave. It mixes into your uploader setup and makes easy thumbnailing of your uploaded videos. This software is quite an alpha right now so any kind of OpenSource collaboration is welcome.
But you will need to of course include carrierwave into your application. Hopefully this helps
Carreierwave is an uploader that enables users to upload content in their app, which I think
Update
Alternatively you can use embedly which allows you to add embedded media into your application. The API provides a lot response options as can be seen here. In doing so you could do something like:
$.embedly('http://www.youtube.com/watch?v=_FE194VN6c4',
{maxWidth: 600,
elems: $('#element'),
success: function(oembed, dict){
alert(oembed.title);
});
The elems property is where you want the video to be embedded, so that when the link is pasted in it should embed the video. You need to pass the video url and get it using the jQuery selector from wherever you put your url in your html.
Your other alternative is to have a look at the following auto_html gem

Add a new file 'thumbnail_helper.rb' in '/app/helper'. Copy and paste the following code in that file:
module ThumbnailHelper
# Regex to find YouTube's and Vimeo's video ID
YOUTUBE_REGEX = %r(^(http[s]*:\/\/)?(www.)?(youtube.com|youtu.be)\/(watch\?v=){0,1}([a-zA-Z0-9_-]{11}))
VIMEO_REGEX = %r(^https?:\/\/(?:.*?)\.?(vimeo)\.com\/(\d+).*$)
# Finds YouTube's video ID from given URL or [nil] if URL is invalid
# The video ID matches the RegEx \[a-zA-Z0-9_-]{11}\
def find_youtube_id url
url = sanitize url
matches = YOUTUBE_REGEX.match url.to_str
if matches
matches[6] || matches[5]
end
end
# Finds youtube video thumbnail
def get_youtube_thumbnail url
youtube_id = find_youtube_id url
result = "http://img.youtube.com/vi/#{youtube_id}/0.jpg"
end
# Finds Vimeo's video ID from given URL or [nil] if URL is invalid
def find_vimeo_id url
url = sanitize url
matches = VIMEO_REGEX.match url.to_str
matches[2] if matches
end
# Finds vimeo video thumbnail
def get_vimeo_thumbnail url
vimeo_id = find_vimeo_id url
result = URI.open("http://vimeo.com/api/v2/video/#{vimeo_id}.json").read
begin
JSON.parse(result).first['thumbnail_large']
rescue StandardError
nil
end
end
# Main function
# Return a video thumbnail
# If the url provided is not a valid YouTube or Vimeo url it returns [nil]
def get_video_thumbnail(url)
if find_vimeo_id(url)
get_vimeo_thumbnail(url)
elsif find_youtube_id(url)
get_youtube_thumbnail(url)
end
end
end
Now call the get_video_thumbnail('video_url') from your view. It will return you the thumbnail of the given video.

You don't need any gems for such a simple task
url = 'https://vimeo.com/126100721'
id = url.partition('vimeo.com/').last
result = URI.open("http://vimeo.com/api/v2/video/#{id}.json").read
begin
JSON.parse(result).first['thumbnail_large']
rescue StandardError
nil
end

Related

You tube Search API - Video Id Prefix with '-' sign?

Few video Ids are prefixed with '-' sign. When we search these Id's with prefix on Youtube, it says no records found. However, Youtube is able to play these videos.
Eg:
https://www.youtube.com/watch?v=-xYmfZ2Ic_M (Video will play)
https://www.youtube.com/results?search_query=-xYmfZ2Ic_M (No results
found).
I would like to know: what all characters could come as prefix so that I can allow or remove them before my Youtube API call? Or is there any standard way to handle this thing?
You refer to 'API call' using the URL is not making a API call, its calling the search URL. The URL unfortunatly does not work using a URL encoded parameter.
I suggest to implement this using YouTube API V3. In PHP this correctly retrives the video based on a ID even if it starts with hyphens. I have provided a PHP snippet below...
//In PHP
function videosListById($service, $part, $params) {
$params = array_filter($params);
$response = $service->videos->listVideos(
$part,
$params
);
print_r($response);
}
videosListById($service,
'snippet,contentDetails,statistics',
array('id' => '-xYmfZ2Ic_M'));
To see this in action you can visit the following URL;
https://developers.google.com/apis-explorer/#p/youtube/v3/youtube.videos.list?id=-xYmfZ2Ic_M&part=snippet%2CcontentDetails%2Cstatistics

Resolving two types of YouTube channel URLs in API v3

I'm taking a youtube url as user input.
The logic I have is as follows:
if(URL === link_to_video) then get video
else if( URL == link_to_channel) then get all_videos_of_channel.
I am doing this via JavaScript and using the YouTube API v3.
The problem is, it seems youtube has two types of URLs to youtube channels.
/channel/, eg:
www.youtube.com/channel/UCaHNFIob5Ixv74f5on3lvIw
/user/,
eg: www.youtube.com/user/CalvinHarrisVEVO
both the above links will take you to the same channel, but my current uploader code supports only /user/CalvinHarrisVEVO.
is there any way to make both the URLs behave similarly in terms of obtaining the channel videos?
One solution would be to parse the url and then apply this logic:
if there is `channel` in the url link
call the APIv3 with the **id** of the channel
Ressource : youtube.channels.list
else if there is 'user'
call the APIv3 with the **forUsername** of the channel
Ressource : youtube.channels.list
Check : https://developers.google.com/apis-explorer/#p/youtube/v3/youtube.channels.list

404 error when writing to a Shopify asset

I've been trying to upload an asset using the shopify_api gem. I made sure I have the appropriate OAuth2 scope (write_themes), and I have no problem reading and even destroying them. The problem is that I get a 404 error when attempting to create or update an asset.
Here's the request the gem is creating:
PUT: /admin/themes/3650318/assets.json [{"Content-Type"=>"application/json", "User-Agent"=>"ShopifyAPI/3.0.3 ActiveResource/4.0.0.beta1 Ruby/2.0.0", "X-Shopify-Access-Token"=>"ommitted"}] ({"key":"templates/index.liquid","attachment":"base64 attachment omitted"})
For reference, here is the code I've used to make the request (wrapped in a ShopifyAPI::Session, of course):
ShopifyAPI::Asset.create(key: 'snippets/test.liquid', attachment: some_base64_data, theme_id: 3650318)
Or:
asset = ShopifyAPI::Asset.new(key: 'snippets/test.liquid', attachment: baset64_data, theme_id: 3650318)
asset.save
Any ideas?
This works for me...
To upload to the published theme (no theme id is given)
a = ShopifyAPI::Asset.new
a.key = "assets/google.png"
a.src = "https://www.google.co.uk/images/srpr/logo11w.png"
a.save
or
ShopifyAPI::Asset.create(key: 'assets/google.png', src: "https://www.google.co.uk/images/srpr/logo11w.png")
To upload to a specific theme
a = ShopifyAPI::Asset.new
a.key = "assets/google.png"
a.src = "https://www.google.co.uk/images/srpr/logo11w.png"
a.prefix_options[:theme_id] = "6731537"
a.save
or
ShopifyAPI::Asset.create(key: 'assets/google.png', src: "https://www.google.co.uk/images/srpr/logo11w.png", theme_id: 6731537)
It seems quite late for the reply but i am answering this so that it will help other developers facing similar issue.
If you have setup shopify_app gem then you can access the asset API on rails by
#This will access the asset of live theme
#assets = ShopifyAPI::Asset.find(:all)
#or if you want to access the asset of particular theme.
#assets = ShopifyAPI::Asset.find(:all, params: {"theme_id": themeid})
You can find the detail explanation here

How do I mask Facebook graph api URLs for pictures?

I'm trying to display Facebook profile pictures on my site, but don't want to leak the facebook id's of the people in the source.
For example, this URL: http://graph.facebook.com/4/picture will redirect to: http://profile.ak.fbcdn.net/hprofile-ak-snc4/157340_4_3955636_q.jpg when you load it in a browser. I'd like to get the 2nd url (CDN url) and use it as my img src since it doesn't show the facebook id in the url.
I'm doing this in Ruby on Rails at the moment and am curious if there's a better way that what I have done below:
def picture_square(facebook_id, secure=false)
raw_url = "http://graph.facebook.com/" facebook_id + "/picture?type=square"
if secure
binary_img = ''
open(raw_url) do |f|
binary_img = f.read
end
encoded_img = Base64.encode64(binary_img)
return 'data:image/jpg;base64,' + encoded_img.to_s
else
return raw_url
end
end
You could call this with the following HTML (using the above example):
<img src="<%= picture_square(4, true) %>"
This definitely works and uses the inline image properties to actually render the image, but it's a bit slow if you have a bunch of images that you're trying to load.
Is there a way in Ruby that I can get the redirected URL and just return that instead of trying to get the actual raw binary data and encode it to base64?
Make a call to the graph API with this url:
http://graph.facebook.com/4/?fields=picture&type=large
This will return the image you are looking for inside the json response. The other option would be to make an http request to the first url you posted and then inspect the HTTP headers to read the location header..

Uploading a file to Facebook using Koala on Ruby on Rails

I followed the following blogpost to figure out how to create Facebook events remotely using my app. I've been having problems loading the images from my app, however, because I do not have images stored locally on my app, they are stored in AWS.
#graph = Koala::Facebook::GraphAPI.new(#token)
picture = Koala::UploadableIO.new(#event.photo.url(:small))
params = {
:picture => picture,
:name => 'Event name',
:description => 'Event descriptio
:start_time => datetime,
}
is the following code I am currently using to send pictures to Facebook when Facebook events are created on my app. The problem is, however, that Rails is throwing the error: No such file or directory - http://s3.amazonaws.com/ColumbiaEventsApp/photos/21/small.jpeg?1312521889.
Does anybody who's more experienced with Rails development know if there is a way for me to treat a URL like a path to a file? The UploadableIO class expects a path to a file, and I'm struggling to figure out if there's a way in Ruby to treat URL's like filepaths. The way that photos stored on the app can be loaded to Facebook is as follows:
picture = Koala::UploadableIO.new(File.open("PATH TO YOUR EVENT IMAGE"))
if that helps.
I appreciate any new insights into this issue.
Ok so I played around and figured out how to post pictures.
Basically what I did was use the 'open-uri' library to convert the image links into file objects, which can then be passed to UploadableIO and sent to Facebook. This is the code that worked:
require 'open-uri'
OpenURI::Buffer.send :remove_const, 'StringMax' if OpenURI::Buffer.const_defined?('StringMax')
OpenURI::Buffer.const_set 'StringMax', 0
picture = Koala::UploadableIO.new(open(#event.photo.url(:small)).path, 'image')
params = {
picture: picture,
name: #event.name,
description: #event.description,
location: #event.location,
start_time: datetime
}
#graph.put_object('me', 'events', params )
The OpenURI constant StringMax needed to be changed because the image files I was using were small enough that the files were being processed as Strings rather than File Objects.
Hope this helps anyone trying to fix this!
With Koala 1.2.1 it's a very elegant solution. Here is sample code for creating an album and uploading to it from a remote, AWS link (btw this took about 30 lines in PHP w/ the PHP SDK!
#foo = Foo.find(params[:foo_id])
albuminfo = #graph.put_object('me','albums', :name=>#foo.title)
album_id = albuminfo["id"]
#graph.put_picture(#foo.remote_image_path,{}, album_id)
Facebook recently released an update that lets you post pictures using publicly accessible URLs (http://developers.facebook.com/blog/post/526/). The Koala library you're using supports that (https://github.com/arsduo/koala/blob/master/lib/koala/graph_api.rb#L102), so you should be able to post the pictures you're hosting on S3 without having to use OpenURI::Buffer.
For Facebook Ad Images, you unfortunately currently cannot do it by URL, thus:
require 'open-uri'
img_data = open(my_post.image.url :medium).read
img = graph.put_connections('act_X', 'adimages', bytes: Base64.encode64(img_data))

Resources