Pages

Sunday 27 April 2014

API for sending Video and Validate Format

Video duration validation using paperclip

  • Curl request for sending video
curl --request POST -F "post[file_attributes][media]=@/Users/tarun/Downloads/11.mp4" -F "post[caption]=api hit" -F  "type=Video" -F "pet_id=10" -F "auth_token=tcNkgmEipgezpFcf1fio" "localhost:3000/api/v1/posts.json"

video_path = params[:post][:file_attributes][:media].tempfile.path
video_name = params[:post][:file_attributes][:media].original_filename

Validation:-

def self.validate_video_format(name)
   video_format = File.extname(name)
   formats = [".mov", ".flv", ".MOV", ".mp4", ".MP4", ".3gp", ".webm", ".mkv", ".m4v"]
   if formats.include? video_format
     return true
   else
     return false
   end
 end

Monday 21 April 2014

Validate Video with his length using paperclip in rails


1. Download ffmpeg on mac.

2. Run ‘which ffmpeg’ on console. It will show the path if it is saved or not.

3. Now write  ‘ gem "paperclip-ffmpeg" ’ in Gemfile.
  and Write the following code in config/development.rb

Paperclip.options[:command_path] = "/usr/local/bin/"
  
4. add the following field in the view
<p>
   <%= f.file_field :vid %>
 </p>

4. Write code in model file

class Post < ActiveRecord::Base
   attr_accessible :content, :user_id, :vid
   has_attached_file :vid, :styles => {
   :medium => { :geometry => "640x480", :format => 'flv' },
   :thumb => { :geometry => "100x100#", :format => 'jpg', :time => 10 }
 }, :processors => [:ffmpeg]

validate :get_video_duration

 def get_video_duration
   vid = self.vid_meta[:length].split(/[:.]/)
   count = vid[0].to_i*3600+vid[1].to_i*60+vid[2].to_i
   if count > 8
     errors.add(:duration, "Length Is Greater For Video")
   end

 end
end

get_duration_videos code for not to upload more than 8 sec video.

5. Add the following columns in present table using given migration

class AddVidToPosts < ActiveRecord::Migration
 def change
   add_column :posts, :vid, :string
add_column :posts, :vid_file_name, :string
add_column :posts, :vid_meta, :text
add_column :posts, :vid_file_size, :string
  end
end

6. In the show form Write the following code

<p>
 <b>Content:</b>
  <%= video_tag @post.vid %>
</p>
<p>
  <%=image_tag @post.vid(:thumb).to_s %>
</p>
<a href="<%=@post.vid%>" > Download video </a>

Friday 18 April 2014

Resque Handler in ruby on rails

class ApplicationController < ActionController::Base

  protect_from_forgery with: :exception

  unless Rails.env == "development"
    rescue_from Exception, with: :server_error
    rescue_from ActiveRecord::RecordNotFound, with: :record_not_found
  end

  def server_error(exception)
    logger.info(exception)                        #add exception to production log
    render :file => "public/500-s.html", :status => 200
  end

  def record_not_found(exception)
    logger.info exception
    render :file => "public/404-s.html", :status => 200
  end

end

Monday 14 April 2014

Facebook javascript sdk for login popup


Facebook provides a large set of client-side functionalities that includes Like buttons, Social plugins etc. But what  I used is javascript SDK for purposes of authenticate user and  fetch information of the user.
 In ruby on rails it is not difficult to login with facebook using gem omniauth, but It redirects to next page or next tab. So, to show popup for facebook authentication, i am using javascript sdk provided by facebook.

Steps to Implement:-
  1. Write the following code in your app/views/layouts/application.html.erb where the the body tag starts.
<body>
     <div id="fb-root"></div>     // fb-root is facebook standard id. Please do not change it

      <script>
$(document).ready(function(){
       window.fbAsyncInit = function () {
           FB.init({ appId: 'appid', cookie: true, xfbml: true, oauth: true });

           if (typeof facebookInit == 'function') {
               facebookInit();
           }
       };

       (function(d){
           var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
           js = d.createElement('script'); js.id = id; js.async = true;
           js.src = "//connect.facebook.net/en_US/all.js";
           d.getElementsByTagName('head')[0].appendChild(js);
       }(document));
     });
      </script>
</body>

    • This given script will automatically include facebook javascript and css.
    • The appid is provided by the facebook.
    • Here if condition checks whether the javascript is loaded or not.
    • fb-root is id provided by facebook. Please do not change it.

  1. Now after that, We have to show the login popup on clicking any button. Write this code in html file under the body tag.
     
<button id="facebook-login" class="button submit-bttn">Facebook Popup</button>
<div id=”status-login”></div>
<div class=”error-vote-poup”></div>
// Using jquery for onclick event
$(‘#facebook-login’).on(‘click’, function(){
loginPopup();
});
function loginPopup() {
FB.login(function(response) {
   if (response.authResponse)
   {
getUserInfo();
   } else{
console.log('User cancelled login or did not fully authorize.');
   }
},{scope: 'email,user_birthday'});       // birthday is important
}
function getUserInfo(){
FB.api('/me', function(response) {
var str="<b>Name</b> : "+response.name+"<br>";
str +="<b>Email:</b> "+response.email+"<br>";
console.log(str);

// this is other info you can get from facebook.
// email: response.email, name: response.name, bio: response.bio,  
// location: response.location.name, uid: response.id, gender:
// response.gender, birthdate: response.birthday
// this ajax is optional (only if you want to hit server with facebook  
// info.)
$.ajax({
type: "PUT",
url: "sessions/update_facebook_info",
data: { email: response.email, name: response.name, bio: response.bio, location: response.location.name, uid: response.id, gender: response.gender, birthdate: response.birthday },
statusCode: {
404: function() {
alert( "page not found" );
},
200: function() {
$('#status-login').html('Authenticated')
},
201: function( msg ) {
$('.error-vote-poup').html(msg.responseText)
},
400: function( msg ) {
$('.error-vote-poup').html(msg.responseText)
}
}
});
});
}

  • In loginPopup function we have to define the scope for the facebook. Reason behind that facebook does not provide us email and birth date untill we define in the scope.
  • In getUserInfo function we will get the response from the facebook in which we we have all the information about the authenticated user.
  • In this function i also define the ajax call with status codes and if we want to hit the server with this information.
  • Now we have all the information regarding the user and we can do the needful.

Thursday 10 April 2014

Capistrano Details

Capistrano is a Ruby gem or we can say a set of Ruby programs that gives you a set
of advanced tools to deploy web applications to web servers. In other
words, Capistrano allows you to copy code from your source control
repository (SVN/Git) to your server via SSH, and perform pre and
post-deploy functions like restarting a web server, renaming files,
running database migrations and so on. With Capistrano you can also
deploy to many machines at once.
  • Capistrano
    offers many advanced options but for the purpose of this introductory
    blog, we will focus only on the essential things that need to be taken
    care of while deploying a simple app. We will setup a simple
    recipe(fancy name for capistrano scripts) for deploying a Rails
    application to a single server from either SVN or Git repositories. We
    will cover a common workflow that allows you to deploy multiple
    environments: in this case, staging and production.
  • This tutorial has three steps for deployment
  • Installing Capistrano
  • Configure
  • Deployment
So Let’s start with the steps:-
1. Installing Capistrano:- In order to install Capistrano you will need Ruby and RubyGems
installed on your computer. Then, just open the Gemfile of your Rails
application and add the following line to include the capistrano gem:-

gem 'capistrano'
After configuring the gemfile, run ‘bundle install‘ command.
2. Configure:
2.1. Capification
:- Capification refers to generating the necessary files in your Rails
application needed for the deployment and this can be done by firing the
following command in your rails app directory:-
ubuntu:~/app_directory$ capify
This command will create two files:
  • Capfile:
    this is the “main” file that Capistrano needs. Capistrano looks for and
    loads “Capfile” by default. All it does is load “config/deploy.rb”.
  • config/deploy.rb:
    this is the file that contains your Rails application’s deployment
    configuration. Rails prefers that all configuration go under the config
    directory, and so Capistrano tries to abide by that as much as it can by
    just pointing the Capfile to config/deploy.rb.
2.2. Configuration
:- In general, you’ll leave the Capfile alone and do all your tweaking
in config/deploy.rb. So for now just leave the Capfile and start working
with the deploy.rb file. The following are the essential elements which
are needed to be include for basic deployment:-
  • set :application, “App_Name” /* The name of your application to be deployed*/
  • set
    :repository, “repository_address” /*address of the repository where the
    application resides. This repository must be accessible to the
    server(where we are deploying) as well as the local machine*/
  • set
    :scm, :git /*we need to tell capistrano about which SCM we are using
    e.g. GIT, SVN or any other SCM. In above example we are using GIT. if we
    don’t write the SCM then by default it takes it as SVN. if you use
    username and password to access your repository then you need to mention
    that also by using the following two attributes also*/
  • set :scm_username, ‘your_scm_username’
  • set :scm_password, ‘your_scm_password’
  • set :deploy_to, “/data/#{application}” /*the address on the server where you want to deploy your application*/
  • set :user, “username” /*username for ssh login into remote server where you want to deploy your application*/
  • set
    :password, “password” /* for ssh login into remote server where you
    want to deploy your application. If you are not having the password you
    can you your public key to login into the server by giving the following
    option*/
  • ssh_options[:keys] = ["Your ssh key full path and name"]
  • server
    “abcd.com”, :app, :web, :db, :primary => true /*name or IP address
    of server where we want to deploy our application. But if we want to
    deploy the application on mltiple servers, then we need to add the
    following */
  • role :app, “tutorial.com”
  • role :web, “tutorial.com”
  • role :db, “tutorial.com”, :primary => true
Those
three roles (app, web, and db) are the three that Capistrano needs for
Rails deployment. You can always add your own roles, too, for tasks of
your own, but make sure you declare at least one server in each of app,
web, and db when you’re deploying Rails applications.
  • web:
    this is where your web server software runs. Requests from the web go
    straight here. For sites with lots of traffic, you might have two or
    three (or more!) web servers running behind a load balancer.
  • app:
    this is where your application layer runs. You might need only a single
    web server, and have it send requests to any of four or five different
    app servers, via a load balancer.
  • db:
    this is where migrations are run. Some prefer not to actually run code
    on the server where the database lives, so you can just set this to one
    of the app servers if you prefer. Capistrano will deploy your
    application to servers in this role. The “:primary => true” bit just
    says that this is our “primary” database server—you can have as many as
    you want (for database slaves and so forth), but Capistrano will only
    run migrations on the one you designate as “primary”.
The addresses you place in each role are the addresses that Capistrano will SSH to, in order to execute the commands you give.
By
using these parameters one can easily deploy a simple app to server.
And there are some parameter which gives you additional options like:
  • use_sudo:
    Defines for the default Rails deployment recipes whether we want to use
    sudo or not. Sudo is a unix tool for executing commands as the
    root_user . To use it, your user must have passwordless sudo access
    enabled. If you’re using shared hosting where sudo access may not be
    enabled for your user, you should set :use_sudo to false. In general, if
    you can get away without using sudo, you should avoid it.
  • keep_releases:
    The number of old releases to keep, defaults to 5, can be overridden
    with any positive integer, negative values will produce undefined
    behavior. 0 means zero.
  • git_enable_submodules:
    If you’re using git submodules you must tell cap to fetch them or not.
    You can set its value 1 to include it and 0 to not include it.
  • branch:-
    You need to tell cap the branch to checkout during deployment. For
    example we have two branches i.e master and production and you want to
    check out from master branch, then you will be write it as:
  • set :branch, “master”
  • deploy_via:-
    This option is used to tell capistrano that which deployment strategy
    we are using for deployment. There are various options available with
    deploy_via and we can chose between them as our convenience.
  • :checkout will do a full SCM checkout.
  • :copy will checkout locally, then tar and gzip the copy and sftp it to the remote servers.
  • :remote_cache
    will keep a local git repo on the server you’re deploying to and simply
    run a fetch from that rather than an entire clone. This is probably the
    best option as it will only fetch the changes since the last deploy.
  • Deployment
  • Everything
    is ready to try our recipe for the first time and let Capistrano create
    the initial directory structure on your server for future deployments.
    Run the following command from the root directory of your application:
  • cap deploy:setup cap deploy:setup
  • When
    you run this command, Capistrano will SSH to your server, enter the
    directory that you specified in the deploy_to variable, and create a
    special directory structure that’s required for Capistrano to work
    properly. If something is wrong with the permissions or SSH access, you
    will get error messages. Look closely at the output Capistrano gives you
    while the command is running.
  • The
    last step before we can do an actual deployment with Capistrano is to
    make sure that everything is set up correctly on the server from the
    setup command. There’s a simple way to verify, with the command:
  • cap deploy:check cap deploy:check
  • This
    command will check your local environment and your server and locate
    likely problems. If you see any error messages, fix them and run the
    command again. Once you can run without errors, you can proceed!Once
    you’ve verified your local and server configuration, run the following
    command:
  • cap production deploy:migrations
  • This command just log in to production and deploy the latest code from the master branch and run all the pending migrations.
  • cap deploy
  • This
    will perform a deployment to your default stage, which is staging. If
    you want to deploy to production, you’d run the following:
  • cap production deploy production deploy
  • While
    these commands are performed, you will see a lot of output. Capistrano
    print all commands it runs on your server as well as their output,
    making it possible for you to debug any problems. Enjoy the dynamic
    deployments using capistrano !!