¿Cómo poner un "escuchando ahora" ("now playing") en las páginas web (foros, twitter, facebook, etc.)?

En primer lugar voy a aclarar que esta solución no es trivial pero si completas los pasos podrás insertar fácilmente un mensaje en las páginas para que aparezca la canción que estás escuchando.

Actualmente está probado en algunos foros, en twitter y en facebook sin problemas pero puede adaptarse a la página web que quieras.

Antes que nada, al ser una solución bastante particular veamos los requisitos:
Para comprender mejor el funcionamiento veamos su diagrama y secuencia de funcionamiento:


Los pasos son los siguientes:
  1. Rhythmbox envía a través de su plugin la información de la pista que se está reproduciendo a nuestro servidor web apache
  2. Nuestro servidor web procesa la petición y crea un fichero JavaScript donde se almacena la información de la pista
  3. Nuestro navegador, mediante el plugin de Greasemonkey, lee dicho fichero e inserta en la web dicha información
Una vez visto cómo funciona todo, pasamos a describir los pasos necesarios:

Preparar Rhythmbox


Lo primero es instalar el plugin Rhythmtoweb. Las instrucciones de instalación se encuentran en la página oficial:
Luego tenemos que indicarle donde enviar la petición de la canción que se está reproduciendo. Pulsamos en el menú "Editar -> Complementos", buscamos el plugin rhythmtoweb y pulsamos en "Configurar". Ahí introducimos la siguiente URL:
  • http://localhost/php/json.php
En "Interval" podemos poner lo que queramos (es el tiempo que pasa entre cada comprobación), lo normal es 5.

Preparar el servidor Apache


Como hemos visto antes, Rhythmbox enviará información sobre la canción que se está reproduciendo a http://localhost/php/json.php. Por tanto, tenemos que crear una página web llamada json.php y gardarla en el directorio php dentro del directorio raíz del servidor. En Ubuntu el directorio se encuentra en "/var/www/":
$ sudo mkdir /var/www/php
$ gedit /tmp/json.php
Ahora copiamos en el fichero lo siguiente:
<?php

/*
This example stores the last few songs played in JSON format. It is also able to
serve the json with a callback, useful if this script is on a different domain
than the one where the website is. Example:

<script type="text/javascript">
function rtw_callback(arrayOfSongs) {
 // do something with the songs
}
</script>
<script type="text/javascript" src="http://example.com/json.php?get&callback=rtw_callback">
</script>
*/

$C = array(
 'jsFile'     => 'nowplaying.js',
 'maxEntries' => 1,
);

require_once 'RTWUtils.class.php';

if (array_key_exists('get', $_GET)) {
 $json = file_get_contents($C['jsFile']);
 if (array_key_exists('callback', $_GET)) $json = $_GET['callback'] . '(' . $json . ')';
 header("Content-Type: text/javascript");
 echo $json;
}
else {
 $song_info = RTWUtils::getInfoFromRequest();

 $last_songs = json_decode(file_get_contents($C['jsFile']), true);
 
 if (!is_array($last_songs)) $last_songs = array();
 elseif (count($last_songs) >= $C['maxEntries']) {
  while (count($last_songs) >= $C['maxEntries']) {
   array_shift($last_songs);
  }
 }

 $last_songs[] = $song_info;
    $file = fopen($C['jsFile'], "w");
    fwrite($file, "var song = ");
    fwrite($file, json_encode($last_songs));
    fclose($file);
// file_put_contents($C['jsFile'], json_encode($song_info));
}

?>
Nota: Esta es una versión simplificada del ejemplo que proporciona el creador del plugin.

Ahora copiamos el fichero al directorio de la web y asignamos permisos para que el servidor pueda crear el fichero javascript:
$ sudo cp /tmp/json.php /var/www/php
$ sudo chmod 777 /var/www/php
También tenemos que copiar en la misma carpeta el siguiente fichero del que depende el anterior, también incluido en los ejemplos del plugin:

Preparar el navegador

Lo primero es instalar el plugin Greasemonkey:
Tras reiniciar el navegador veremos que aparece el icono de un mono abajo a la derecha. Ahora pulsamos en el siguiente enlace para instalar el script:
Por defecto está preparado para el foro de Manerasdevivir.com, twitter y facebook pero con un poco de maña en JavaScript podemos adaptarlo a cualquier página que tenga un campo de texto. Veamos el código fuente para ver las partes que habría que modificar en el caso de que queramos añadir otra página:
// Escuchando_Ahora
// Copyright (c) 2010, Federico Fernández Beltrán
// Released under the GPL license
// http://www.gnu.org/copyleft/gpl.html
//
// --------------------------------------------------------------------
//
// This is a Greasemonkey user script.
//
// To install, you need Greasemonkey: http://greasemonkey.mozdev.org/
// Then restart Firefox and revisit this script.
// Under Tools, there will be a new menu item to "Install User Script".
// Accept the default configuration and install.
//
// To uninstall, go to Tools/Manage User Scripts,
// select "Escuchando_Ahora", and click Uninstall.
//
// --------------------------------------------------------------------
//
// ==UserScript==
// @name Escuchando_Ahora
// @namespace http://tutorialexception.blogspot.com
// @description Pone "Escuchando ahora" en los campos que elijas
// @include http://www.manerasdevivir.com/foro/*
// @include http://twitter.com/*
// @include http://www.facebook.com/*
// ==/UserScript==

var p = unsafeWindow;
var nowplaying = document.createElement('script'); 
nowplaying.src = 'http://localhost/php/nowplaying.js';
nowplaying.type = 'text/javascript'; 
document.getElementsByTagName('head')[0].appendChild(nowplaying);

GM_registerMenuCommand('NowListening: populateField', populateField);

waitLoad();

function waitLoad() {    
    if (typeof p.song=='undefined') { 
        window.setTimeout(waitLoad, 100);
    }
    else {
        populateField();
    }    
}

var hosts = [ 
              "manerasdevivir.com",
              "twitter.com",
              "facebook.com"
            ];
var prefixes = [ 
                 "\n\n---- \n [color=darkblue]Escuchando ahora:[/color]",
                 "#nowplaying: ",
                 "\n\n---- \n <font color=\"blue\">Escuchando ahora:</font>",
                 "Escuchando ahora:"
               ];
                        
var hosts_prefixes = { // hosts_index:prefixes_index
                        0:0, 1:1, 2:3
                     };
// types= 0:forum, 1:html, 2:simple
var hosts_types = { // hosts_index:type
                        0:0, 1:2, 2:2
                     };

function showButton() {
    var div = createElement('div', {id:'divMenu', style:"position:absolute; top:3px; right:3px; z-index:1000; background-color:#FFA636; padding:2px 5px 2px 5px; -moz-border-radius:3px; font-size:small; cursor:move;"}); 
    document.body.appendChild(div);
 
    a = createElement('a', {href:"javascript:populateField()", style:'text-decoration:none !important;'}, 'click populateField false', 'Add Now Listening');
    div.appendChild(a);
    div.appendChild(createElement('span',null,null,' '));
}

function createElement(type, attrArray, evtListener, html) {
    var node = document.createElement(type);

    for (var attr in attrArray) if (attrArray.hasOwnProperty(attr)){
        node.setAttribute(attr, attrArray[attr]);
    }

    if(evtListener){
        var a = evtListener.split(' ');
        node.addEventListener(a[0], eval(a[1]), eval(a[2]));
    } 

    if(html) {
        node.innerHTML = html;
    }

    return node;
}

function populateField() {
    var host = location.host;
    if (host.match("^www\.")) {
        host = host.substring(4);
    }
    var textarea = getTextArea(host);
    
    if(textarea!=false) {
        var host_index = getHostIndex(host);
        if (host_index == -1) {
            alert("'Escuchando ahora' El host " +  host +  " no está configurado!");
            return;
        }
        var prefix = prefixes[hosts_prefixes[host_index]];
        var prefix_encoded = encodeRegex(prefix);

        var content = getNowListening(p.song[0], host_index);
        var textareacontent = textarea.value;
        var pos = textareacontent.search(prefix_encoded);
        
        if(pos!=-1) {
            if(pos>0) {
                textareacontent = textareacontent.substring(0, pos);
            } else {
                textareacontent = "";
            }
        }
        textarea.value = textareacontent + content;

    }
}

function getTextArea(host) {
    if (host == "twitter.com") {
        var textarea = document.getElementById('status');
    } else if (host == "facebook.com") {
        var textarea = document.getElementsByName('status')[0];
    } else if (host == "manerasdevivir.com") {
        var textarea = document.getElementsByName('message')[0];
        if(textarea==undefined) {
            textarea = document.getElementById('text_editor_textarea');
        }
    }
    
    if(textarea==undefined) {
        return false;   
    } else {
        return textarea;
    }
}

function getHostIndex(host) {
    var prefix_count;
    for (var i = 0; i < hosts.length; i++){ 
         if(hosts[i] == host) {
            return i;
         }
    }
    return -1;
}

function getNowListening(songObj, host_index) {    
    var content = prefixes[hosts_prefixes[host_index]] + " ";
    
    var artist = songObj.artist.replace(/\\/g, '');
    var title = songObj.title.replace(/\\/g, '');
    var album = songObj.album.replace(/\\/g, '');
    content += getListenString(host_index, artist, title, album, songObj.genre=="Podcast");
    
    return content;
}

function getListenString(host_index, artist, title, album, podcast) {
    var type = hosts_types[host_index];
    var open = "";
    var close = "";
    if (type == 0) {
        open = "[b]";
        close = "[/b]";
    } else if(type == 1) {
        open = "<b>";
        close = "</b>";
    }
    if (podcast) {
        return "Podcast: " + open + artist + close +" - " + open + title + close;
    } else {
        return open + artist + close + " - " + open + title + close +" del disco " + open + album + close;
    }
}
                     
function encodeRegex(s) {
    return s.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1');
}
  • Añadir al array "hosts" (línea 46) el dominio que queramos añadir.
  • Si queremos añadir un nuevo prefijo a la información añadirlo a la variable "prefixes" (línea 51)
  • Enlazar el índice de nuestro hosts con el índice del prefijo que queramos en la variable "hosts_prefixes" (línea 58)
  • Enlazar el índice de nuestro hosts con el tipo de elemento (0 para foros, 1 para html y 2 simple)
  • Añadir una nueva cláusula if en la función "function getTextArea(host)" (línea 98) que devuelva el campo de texto o textarea
Por supuesto, tendríamos que añadir el dominio de la página a nuestro script en Greasemonkey. Para ello pulsamos en firefox en el botón derecho del icono de greasemonkey, elegimos "Administrar Scripts", seleccionamos "Escuchando Ahora" y pulsamos en "Añadir".

Una vez instalado nos aparecerá un icono en la parte superior derecha con el mensaje "Add Now Listening" que inserta el mensaje en el campo de texto. También se crea un comando accesible mediante el botón derecho sobre el icono de GreaseMonkey.

Espero que os sea de utilidad.

0 comentarios:

Publicar un comentario