Chatting on Last.fm using websockets

Adding a Chat box on Last.fm is easier than you think. Here’s a quick hack.

qop chat

The hack

As shown before, it’s relatively easy to embed a chat box on twitter. Doing the same for last.fm is trivial. First, we need to add omniauth_lastfm in the Gemfile of our Sinatra app.

    gem 'omniauth-lastfm'

We need to add also the require in the app file:

    require 'omniauth-lastfm'

Now we have to define the OAuth callback for Lastfm:

  get '/auth/lastfm/callback' do
    auth = request.env["omniauth.auth"]

    user = User.first_or_create({ :uid => auth["uid"]}, {
      :uid => auth["uid"],
      :name => auth["info"]["name"],
      :nickname => auth["info"]["name"],
      :created_at => Time.now })

    session[:user_id] = user.id # User logged in
    redirect 'http://last.fm'
  end

Chrome Extension

We add a Chrome Extension that automatically loads up the javascript and opens the chat box. The manifest.json is:

    {
       "content_scripts": [ {
          "js": [ "qop.js" ],
          "matches": [ "http://*.last.fm/*", "https://*.last.fm/*" ],
          "run_at": "document_end"
       } ],
       "description": "Last.fm Chat",
       "name": "qop.im",
       "version": "1.0",
       "manifest_version": 2
    }

And the qop.js is:

    if (window.top === window) {
        (function(){
            link = document.createElement('link');
            link.href = 'http://YOURSERVER/application.css';
            link.type = 'text/css';
            link.rel = 'stylesheet';
            document.getElementsByTagName('head')[0].appendChild(link);
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.async = true;
            script.src = 'http://YOURSERVER/application.js';
            document.getElementsByTagName('head')[0].appendChild(script);})();
    }

That’s all. Give it a spin if you’d like, but remember that it’s alpha code. Here’s the Chrome extension: Chat on Last.fm