How can I handle youtube's thumbnail in rails? - ruby-on-rails

If user types youtube url in body and save record,
I'd like to show its thumbnail in view.
Is there any good techniques? or good gem for that?
sample typed in url:
http://www.youtube.com/watch?v=qrO4YZeyl0I

Are you parsing the video ID code from the URL? I.e. in your example it'd be qrO4YZeyl0I.
Once you have this you can do anything you want with it. There are four thumbnails generated for each video.
http://img.youtube.com/vi/qrO4YZeyl0I/0.jpg
http://img.youtube.com/vi/qrO4YZeyl0I/1.jpg
http://img.youtube.com/vi/qrO4YZeyl0I/2.jpg
http://img.youtube.com/vi/qrO4YZeyl0I/3.jpg
To simply select the default thumbnail for the video use:
http://img.youtube.com/vi/qrO4YZeyl0I/default.jpg
See this answer for more detail - How do I get a YouTube video thumbnail from the YouTube API?

I needed youtube thumbnails recently, so just an update. Currently urls look like:
http://i1.ytimg.com/vi/video_id/default.jpg
http://i1.ytimg.com/vi/video_id/mqdefault.jpg
http://i1.ytimg.com/vi/video_id/hqdefault.jpg
http://i1.ytimg.com/vi/video_id/sddefault.jpg
http://i1.ytimg.com/vi/video_id/1.jpg
http://i1.ytimg.com/vi/video_id/2.jpg
http://i1.ytimg.com/vi/video_id/3.jpg

You can parse the url, and get the thumbnail from the youtube before saving the model:
Gemfile:
gem 'youtube_it'
Model:
before_save :get_youtube_thumbnail
def get_youtube_thumbnail
url = extract_url_from_body
unless url.blank?
client = YouTubeIt::Client.new
response = client.video_by(url)
self.thumbnail = response.thumbnails.first.url
end
end
def extract_url_from_body
URI.extract(body).first
end
View:
<%= image_tag model.thumbnail, alt: model.title %>

Related

How to add a picture to a model (User) in Rails using ActiveStorage and the Cloudinary Upload Widget?

world!
After implementing Cloudinary's Active Storage Integration, it's easy to make it work in a form.
We just need to add to our simple_form_for a
<%= f.input :photo, as: :file %>
BUT, if we want to use the Cloudinary Upload Widget, there's no straightforward way of adding this file to the form.
What I have tried is:
1- let the widget upload the picture;
2- update the value of a hidden input with the url of the uploaded picture;
3- in the controller, when creating the model, download the picture and attach it to the model:
require 'open-uri'
file = URI.open(photo_url)
#user.photo.attach(io: file, filename: 'profile_photo.jpg')
# [...]
private
def photo_url
params.require(:user).permit(:photo_url)[:photo_url]
end
It works, BUT it uploads twice the same picture and - IMHO - is extremely inefficient.
Any ideas?
Thank you!
Good Luck, Have Fun!

How to get videos from rss feed entries

I am trying to get videos(urls) from feed entry url.
I am using Feedjira and MetaInspector in my application to fetch and store articles along with images. Now I want to store videos of articles if any. Can anyone please tell me what could be the best possible ways to store videos from articles
Thank you.
I do this in my project to save all the url found from rss feeds
Source.all.each do |source|
feed = Feedjira::Feed.fetch_and_parse(source.url)
feed.entries.each do |entry|
unless Link.exists? url: entry.url
Link.create!(title: entry.title,
url: entry.url)
end
end
end
in my snippet, I only save the url and title, for videos you just need to add entry.video,
you can see all the entry tag from feed.entries object or from the rss given.
and If you want to add another attributes, ex: media:thumbnail you could add this code before calling fetch_and_parse but you need to call it once not everytime you call fetch_and_parse to avoid memory leak
Feedjira::Feed.add_common_feed_entry_element("media:thumbnail", :value => :url, :as => :pic)
then you could do entry.pic to get the thumbnail url

Using Panda (pandastream) Video to show all videos in Index Action

I'm using PandaVideo (http://www.pandastream.com/docs/integrate_with_rails) to upload videos in my Rails app. I'm having trouble taking the code from the docs at Panda and Heroku to relate it to the index action to show ALL of the videos, both on the Video's controller index action and on the User's profile to show each user's videos.
Here is the code that they give to find and show the video on the Video's SHOW action:
#video = Video.find(params[:id])
#original_video = #video.panda_video
#h264_encoding = #original_video.encodings["h264"]
then on the show view, I reference the video based on the last variable #h264_encoding
This works nicely. Now, I need to somehow take this code and use it to show all videos on a single page. For this example, let's show all of a particular user's videos on their page.
def show
#user = User.find_by(username: params[:username])
# not sure what goes here to find that user's videos (from Panda).
# If i were just using paperclip for instance, I could easily write:
#videos = #user.videos # but I need to use the Panda (the #h264_encoding variable) to find the video.
end
maybe this is useful...here is part of the video model
def panda_video
#panda_video ||= Panda::Video.find(panda_video_id)
end
I hope I've provided enough code. If not please let me know and I'll add more. Again, I'm trying to show all of a particular user's videos from PandaStream.
Not sure if I'm missing something, but why wouldn't it be as simple as this:
def index
#videos ||= Video.all
end
As far as your show, I see nothing wrong with this:
def show
#user = User.find_by(username: params[:username])
#videos = #user.videos
end
Then in your view something like the following:
<%= #videos.each do |video| %>
<% h264_encoding = video.panda_video.encodings["h264"] %>
<video id="movie" width="<%= h264_encoding.width %>" height="<%= h264_encoding.height %>" preload="none"
poster="<%= h264_encoding.screenshots.first %>" controls>
<source src="<%= h264_encoding.url %>" type="video/mp4">
</video>
<% end %>
You are simply referencing Panda's API to retrieve the information relating to an upload, however you handle all the relationships and the User and Video models.
Let me know if I'm missing something, as it seems you are on the right track.

How to upload an image to S3 using paperclip gem

For the life of my I can't understand how the basic paperclip example works. There's only one line included in the controller, and that's
#user = User.create( params[:user] )
I simply don't understand how that's all that is needed to upload an image to s3. I've changed the example quite a bit because i wanted to use jquery file uploader rather than the default rails form helper, so I'm at the point where an image is being POSTed to my controller, but I can't figure out how I'm supposed to take the image from the params and assign it as an attachment. Here's what I'm seeing the logs:
Parameters: {"files"=>[#<ActionDispatch::Http::UploadedFile:0x132263b98 #tempfile=#<File:/var/folders/5d/6r3qnvmx0754lr5t13_y1vd80000gn/T/RackMultipart20120329-71039-1b1ewde-0>, #headers="Content-Disposition: form-data; name=\"files[]\"; filename=\"background.png\"\r\nContent-Type: image/png\r\n", #content_type="image/png", #original_filename="background.png">], "id"=>"385"}
My JS is very simple:
` $('#fileupload').fileupload({
dataType: 'json',
url: '/my_url',
done: function (e, data) {
console.log('done');
}
});`
What would be helpful for me to know is how I can strip the file data from the POSTed parameters given above and pass it to paperclip. I'm sure that I'll have to assign the attachment attribute a value of File.open(...), but I dont know what source of my file is.
I've spent a ridiculous amount of time trying to figure this out and I can't seem to get it. I've tried uploading directly to s3, but the chain of events was terribly confusing, so I want to get this simple pass-through example completed first. Thanks so much for any help you cna give!
You need a few more pieces and it will help if you can show the exact code you're using.
Paperclip can post to S3 by using:
http://rubydoc.info/gems/paperclip/Paperclip/Storage/S3
When your controller creates a User model, it is sending along all the params. This is called "mass assignment" (be sure to read about attr_accessible).
When your model receives the params, it uses the Paperclip AWS processor, which uploads it.
You need the AWS gem, a valid bucket on S3, and a config file.
Try this blog post and let us know if it helps you:
http://blog.trydionel.com/2009/11/08/using-paperclip-with-amazon-s3/
UPDATE 2013-04-03: Pleases see Chloe's comment below-- you may need an additional parameter, and the blog post may be outdated.
If you want to do it manually, approach it like this:
# In order to get contents of the POST request with the photo,
# you need to read contents of request
upload = params[:file].is_a(String)
file_name = upload ? params[:file] : params[:file].original_filename
extension = file_name.split('.').last
# We have to create a temp file which is going to be used by Paperclip for
# its upload
tmp_file = "#{Rails.root}/tmp/file.#{extension}"
file_id = 0
# Check if file with the name exists and generate unique path
while File.exists?(tmp_file) do
tmp_file_path = "#{Rails.root}/tmp/file#{file_id}.#{extension}"
id += 1
end
# Let's write the file from post request to unique location
File.open(tmp_file_path, 'wb') do |f|
if upload
f.write request.body.read
else
f.write params[:file].read
end
end
# Now that file is saved in temp location, we can use Paperclip to mimic one file
# upload
#photo = Photo.new :photo => File.open(tmp_file_path)
# We'll return javascript to say that the file is uploaded and put its thumbnail in
# HTML or whatever else you wanted to do with it
respond_to do |format|
if #photo.save
render :text => "Success"
else
render :text => #photo.errors
end
end
You can rewrite your create or whatever you use as the url to which you are POSTing the form.
This bit:
"files"=>[#<ActionDispatch::Http::UploadedFile:0x132263b98 #tempfile=# <File:/var/folders/5d/6r3qnvmx0754lr5t13_y1vd80000gn/T/RackMultipart20120329-71039-1b1ewde-0>
is the part (I think) that holds the file contents that are posted in the form.
In Rails, the User model will have a helper: has_attached_file
Passing the [:params] to the User.create method allows that helper to pick up the file contents, do any processing on them (eg resizing etc based on attributes supplied to the helper) and then push the image(s) to your storage (eg S3 or whatever - S3 credentials are passed to the helper).
Hopefully that explains the 'how does it do it?' question
re the jQuery bit.. not sure what the code should be there, but why not use the Rails form with :remote => true and handle the response in jquery?

Need help integrating youtube_it into my rails app

I am pretty new to rails so this may be an easy question, but I was looking to create a Rails app that would use youtube in it. I have found that youtube_it seems to be the gem of choice for a task like this but I am having trouble using it. Basically, I want to use the gem so that I can get videos from specific users, i.e. Stanford University and create a list of those videos with links to another page that has the video information and player. To test this out I tried the follow code:
application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery
helper_method :yt_client
private
def yt_client
#yt_client ||= YouTubeIt::Client.new(:dev_key => dev_key)
end
end
home_controller.rb
class HomeController < ApplicationController
def index
#playlists = yt_client.playlists('stanforduniversity')
end
end
index.html.erb
<h3>Home</h3>
<% #playlists.each do |playlist| %>
<p>Playlist: <%= playlist %></p>
<% end %>
The problem with this is all I get for output on my home page is a list of something like this: #
My questions then are: is there a way to change this output into an actual title? Am I doing something wrong/forgetting a step? Or should I just use python code to use the Google API and put all the videos into my database(I already have some code for this) and just access it using my rails app?
Hope this is clear enough.
it looks like what you want to print out is the name of the playlist - but that is an attribute of the playlist object, so you'll need something like:
<% #playlists.each do |playlist| %>
<p>Playlist: <%= playlist.title %></p>
<% end %>
otherwise ruby is trying to "print" the playlist object - which just doesn't work the way you expect.
Note: I've not used this gem either, I'm gathering this info from the gem docs here: https://github.com/kylejginavan/youtube_it
https://github.com/kylejginavan/youtube_it or youtube_it is the new version of youtube_g. This was forked and enhanced. If you need any enhancements please reach out to me.
you have a complete demo that I made here
http://youtube-it.heroku.com/
included source!

Resources