Automation

From AwkwardTV

Jump to: navigation, search

Contents

Automation

Notes

This is a Mac only process and works on Leopard 10.6.4 and with iTunes 9.2. It should be reasonably future proof. Unfortunately, I don't know how to script anything on Windows and I have cobbled together what I have found in other places to get this working. I am not an Applescript expert by any means, so improvements are welcome, although it would be good to keep the original script for reference. Your thanks / comments are gratefully received.

Update: it's still working on Snow Leopard 10.6.7 and iTunes 10.x.

What we're going to do

Mac OS X has a standard feature called "Folder Action Scripts". The system will run an Applescript we'll create each time a file is added to the folder. This script will convert the video file to an iTunes friendly, Apple TV format. It will add it to iTunes and do some basic processing of it, too. Although this process uses Applescript, I will explain each part step-by-step, as this is meant to be a beginner's guide.

What we can't do: process HD videos and have them come out as HD videos. This is a limitation of Handbrake. HD videos some out as a middle ground - higher quality than SD, but not full HD. This is correct as of version 0.9.4 of handbrake. Future versions may improve this situation and as long as the preset for Apple TV remains named as "Apple TV" then this will work.

Update for Apple TV 2: the latest version of Handbrake has a preset for Apple TV 2 which supports HD.

Getting Started

A few little bits to do in advance. If you can't do any of these steps without further instruction, then this guide is a little too advanced for you. :-)

Download the latest Handbrake CLI version from here and place it in your home directory. Everything else you need is already installed.

Create a folder called "Automatic" in your home directory.

Create a playlist called "AutoAdded" in iTunes.

You can change the names and locations of any of the files / playlists above, but if you do, you need to suitably amend the steps / scripts outlined below.

The Script

Update: 19th Apr 2011 - revised the script to work with the new TV Rage website and now also adds show synopsis to the show description in iTunes.

First and foremost, hardcore Applescript users will simple fall over and die with horror at the mess that is the following script. I am self-taught and cobbled bits from all over the internet. I'm sorry about this. But, I can only say that this works for me and if anyone want to add spit and polish, they should go right ahead!

Open Applescript Editor (Applications --> Utilities). A blank script is in front of you. Add the following code. You can just copy and paste in.


--this tells the mac to run this script on each new item in the folder
on adding folder items to theWatchedFolder after receiving theDetectedItems
	
	try
		--we count the new items in the folder
		set filecount to (count theDetectedItems)
		--and do this for each item in the folder
		repeat with i from 1 to filecount
			
			set rawfile to item i of theDetectedItems
			set inputFile to POSIX path of rawfile
			
			--by default, set the conversion to not run
			set convert to "No"
			
			--now set it to run, if one of our wanted file types is added
			--add a line here for each file type you'd like to convert. As is, this will convert all avi, mkv and wmv files and ignore all else
			if (offset of ".avi" in inputFile) - 1 > 0 then set convert to ".avi"
			if (offset of ".mkv" in inputFile) - 1 > 0 then set convert to ".mkv"
			if (offset of ".wmv" in inputFile) - 1 > 0 then set convert to ".wmv"
			
			--when files are converted, they will become m4v files, so we need to make sure those are properly handled later
			if (offset of ".m4v" in inputFile) - 1 > 0 then set convert to ".m4v"
			
			--let's check what kind of file we have
			if convert = "No" then
				--we want to stop completely, as this isn't a video to convert and it isn't an mp4 to copy to itunes
				-- this command will stop everything
				error number -128
			else
				--conversion will proceed, you can have a message pop up here if you like. Remove the two dashes.
				set extension to convert
				
			end if
			
			
			--We need to do something with this file
			
			if extension = ".m4v" then
				
				--add the file to iTunes, it's been converted
				tell application "iTunes"
					add rawfile to playlist "AutoAdded" of source "Library"
				end tell
				
				
				
				--this calls the function below, which will process the file in iTunes. See below.
				ProcessTracks()
				
				--we will delete the original file. Obviously you could move it to a folder to keep safe or leave it in place, if you want
				try
					tell application "Finder"
						move rawfile to the trash
					end tell
				end try
				
			else
				
				--we need to convert this file
				--this sets up the file input name and output name for handbrake CLI								
				
				set outputFile to text 1 through (offset of extension in inputFile) of inputFile & "tmp"
				
				--!!!!YOU MUST CHANGE THE USERNAME HERE TO YOUR OWN USERNAME OR LOCATION OF THE FILE HandBrakeCLI!!!!!
--You could change the profile to Apple TV 2 using this next line and quoting out the one after, which is for the Apple TV 1
--do shell script "/Users/USERNAME/HandBrakeCLI -Z " & quoted form of "AppleTV 2" & " -i " & quoted form of inputFile & " -o " & quoted form of outputFile
		


				do shell script "/Users/USERNAME/HandBrakeCLI -Z AppleTV -i " & quoted form of inputFile & " -o " & quoted form of outputFile
				


				--that's created a new file with the ext "tmp"
				--when done, let's rename it to .m4v, so it can be processed
				
				set extensionTmp to (offset of ".tmp" in outputFile) - 1
				set doneFile to text 1 through extensionTmp of inputFile & ".m4v"
				
				--rename the file
				do shell script "mv " & quoted form of outputFile & " " & quoted form of doneFile
				
				--trash the file
				--you should only do this if on adding files to iTunes, the file is copied to your library.
				--Check iTunes Preferences --> Advanced and put a check against "Copy files to iTunes Media folder when adding to library"
				
				tell application "Finder"
					move rawfile to the trash
				end tell
				
			end if
			
		end repeat
		
		
		
	on error m
		display dialog "Conversion error" & return & inputFile & ": " & m
	end try
	
end adding folder items to


--This is how the tracks are processed in iTunes
on ProcessTracks()
	
	try
	
	
	tell application "iTunes"
		set sel to selection
		
		
		
		
		repeat with i from 1 to (count sel)
			
			tell (item i of sel)
				
				set epname to name
				set startpoint to 1
				set endpoint to count (epname)
				set epname_search to epname
				
				
				-- this will find the first instance of .S0, .S1 or .S3
				-- this script always assume the format SnnEnn (always two digits!)
				repeat
					set epname_search to text startpoint through endpoint of epname
					set theSeasonOffset to offset of ".S" in epname_search
					set sos to theSeasonOffset + 2
					set soe to theSeasonOffset + 2
					set checkNo to text sos through soe of epname_search
					
					if checkNo is equal to "0" then exit repeat
					if checkNo is equal to "1" then exit repeat
					if checkNo is equal to "2" then exit repeat
					if checkNo is equal to "3" then exit repeat
					set startpoint to theSeasonOffset + 3
				end repeat
				
				
				--series no 
				set theSeasonStart to theSeasonOffset + 2
				set theSeasonEnd to theSeasonOffset + 3
				set theSeason to text theSeasonStart through theSeasonEnd of epname
				set theSeasonFull to theSeason
				if text 1 of theSeason is "0" then set theSeason to text 2 of theSeason
				
				
				
				--get the ep number					
				set theEpisodeStart to theSeasonOffset + 5
				set theEpisodeEnd to theSeasonOffset + 6
				set theEpisode to text theEpisodeStart through theEpisodeEnd of epname
				set theEpisodeFull to theEpisode
				if text 1 of theEpisode is "0" then set theEpisode to text 2 of theEpisode
				
				
				
				--show name, remove "." and replace with " "
				set showend to theSeasonOffset - 1
				set shownamerough to text 1 through showend of epname
				set AppleScript's text item delimiters to the "."
				set the item_list to every text item of shownamerough
				set AppleScript's text item delimiters to " "
				set showname to the item_list as string
				set AppleScript's text item delimiters to {""}
				
				
				
				--show name, remove "." and replace with "_" to use with tvrage
				set showend to theSeasonOffset - 1
				set shownamerough to text 1 through showend of epname
				set AppleScript's text item delimiters to the "."
				set the item_list to every text item of shownamerough
				set AppleScript's text item delimiters to "_"
				set wwwshowname to the item_list as string
				set AppleScript's text item delimiters to {""}
				set theLink to "http://www.tvrage.com/" & wwwshowname & "/episode_guide/" & theSeason
				
				--get show ep name - for this, we'll have to scrape tv rage
				
				set tvrage to "some random old text, just because it can't be blank"
				try
					set tvrage to do shell script "/usr/bin/curl " & quoted form of theLink
				end try
				
				
				--search the page for ssXee
				set textFound to 0
				set searchText to theSeasonFull & "x" & theEpisodeFull
				try
					set textFound to offset of searchText in tvrage
				on error
					--Well, that didn't work, fall back to default position
					set eptitle to "Episode " & theEpisode
				end try
				
				if textFound is equal to 0 then
					set eptitle to "Episode " & theEpisode
				else
					
					--epname
					set textFound2 to textFound + 1000
					set tvrage2 to text textFound thru textFound2 of tvrage
					--display dialog tvrage2
					set titleend to (offset of "<" in tvrage2) - 1
					set eptitle to text 9 thru titleend of tvrage2
					
					--epsynopsis
					set startSynopsis to (offset of "margin_bottom" in tvrage2) + 15
					set endSynopsis to (offset of "<br><br><b>" in tvrage2) - 1
					set theSynopsis to text startSynopsis thru endSynopsis of tvrage2
					set synCount to count (theSynopsis)
					if synCount is greater than 255 then
						set theDescription to (text 1 thru 252 of theSynopsis) & "..."
					else
						set theDescription to theSynopsis
					end if
					
					
				end if
				
				
				--think we've got it all
				
				--episide no (episode number) & track number (track number)
				set episode number to theEpisode
				set track number to theEpisode
				--series no (season number)
				set season number to theSeason
				--show name
				set show to showname
				--episide title
				set name to eptitle
				--And it's a TV Show
				set video kind to TV show
				set description to theDescription
				set long description to theSynopsis
				
				display dialog "Processed file: " & epname & return & return & "Ep: " & theEpisode & return & "Track: " & theEpisode & return & "Season: " & theSeason & return & "Show: " & showname & return & "Title: " & eptitle & return & return & theSynopsis
				
				
			end tell
			
			
			
			
		end repeat
		--end timeout
		
	end tell
	
	
on error m
	--display dialog m --debugging only
	set msg to "Could not process track: " & m
	do shell script "echo " & msg & ">> " & logt
end try
	
	
end ProcessTracks

Tweaks

There are a couple of changes to make to the script for your own system. Firstly, by default avi, mkw and wmv files will be converted. If you want less or more, then you must edit the following lines:-

Filenames
if (offset of ".avi" in inputFile) - 1 > 0 then set convert to ".avi"
if (offset of ".mkv" in inputFile) - 1 > 0 then set convert to ".mkv"
if (offset of ".wmv" in inputFile) - 1 > 0 then set convert to ".wmv"

If you wanted only avi files converted, then the lines would look like this:-

if (offset of ".avi" in inputFile) - 1 > 0 then set convert to ".avi"

and if you want to add other formats (like mpg, below), do it like this:-

if (offset of ".avi" in inputFile) - 1 > 0 then set convert to ".avi"
if (offset of ".mkv" in inputFile) - 1 > 0 then set convert to ".mkv"
if (offset of ".wmv" in inputFile) - 1 > 0 then set convert to ".wmv"
if (offset of ".mpg" in inputFile) - 1 > 0 then set convert to ".mpg"
Amend your username

It's critical that you change your username in the script in the following line:-

do shell script "/Users/'USERNAME'/HandBrakeCLI -Z AppleTV -i " & quoted form of inputFile & " -o " & quoted form of outputFile

So that would become something like:-

do shell script "/Users/david/HandBrakeCLI -Z AppleTV -i " & quoted form of inputFile & " -o " & quoted form of outputFile
Error Messages

Finally, any errors that occur will show messages and stop the script. If you would prefer, you can remove the two lines that display these dialogs, either by deleting them or commenting them out (put two dashes in front of them) as follows:-

		-- display dialog "iTunes processing error" & return & epname & ": " & m

Save the script as "Converter" to the following folder Library > Scripts > Folder Action Scripts. You can now quit Applescript Editor.

Setting Everything Up

Everything is now in place. We just need to set things running.

Go to your home folder and find the folder called "Automatic" you created earlier. Right click on it and select "Folder Actions Setup". Find the script in the list called "Converter" which we saved in the step above. Click on it once and press "Attach". Make sure the "Enable Folder Actions" checkbox is selected and then you can use the red button to close the window.

What, exactly, will happen, then?

Any file that goes into the Automatic folder that is an avi, wmv or mkv will be converted to a new file with the same name, but the extension "tmp". Once the conversion is complete, the original file will be moved to the trash, the new file will be renamed .m4v (the right extension) and added to a playlist in iTunes called "AutoAdded". The converted file (now in your iTunes library) will also be trashed (there are notes in the script on how you can change this behaviour, if you want). Then, then file will be checked. If you're ripping DVDs and use the naming convention for your files as Some.Television.Show.S02E02.DVDRIP.avi (a generally accepted convention) then the script will realise that it's a TV Show and process it for you, naming the show "Some Television Show", giving it season 2 and episode 1 numbering. If it doesn't find the data, it will remain as a movie (you might want to use MetaX to process it).

Tidying Up, Extra Touches

I advise that you read the script's comments carefully. Even if you don't understand something, the comments should help you avoid any basic problems. Any lines that you want to remove, just comment them out by putting two dashes in front of them and they will no longer run (they turn grey in Applescript, just like the other comments).

This is obviously a lengthy process for the computer to run and sometimes things go wrong. The most common problem is that the script gets as far as adding the file to iTunes, but doesn't process it. I'm not sure why. If this happens, then you can make things very simple to fix by taking part of the script (below) and creating a new script and then saving it as "Process as TV Show" in your home directory > Library > iTunes > Scripts folder. Create the "Scripts" folder here if it does not exist. This will add a little script menu to iTunes with the menu option "Process as TV Show". Just select any unprocessed tracks in your AutoAdded playlist and the script will do the rest. It will, in fact, process any selected track(s) whether in the AutoAdded playlist or not.

Process as TV Show Applescript for iTunes

try
	
	
	tell application "iTunes"
		set sel to selection
		
		
		
		
		repeat with i from 1 to (count sel)
			
			tell (item i of sel)
				
				set epname to name
				set startpoint to 1
				set endpoint to count (epname)
				set epname_search to epname
				
				
				-- this will find the first instance of .S0, .S1 or .S3
				-- this script always assume the format SnnEnn (always two digits!)
				repeat
					set epname_search to text startpoint through endpoint of epname
					set theSeasonOffset to offset of ".S" in epname_search
					set sos to theSeasonOffset + 2
					set soe to theSeasonOffset + 2
					set checkNo to text sos through soe of epname_search
					
					if checkNo is equal to "0" then exit repeat
					if checkNo is equal to "1" then exit repeat
					if checkNo is equal to "2" then exit repeat
					if checkNo is equal to "3" then exit repeat
					set startpoint to theSeasonOffset + 3
				end repeat
				
				
				--series no 
				set theSeasonStart to theSeasonOffset + 2
				set theSeasonEnd to theSeasonOffset + 3
				set theSeason to text theSeasonStart through theSeasonEnd of epname
				set theSeasonFull to theSeason
				if text 1 of theSeason is "0" then set theSeason to text 2 of theSeason
				
				
				
				--get the ep number					
				set theEpisodeStart to theSeasonOffset + 5
				set theEpisodeEnd to theSeasonOffset + 6
				set theEpisode to text theEpisodeStart through theEpisodeEnd of epname
				set theEpisodeFull to theEpisode
				if text 1 of theEpisode is "0" then set theEpisode to text 2 of theEpisode
				
				
				
				--show name, remove "." and replace with " "
				set showend to theSeasonOffset - 1
				set shownamerough to text 1 through showend of epname
				set AppleScript's text item delimiters to the "."
				set the item_list to every text item of shownamerough
				set AppleScript's text item delimiters to " "
				set showname to the item_list as string
				set AppleScript's text item delimiters to {""}
				
				
				
				--show name, remove "." and replace with "_" to use with tvrage
				set showend to theSeasonOffset - 1
				set shownamerough to text 1 through showend of epname
				set AppleScript's text item delimiters to the "."
				set the item_list to every text item of shownamerough
				set AppleScript's text item delimiters to "_"
				set wwwshowname to the item_list as string
				set AppleScript's text item delimiters to {""}
				set theLink to "http://www.tvrage.com/" & wwwshowname & "/episode_guide/" & theSeason
				
				--get show ep name - for this, we'll have to scrape tv rage
				
				set tvrage to "some random old text, just because it can't be blank"
				try
					set tvrage to do shell script "/usr/bin/curl " & quoted form of theLink
				end try
				
				
				--search the page for ssXee
				set textFound to 0
				set searchText to theSeasonFull & "x" & theEpisodeFull
				try
					set textFound to offset of searchText in tvrage
				on error
					--Well, that didn't work, fall back to default position
					set eptitle to "Episode " & theEpisode
				end try
				
				if textFound is equal to 0 then
					set eptitle to "Episode " & theEpisode
				else
					
					--epname
					set textFound2 to textFound + 1000
					set tvrage2 to text textFound thru textFound2 of tvrage
					--display dialog tvrage2
					set titleend to (offset of "<" in tvrage2) - 1
					set eptitle to text 9 thru titleend of tvrage2
					
					--epsynopsis
					set startSynopsis to (offset of "margin_bottom" in tvrage2) + 15
					set endSynopsis to (offset of "<br><br><b>" in tvrage2) - 1
					set theSynopsis to text startSynopsis thru endSynopsis of tvrage2
					set synCount to count (theSynopsis)
					if synCount is greater than 255 then
						set theDescription to (text 1 thru 252 of theSynopsis) & "..."
					else
						set theDescription to theSynopsis
					end if
					
					
				end if
				
				
				--think we've got it all
				
				--episide no (episode number) & track number (track number)
				set episode number to theEpisode
				set track number to theEpisode
				--series no (season number)
				set season number to theSeason
				--show name
				set show to showname
				--episide title
				set name to eptitle
				--And it's a TV Show
				set video kind to TV show
				set description to theDescription
				set long description to theSynopsis
				
				display dialog "Processed file: " & epname & return & return & "Ep: " & theEpisode & return & "Track: " & theEpisode & return & "Season: " & theSeason & return & "Show: " & showname & return & "Title: " & eptitle & return & return & theSynopsis
				
				
			end tell
			
			
			
			
		end repeat
		--end timeout
		
	end tell
	
	
on error m
	--display dialog m --debugging only
	set msg to "Could not process track: " & m
	do shell script "echo " & msg & ">> " & logt
end try

Automatically downloading TV Shows

If you use the TV Shows application, you can set the options to automatically download new show torrents and open them with your preferred torrent client. If you use Transmission, you can set partially completed torrent to be on one folder and completed ones to be moved into another. If you set the completed location to "Automatic" folder you created earlier, then all your TV Shows will download automatically using TV Shows and Transmission and when complete, be converted and added to iTunes with the right season name, number and episode title.

Update: TV Shows has been discontinued. You might want to try Ted instead.

Please feel free to add any tips or comments here. --Simplicity 10:00, 22 June 2010 (UTC)

Personal tools