'	rainmeter_itunes.vbs
'
'		A VBScript to monitor the currently playing track in iTunes
'		and write it into a file that can be monitored by Rainmeter
'
'		Copyright 2009, Marc Stewart
'		http://www.obfuscatepenguin.net/code/2009/03/27/rainmeter-itunes/

' ==== LICENCE =========================================================

'	This program is free software: you can redistribute it and/or modify
'	it under the terms of the GNU General Public License as published by
'	the Free Software Foundation, either version 3 of the License, or
'	(at your option) any later version.
'
'	This program is distributed in the hope that it will be useful,
'	but WITHOUT ANY WARRANTY; without even the implied warranty of
'	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
'	GNU General Public License for more details.
'
'	You should have received a copy of the GNU General Public License
'	along with this program.  If not, see <http://www.gnu.org/licenses/>.

' ========================================================= LICENCE ====

' ==== USER-DEFINABLE PARAMETERS =======================================

FILENAME = "D:\rainmeter_itunes_playing.txt"
SECONDS_BETWEEN_CHECKS = 2

' ======================================= USER-DEFINABLE PARAMETERS ====



Function UpdateInfo()
	Set Current = iTunes.CurrentTrack

	Name = Current.Name
	Artist = Current.Artist
	Album = Current.Album

	Set f1 = fso.CreateTextFile(FILENAME)
	f1.Write Name + vbCrLf +  Artist + vbCrLf + Album
	f1.Close
End Function

Function ClearInfo()
	Set f1 = fso.CreateTextFile(FILENAME)
	f1.Write vbCrLf
	f1.Close
End Function



Set fso = CreateObject("Scripting.FileSystemObject")

iTunesRunning = 0

delay = SECONDS_BETWEEN_CHECKS * 1000

Do
	Do
		ClearInfo()
		
		Wscript.Sleep(delay)

		Set colProcesses = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery( "Select * From Win32_Process", , 48 )
		For Each objProcess in colProcesses
			If LCase(objProcess.Name) = "itunes.exe" Then iTunesRunning = 1
		Next
	Loop While iTunesRunning = 0

	Set iTunes = CreateObject("iTunes.Application")

	Do
		PlayState = iTunes.PlayerState
		
		If PlayState Then
			UpdateInfo()
		Else
			ClearInfo()
		End If

		Wscript.Sleep(delay)
		
		iTunesRunning = 0
		
		Set colProcesses = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery( "Select * From Win32_Process", , 48 )
		For Each objProcess in colProcesses
			If LCase(objProcess.Name) = "itunes.exe" Then iTunesRunning = 1
		Next
	Loop While iTunesRunning = 1
	
	Set iTunes = Nothing
Loop