Recently Watched TV Shows in iTunes


I’ve been looking for a way to find the 10 most recently watched TV show episodes in iTunes applescript, which can then be sent to a webpage to update a MySQL database - to show a user’s 10 recently watched shows on their website.

I have this code already, but it works by hitting iTunes every few seconds and checking if it is playing. This is undesirable, as I’d like to include iPod plays as well - therefore I’d have to get episodes ordered by the Last Played date.

Here is the code I have already, but like I said, I’d much prefer if I could get episodes from their Last Played date and not on their “current track” state. Any help would be hugely appreciated.

-- Code modified from an original script by Jerry Kindall 

property pollInterval : 5
property pingURL : ""
property debug : true

global lastID
on run
	set lastID to -1
end run

on idle
		tell application "Finder" to get every process whose name is "iTunes"
		if result is not {} then
			tell application "iTunes"
				if player state is playing then
					tell current track
						if database ID is not lastID then
							if name is not missing value then
								set epname to name
								set epname to ""
							end if
							if played date is not missing value then
								set lastplayed to played date
								set lastplayed to ""
							end if
							if debug then tell me
								set trackBack to "name=" & urlEncode(epname) of me & "&lastplayed=" & lastplayed
								display dialog trackBack
							end tell
							--tell me to do shell script "curl --silent '" & trackBack & "'"
							set lastID to database ID
						end if
					end tell
				end if
			end tell
		end if
	on error m number n
		if n is -128 then
			error number n
			if debug then tell me
				display dialog m & " (#" & n & ")"
			end tell
		end if
	end try
	return pollInterval
end idle

(I’ve left out the urlEncode stuff because that’s irrelevant, as well as the track details besides name and lastplayed that I’m sending)