Blog Archive

Wednesday, 25 April 2012

Remote start of iTunes on Mac

I leave my Mac Mini on all the time because I like to use it pretty much all the time, and it runs Plex server so I can watch movies on the iPad etc.  It's on all the time is the point.

I have the Mac hooked up to an FM transmitter so I can listen to music wherever I have an FM radio in my house.  Which is everywhere in my house.  I listen to either Spotify (using "Remoteless" on the iPhone) or by playing stuff from iTunes using the Apple "Remote" app for the iPhone.  This works great if I remember to restart iTunes when I'm not actually sitting at my desk any more.  Mostly I forget.  I have to shut down iTunes when I actually want to use my Mac because it's a big fat ugly resource hog.

So I needed a way to start iTunes on my dekstop from the iPhone.  Having had a bit of experience with Unix and Linux, I know I can start graphical applications remotely using a combination of bash scripts, php scripts and a bit of web-server action.  The script sets the right DISPLAY variable, and runs the right app.  Could this work on my Mac I thought?  Well, yes it could.  Here's what I did:
I enabled the personal web server in Mac OS X.  It's in the Network bit of Setting somewhere, I'm pretty sure Google will know if you ask it nicely.  The files you want to serve via http go in ~/Sites/ and are accessed using the name of your Mac host in a URL like this : "http://macmini/~andy/".  So I plonked an index.php in ~/Sites which looks like this:

<?
echo "<hr>";
echo "Starting iTunes for user andy...!";
exec ('/usr/bin/sudo -u andy /Applications/iTunes.app/Contents/MacOS/iTunes > /tmp/itunes.www.out.txt 2>&1 &',$output);
echo "<hr>";
print_r($output);
echo "<hr>";
?>

The practical upshoot of all this is that if I go to http://macmini/~andy/index.php in Safari on my iPhone, iTunes starts up on my Mac and the Remote app can actually start stuff playing.

Notes : You need to allow the user which actually runs the http service (the web server) to use sudo without a password.  This seems to be the "_www" user.  I added it to the sudoers file in Terminal, because that's where I'm most comfortable doing it.  I ran:
sudo visudo
and the added this line to the right bit of the file (under where it says "# User privilege specification"):
_www ALL=(ALL) NOPASSWD: ALL

Job done.

There are, I'm sure, eleventy-million other ways of doing this, many of which will be deemed as "better" than my way.  My way works for me, and that's all I need.