The video upload marks the spot.

It’s about time I write on this thing since it has been months since my last post. I was sifting through some old code I’d written last year and I tell you what, sometimes I’m actually shocked at the things I’ve written that I have forgotten about. For instance, I had a client who wanted not only the ability to upload videos, but also link to videos through YouTube. Sounds easy right? Okay but make the videos play in the same player, and make them look like there is no difference. Not so easy. It took a lot of scrounging since this was last year, prior to the YouTube API, however it became a very fun little project involving ffmpeg and rvideo.

Basically what happens is if a video has a YouTube ID, then go get the thumbnail image and the original MPEG file from YouTube and convert it to flv before saving. If the user uploads a video, use ffmpeg to grab a still of the first frame to use as the thumbnail, then convert it to flv and save it.

I present thee Video model. (Unfortunately this was so long ago, I was using attachment_fu… maybe Paperclip would have helped a bit.)

class Video < ActiveRecord::Base
  include AASM

  aasm_column :state
  aasm_initial_state :pending
  aasm_state :pending
  aasm_state :converting
  aasm_state :converted, :enter => :set_new_filename
  aasm_state :error

  aasm_event :convert do
    transitions :from => :pending, :to => :converting
  end

  aasm_event :converted do
    transitions :from => :converting, :to => :converted
  end

  aasm_event :failure do
    transitions :from => :converting, :to => :error
  end

  def get_yt_video_data
    uri = URI.parse("http://www.youtube.com/get_video_info")
    post_args = { 'video_id' => self.url }
    res, data = Net::HTTP.post_form uri, post_args
    b = res.body
    CGI::parse(b) ## return a hash of k=>v pairs
  end

  def get_yt_video_thumb
    get_yt_video_data["thumbnail_url"].first
  end

  def get_yt_video_duration
    seconds = get_yt_video_data["length_seconds"].first.to_i ## format this better... seconds/60 = mins/60 = hours ... hh:mm:ss
    total_minutes = seconds / 1.minutes
    seconds_in_last_minute = seconds - total_minutes.minutes.seconds
    "#{total_minutes}:#{seconds_in_last_minute}"
  end

  def get_yt_embed_url
    return CGI::escape("#{public_filename}") unless self.url.present?
    data = get_yt_video_data
    fmt = '';
    fmt_map = data["fmt_map"]
    a = fmt_map[0..2]
    if a == '18/'
      fmt = '18'
    elsif a == '22/'
      fmt = '22'
      break
    end
    token = data["token"]
    uri2 = URI.parse("http://www.youtube.com")
    args2 = {:video_id => url, :t => token, :fmt => fmt }
    qstr = "video_id=#{url}&t=#{token}&fmt=18"
    res = ""
    Net::HTTP.start(uri2.host, uri2.port) {|http|
      res = http.head("/get_video?#{qstr}")
    }
    CGI::escape("#{res.header['Location']}")
  end

  protected

  def after_create
    return true if url.present?
    convert
  end

  def convert
    self.convert!
      spawn do
        success = system("ffmpeg -i #{full_filename} -ar 22050 -s 480x320 -f flv -y #{full_filename}.flv")
        if success && $?.exitstatus == 0
          self.converted!
        else
          self.failure!
        end
     end
  end

  def create_thumbnail
    system "ffmpeg -i #{full_filename}.flv -s 120x90 -vframes 1 -f image2 -an #{full_filename}.jpg"
  end

  def set_new_filename
    create_thumbnail
    update_attribute(:filename, "#{filename}.flv")
    update_attribute(:content_type, "application/x-flash-video")
    update_attribute(:width, "480")
    update_attribute(:height, "320")
  end

end
Posted in Uncategorized | Leave a comment

Updating Multiple DOM Elements (Unobtrusively) with AJAX in Rails

Okay, so you’re like me and you have a complex app that requires AJAX calls to update numerous areas on the page with content from partials. For instance, a date range changes, gets submitted, and that updates a calendar, the list of items below it, and so on and so forth. And, like me, you’re choosing to use sexy, unobtrusive javascript to do so. (I’ll be using jQuery as it’s my flavor of choice, but feel free to apply the same principles to your JS library). The purpose of this article is not to explain AJAX or Rails, I will assume if you’re reading, you have some education on both subjects.

First, we have a template that looks a little something like this:

<div id="events-calendar">
  <%= render :partial => "events/calendar" %>
</div>
<% form_tag events_path, :id => "update_dates", :name => "update_dates" %>
  <%= label_tag :start_date %>
  <%= text_field_tagĀ  :start_date %>
  <%= label_tag :end_date %>
  <%= text_field_tagĀ  :end_date %>
  <%= submit_tag "Go!" %>
<% end %>
<div id="events-list">
  <%= render :partial => "events/list" %>
</div>

Now, in the past using RJS, this was a very easy thing to do, you just did something to the effect of:

render :update do |page|
  page.replace "events-calendar", :partial => "events/calendar"
  page.replace "events-list", :partial => "events/list"
end

Continue reading

Posted in AJAX, Development, jQuery, Ruby on Rails | Leave a comment

Fluid Icons

Rock out. I’m uploading several high-res Fluid icons for your pleasure.

Click Here to Download (.zip)

Credits to:

Facebook: http://cootelibeau.files.wordpress.com

Github: http://github.com/blog/47-new-fluid-icon

Mint and Pivotal: http://sneaky.me/2008/11/fluid-app-icons-for-mint-and-pivotal-tracker/

Campfire: http://www.flickr.com/photos/indiekid/2555128022/

Gmail: http://iconexpo.com/


Posted in Random | Tagged , , | Leave a comment

Rails Collection Blocks

My great friend and mentor Jake Dempsey is always preaching about code readability and keeping logic out of views, etc, and therefore he’s always writing nice little helpers to do some of the magic — for instance, collection_content_for(collection) which will takes a block and will only render that block if that collection is not empty.

Now, it’s my turn to give back:

I wanted something completely reusable, simple and easy-to-read that would allow me to iterate over a collection, whilst producing an html block of content specific to the type of object in the collection. Understand? No. Okay then, here you go:

BEFORE

<% if @blog_posts && @blog_posts.size > 0 %>
  <% @blog_posts.each do |blog_post| %>
    <div class="blog_post">
      <%= link_to blog_post.title, blog_post %>
      <%= truncate blog_post.content, :length => 500 %>
    </div>
  <% end %>
<% end %>

That’s a lot of ugliness, logic, just — ugh.

Continue reading

Posted in Development, Ruby on Rails | Leave a comment

When you get really bored, and want to find a problem for this solution:

Getting the intersection and lowest values of a hash. :)

def hash_intersect_min(*hashes)
  hashes.inject(hashes.pop.dup) { |i,h| i.delete_if { |k,v| hv=h[k]; next true unless hv; i[k]=hv if hv<v; false }; i }
end

So the following:

hash_intersect_min({:a => 1, :d => 2, :k => 2, :j => 6}, {:k =>1, :a => 4, :j => 4}, {:e => 4, :k => 2, :d => 4, :j => 9})

Produces:

{:k=>1, :j=>4}

I’m completely aware of the extreme triviality this introduces to most programming, but ya know what… sometimes you need quirky crap to get you through the day. :) Happy coding!

Posted in Uncategorized | Leave a comment