Hack Kung-Tunes into a Dynamic Server

Turn the Kung-Tunes utility into a server-side PHP machine and take the public display of your listening habits to the next level.

Say you’re working at your Mac while listening to some cool song and thinking “Wouldn’t it be cool if I could share what I’m listening to with my blog readers?” Well, you can! iTunes includes extensive AppleScript support, so why not write a script so you can share information about the songs you’re currently playing?

Kung-Tunes (http://kung-foo.tv/kung-tunes; donationware) is a utility that retrieves the information about the currently playing track in iTunes and uploads it to a web server. For information on setting up Kung-Tunes, visit http://www.kung-foo.tv/blog/archives/000324.php. Also, check out “Upload a Graphic of Your Currently Playing Song” [Hack #62] for another way to let your friends know what you are listening to right now.

Kung-Tunes is an extreme example that takes sharing listening info to the next level. It periodically checks whether iTunes is playing and then asks for details about the currently playing track. These details are then inserted into a highly customizable template and saved to a local file. Optionally (that is, if your Mac is not also your server), this file is submitted to your web server via FTP or HTTP, as shown in Figure 4-61.

Kung-Tunes, showing the currently playing song and the upload status

Figure 4-61. Kung-Tunes, showing the currently playing song and the upload status

Kung-Tunes comes with instructions for setting up a basic HTML template and using the FTP upload method. This hack takes the functionality of Kung-Tunes up a notch and provides server-side support for even more customizability. Instead of uploading a single static file, you will employ a server-side script to store song data on the server. This gives you the advantage that you can display your listening preferences anywhere on your web site. Because FTP can be slow and is fickle on some servers, we’ll use HTTP transfer in this hack.

First, you need to set up Kung-Tunes so that it submits iTunes data over HTTP to a PHP script that you will put on your server. Open Kung-Tunes and select the Preferences item from the Application menu. Click to reveal the Upload pane (shown in Figure 4-62), in which the following four changes have to be made. Set the upload method to HTTP and set the URL so that it points to the file kt.php on your server (you will create this file later) and set the location and name of the local file to /private/tmp/ and newtrack (or whatever you want it to be; it really doesn’t matter).

Upload settings in the Kung-Tunes Preferences dialog

Figure 4-62. Upload settings in the Kung-Tunes Preferences dialog

Click Save to dismiss the Preferences dialog, and then choose Formats from the Application menu. Clear all text fields, set the name to HTTP, and enter the following text in the “Format for currently playing track” field:

	code=secret&t=^t&p=#p^p#p&a=#a^a#a

Click Add and press the Save button to dismiss the dialog. This format string captures the information of the currently playing track that will be sent as parameters to a PHP script. For demonstration purposes, we’ll use only the title (^t), artist (^p), and album (^a) placeholders (for a full list, see the Formats dialog). Since values for artist and album cannot be set in iTunes, you wrap them in # flags, allowing Kung-Tunes to strip them so that you will not be sending the placeholders themselves. Titles are always set, so you do not have to wrap that field with flags.

The Code

We need to accomplish two tasks. First, upload your current track data to your web site. Then, use that data to display what you are listening to on your web site.

Uploading your current track data.

Now that you’ve set up Kung-Tunes to speak HTTP, you need something on your server that can actually do something with the data it gets. You will be using a simple PHP script that can not only process submission of a new song but also display what it has received so far, depending on whether it is called by a browser or by Kung-Tunes.

Save the following code as a file named kt.php. Upload this file to your server in the directory you specified in the KungTunes upload preferences. Also upload an empty file named kt.txt and set its permissions to be readable and writable by everyone.

    <?
    if ( $_SERVER['REQUEST_METHOD'] == 'POST' )
      processSong( $HTTP_POST_VARS );
    else
	  displaySongs();

    function processSong( $var_list )
    {
      extract( $var_list ); // get post parameters and check
      if ( is_null($t) or is_null($code) )
        die( "<error>Invalid usage of script</error>" );
      if ( $code != 'secret' )
        die( "<error>Incorrect password</error>" );

      // read old song list into array
      $tunes = file( 'kt.txt' );
      // forget last element if there are already more than 20 songs
      if ( count($tunes) >= 20 ) array_pop( $tunes );
      // create a new string with the song details
      $t = date("m/d, G:i").' || '.$t.' || '.$p.' || '.$a."\n";
      // add new string to array
      array_unshift( $tunes, $t );
      // merge array into string
      $t_str = join( '', $tunes );
      // write to file
      $tfile = fopen( 'kt.txt', "w" );
      fwrite( $tfile, $t_str );
      fclose( $tfile );
    }

    function displaySongs()
    {
    echo "<table>\n";
    echo "<tr> <th>time</th><th>band</th><    th>song</th><th>album</th></tr>";
      // read song list into array
      $tunes = file( 'kt.txt' );
      foreach( $tunes as $song )
      {
        $bits = explode( ' || ', $song );
        echo '<tr>';
        for ( $i = 0; $i < 4; $i++ )
          echo "<td>$bits[$i]</td>";
        echo "</tr>\n";
       }
echo "</table>\n";
       }
       ?>

The code has two main routines: processSong() and displaySongs(). The first is called when the script is called by Kung-Tunes and updates the data on the server. The second routine is called by the browser and outputs a formatted list of songs that have been stored on the server.

When the script is called by Kung-Tunes, it first checks if there is a title (t) and a code parameter. You use the code parameter to authorize usage of the script, so that you will not be embarrassed by other people submitting a series of Britney Spears songs to the script. If the code parameter does not match the password string set in the script, it will bail out.

If the parameters are valid, their values are simply saved to the kt.txt text file. This file stores the last 20 songs played and also prepends each song with the date on which it was added. If the script is called via the browser, it reads in this song list file and displays the contents as a basic HTML table.

Displaying track data on your site.

The hack doesn’t stop here, of course. Thanks to PHP and having your song data available on your server, the possibilities are endless. You could, for example, display the most recently played song on your web page (provided its filename ends in .php), using the following code snippet:

    <?
    $tunes = file('kt.txt'); // read file into array
    $bits = explode(" || ", $tunes[0]); // only use topmost item
    $songTimePlayed = $bits[0];
    $songTitle = $bits[1];
    $songArtist = $bits[2];
    $songAlbum = $bits[3];

    echo "<h3>latest <a href=\"http://www.kung-foo.tv/kung-tunes\">iTunes</a>
      song</h3>";
    echo "<p>$songTimePlayed<br />$songTitle<br />\n";
    if ( $songArtist != "" )
      echo "<br /><a href=\"http://www.amazon.com/exec/obidos/external-search*
      102-6473795-0973730?mode=music&amp;keyword=$songArtist\">$songArtist</a>*
      \n";
    if ( $songAlbum != "" )
      echo "<br /><a href=\"http://www.amazon.com/exec/obidos/external-search*
      102-6473795-0973730?mode=music&amp;keyword=$songAlbum\">$songAlbum</a>\n";*
      echo "</p>\n";
    ?>

Let’s test what you have so far. Launch Kung-Tunes and open the Preferences dialog. Edit the Runtime options to look like Figure 4-63. This tells Kung-Tunes to start up automatically and to upload info any time a different song is playing. If Kung-Tunes is not running yet, press “Start timer” in the main window.

Timer settings in the Kung-Tunes Preferences dialog

Figure 4-63. Timer settings in the Kung-Tunes Preferences dialog

To see what’s happening under the hood, open Window Console and Kung-Tunes will provide a detailed transcription report. This is useful for debugging the PHP script, because any error messages returned from the server will be shown in this console.

Adriaan Tijsseling

Get iPod and iTunes Hacks now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.