How do I mask Facebook graph api URLs for pictures? - ruby-on-rails

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..

Related

Images/Videos CDN URL - Detect file type/extension

I'm trying to implement Story Mention rendering according to IG messenger graph API.
IG webhooks sends the payload URL of the media as CDN URLs that are extensionless,
which means I can't detect the file type(could be any kind of image or a video file).
The purpose is to render the URL to an HTML element and to prevent saving some file extensions.
Did anybody find out how to get this information?
An example for IG CDN URL
https://lookaside.fbsbx.com/ig_messaging_cdn/?asset_id=17952754300482708&signature=AbxVoHUcW3qKGZvE0FwrbpSEKBqkYGH9wFDUY9xnywlxxek8lWtrTwE173Sxhta9jbp0bgDiL17IpyiI82vqHGNPUD1wdMUZphwQOggW-_877cCI1BxaY_aDUZ8hj5OwmHK9E8OnSybqtMVmGXCX_hBF399t1Hb44zspeL3d9NWb9rib
Python:
import requests
res = requests.head(url)
print res.headers
I was able to retrieve the content type by making a request with node-fetch.
const fetch = require('node-fetch');
const response = await fetch(mediaUrl, { method: 'HEAD' });
const contentType = response.headers.get('Content-Type');

Crystal-lang: How to Find End URL After a Redirect?

I'm just dipping a toe in the water with Crystal at the moment and, as an exercise, trying to port one of my Python scripts across.
The script in question downloads the 'latest' PDF from a URL which takes the form: "http://somesite.com/download/latest/". When visited that URL automatically redirects to the page for the latest download eg. "http://somesite.com/download/4563/"
I'm having difficulty working out how to implement this in Crystal so that I can grab the actual URL that the redirect ends up on.
In Python I do:
currenturl = urllib.request.urlopen(latesturl)
#above will redirect to URL of format http://somesite.com/download/XXXXX/
#where XXXXX is the current d/load
endurl = currenturl.geturl()
...which gives me the end URL in the "endurl" variable.
But, reading the docs for Crystal's "http/client" I can't see any way to return the actual URL that a redirect ends up on. Is it possible?
Crystal's HTTP::Client currently can't automatically follow redirects.
Please note that you're reading an outdated version of the API docs, the current is at https://crystal-lang.org/api/latest/HTTP/Client.html (I don't think there have been relevant changes between 0.24.1 and 0.26.1 though).
But you can easily access the redirect URL from reading the Location header of an HTTP response:
response = HTTP::Client.get latesturl
endurl = response.headers["Location"]

Redirect and then render

Okay, so real quick, I am using a file upload plugin http://plugins.krajee.com/file-input to upload my images. The plugin expects some sort of response from the server, and i want to send back an empty json object.
But when the images are uploaded, I also need to redirect immediately to another place so people can sort of make changes to the order.
Rails says I can't use render and redirect, but says i can redirect and return.
How do i redirect and return the empty json object??
def create
if !params[:images].nil?
package = Package.first
#photos = Array.new
#order = current_user.orders.new
#order.save
#order.order_items.each{|d| d.delete} #Stupid hack to prevent creation of fake order items. Don't know what is causing this yet
params["images"].each do |i|
photo = current_user.photos.create
photo.write(i.original_filename, i.read)
photo.save
#order.order_items.create(photo_id: photo.id, size_id: package.size_id, material_id: package.material_id)
end
redirect_to edit_order_path(#order) and return
else
flash[:danger] = "Please select at least one photo to upload"
redirect_to upload_photos_path
end
end
If the upload plugin you're using is expecting a JSON response and you would like to redirect after a successful upload, then you'll need to do it client side.
If you're not using Rails 4 or Turbolinks, you can simply redirect via window.location.replace. From your Rails code it looks like you're batch uploading in which case you'll want to assign a callback to the filebatchuploadsuccess event as per the docs
Example:
$('#fileinputid').on('filebatchuploadsuccess', function(event, data, previewId, index) {
// files have been successfully uploaded, redirect
window.location.replace( '/your_path_here' );
});
If you are using Turbolinks, the above code will be exactly the same except that instead of window.location.replace, you can use Turbolinks.visit
Example:
$('#fileinputid').on('filebatchuploadsuccess', function(event, data, previewId, index) {
// files have been successfully uploaded, redirect
Turbolinks.visit( '/your_path_here' );
});

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

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

How do you directly access the Omniauth facebook image url?

Using Omniauth version 1.0.2, currently when I call env["omniauth.auth"]["info"]["image"] to get the image for the current user I get a URL:
http://graph.facebook.com/100002739564577/picture?type=square
This redirects to the actual jpeg url which is what I want:
http://profile.ak.fbcdn.net/hprofile-ak-ash2/532749_100003719364175_332972681_a.jpg
Is it possible to get the jpeg url directly in rails?
Thanks
You don't necessarily have to if you want to display the image.
This works:
<img src="http://graph.facebook.com/100002739564577/picture?type=square" />
If you must however, try this:
url = URI.parse('http://graph.facebook.com/100002739564577/picture?type=square')
res = Net::HTTP.get_response(url)
res['location'] #returns the image URL

Resources