iTunes Library File Uploader

What follows is an overview of how to automatically upload your iTunes library file to a remote server whenever music is playing no more often than once an hour.

Simply save the following two files as /usr/local/bin/upload_itunes_lib.sh and ~/Library/LaunchAgents/net.kdough.iTunes.plist, respectively and make the first file executable as it is, of course, a shell script. Be sure to update the text shown in bold to reflect your account and path information. All that's left to do is to tell launchd to load the new configuration file: launchctl load ~/Library/LaunchAgents/net.kdough.iTunes.plist Please note that this is done automatically for you at boot time so you could just restart your machine.

After a few seconds (depending on connection speeds), your iTunes library should exist on your server. If you see nothing, try running the script by hand (using "bash -x upload_itunes_lib.sh") after removing the timestamp file first (specified under last_run_path).

Once this library file is on your server, you can do cool things with it using XSLT. For example, I list the last 200 songs I've listened to using itunes.xsl. See my "music report" for that stylesheet in action.

#!/bin/bash
#
# Quick script to upload my iTunes library to a remote server
# no more often than a specified period of time.  This script
# assumes you have some sort of rsa/dsa/etc. keypair in place
# so that ssh/scp sessions do not require a password.
#
# Copyright (c) 2005 Kevin Dougherty
#

library="/Users/your_user_name/Music/iTunes/iTunes Music Library.xml"
remote_path="public_html/itunes.xml"
remote_user="your_remote_user_name"
remote_host="my.server.com"
last_run_path="/Users/your_user_name/Music/iTunes/.itunes_last_upload"
seconds_between_uploads=3600 # one hour
cur_time=`/bin/date '+%s'`
last_run=$(($cur_time - $seconds_between_uploads))

if [ -e $last_run_path ]; then
        last_run=`/usr/bin/stat -t '%s' "$last_run_path" | awk '{ print $9 }' | cut -c2-11`
fi

seconds_elapsed=$(($cur_time - $last_run))

if [ $seconds_elapsed -ge $seconds_between_uploads ]; then
        /usr/bin/scp -C -q "$library" $remote_user@$remote_host:$remote_path-tmp
        /usr/bin/ssh -q $remote_user@$remote_host "mv $remote_path-tmp $remote_path"
        /usr/bin/touch "$last_run_path"
fi

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
        <key>Label</key>
        <string>net.kdough.iTunes</string>
        <key>OnDemand</key>
        <true/>
        <key>ProgramArguments</key>
        <array>
                <string>/usr/local/bin/upload_itunes_lib.sh</string>
        </array>
        <key>WatchPaths</key>
        <array>
                <string>/Users/your_user_name/Music/iTunes/iTunes Music Library.xml</string>
        </array>
</dict>
</plist>