Jump to content

Sky Slate Blueberry Blackcurrant Watermelon Strawberry Orange Banana Apple Emerald Chocolate
Photo

SceneRenamer - Renames "Scene" releases of TV Show


  • Please log in to reply
56 replies to this topic
strictlyfocused02
  • Members
  • 64 posts
  • Last active: Dec 11 2015 08:35 PM
  • Joined: 21 Jan 2009
Updated the main post with a new version (1.40). Its mainly just a bug fix I noticed since TheTVDB is down at the moment. Check out the changelog at the bottom of the script for more info.

I also want to thank everyone for the kind words. It means a lot to me coming from you guys that my "pet project" is appreciated :D

ZACH4
  • Members
  • 15 posts
  • Last active: Feb 06 2012 10:11 PM
  • Joined: 26 Feb 2009
I'm getting an error when I try to run this script.

Erro at line 184.

Line Text: StringReplace, EpisodeTitle
Error: "StringReplace" requires that parameter #3 be non-blank.

The program will exit.



ZACH4
  • Members
  • 15 posts
  • Last active: Feb 06 2012 10:11 PM
  • Joined: 26 Feb 2009
Added a . for the third parameter and it works now.

strictlyfocused02
  • Members
  • 64 posts
  • Last active: Dec 11 2015 08:35 PM
  • Joined: 21 Jan 2009
ZACH4, my apologies. Apparently the forums have an internal parser that uses &`#44; as a delimter (minus the 2nd char[the accent]) and replaces it with a comma in scripts that are posted but never converts it back to the original 5 characters.

I have updated the main post and tested what was uploaded so everything should work now. :)

Pacheco
  • Members
  • 168 posts
  • Last active: Apr 11 2013 08:21 AM
  • Joined: 23 Feb 2006
@strictlyfocused02:

I've tried your application and in fact it works very well...
But as it don't preserves the Source.Codec-Group stuff, that for me is important, I've modified (after some hours searching for an app that already implements it - there isn't i guess) you app to include this info.

As i don't understand REGEX (unfortunately), i have to code a lit bit "dirty"... For now it has worked, but if someone wants my version, feel free to better it up... :)

for example
Dexter.S04E11.HDTV.XviD-SYS => Dexter - S04E11 - Hello Dexter Morgan - HDTV.XviD-SYS

or

Fringe.S02E10.HDTV.XviD-FQM => Fringe - S02E10 - Grey Matters - HDTV.XviD-FQM

My MODDED files are here:
http://dl.dropbox.co...sode_Rename.rar

strictlyfocused02
  • Members
  • 64 posts
  • Last active: Dec 11 2015 08:35 PM
  • Joined: 21 Jan 2009
Updated the main post with version 1.42. Just two bug fixes.

Pacheco, Im glad my script was able to suit your needs :D

Delusion
  • Members
  • 272 posts
  • Last active: Jul 13 2014 09:04 PM
  • Joined: 16 Jul 2008
thats a very usefull mod Pacheco thanks for it
i want to keep the release name at the end too because this way i always know what subtitles i have to download when i need some
QuickSubs | Popcorn Movie Catalog
All my scripts are just in AutoHotkey v1.0.48.05

Paradox
  • Members
  • 24 posts
  • Last active: Mar 05 2013 04:15 PM
  • Joined: 05 Feb 2010
This is exactly the script I have been looking for, and had planned on writing myself before I found it, all other renamers didn't work the way I needed them to. That being said, I have spent the last 2 days cleaning up some errors and changing the way certain things work.

If the original author wants to add any or all of this to the official version, all I ask for is a bit of credit, if not, hopefully someone will find my changes useful.

I can provide a diff (patch) file, if anyone wants to see exactly what I changed without manually combing through, or, you can get wdiff32 (on windows) for free and use that to see what i changed.
1.42.1
; SceneRenamer by strictlyfocused02
; Modified By Paradox iamparadox at netscape.net
; AutoHotkey Version: 1.0.48+
;
; Script Function:
;   Extracts season and episode info from the filename
;   and uses that to retreive info from TheTVDB.com to rename
;   the file to a user-specified format

;   Special thanks to TheTVDB.com
;   This project would not have been possible without their top-notch API

#Include xpath.ahk

#NoEnv
SendMode, Input
SetWorkingDir, %A_ScriptDir%

WindowTitle = SceneRenamer v1.42.1 Modified By Paradox

Gui, Add, Button, Default gButtonAddFolder, &Add folder
Gui, Add, Button, x+20 gButtonAddFile, &Add file
Gui, Add, Button, x+20 gButtonClear, &Clear list
Gui, Add, Text, x+150 w50, Status:
Gui, Add, Edit, +ReadOnly x+0 w400, Waiting for user to add file(s)...

Gui, Add, ListView, xm r26 w800 -ReadOnly vMyListView, Name|Preview|Directory|Extension|TVDB Series ID No

Gui, Add, DropDownList, y+7 w250 AltSubmit vNameScheme, (Show Title) - (SS)x(EE) - (Episode Title)|(Show Title) - S(SS)E(EE) - (Episode Title)|(SS)x(EE) - Episode Title||S(SS)E(EE) - (Episode Title)
Gui, Add, Checkbox, x+30 Checked vZero, Pad with zero?
Gui, Add, Checkbox, x+30 Checked vCache, Cache Episode Info?
Gui, Add, Button, x+50 gButtonGetTVDBInfo, &Get TVDB Info
Gui, Add, Button, x+60 gButtonRename, &Rename files

Menu, MyContextMenu, Add, Open, ContextOpenFile
Menu, MyContextMenu, Add, Properties, ContextProperties
Menu, MyContextMenu, Add, Remove item, ContextRemoveItem

Gui, Show,, %WindowTitle%
Return

GuiClose:
   ExitApp

GuiContextMenu:
   If A_GuiControl <> MyListView
       Return
   Menu, MyContextMenu, Show, %A_GuiX%, %A_GuiY%
   Return

ContextOpenFile:
ContextProperties:
   FocusedRowNumber := LV_GetNext(0, "F")
   If not FocusedRowNumber
      return
   LV_GetText(FileName, FocusedRowNumber, 1)
   LV_GetText(FileDir, FocusedRowNumber, 3)
   IfInString A_ThisMenuItem, Open
      Run %FileDir%\%FileName%,, UseErrorLevel
   Else
      Run Properties "%FileDir%\%FileName%",, UseErrorLevel
   If ErrorLevel
      MsgBox Could not perform requested action on "%FileDir%\%FileName%".
   return

ContextRemoveItem:
   RowNumber = 0
   Loop
   {
      RowNumber := LV_GetNext(RowNumber - 1)
      If not RowNumber
           Break
      LV_Delete(RowNumber)
   }
   Return

ButtonAddFolder:
   Gui +OwnDialogs
   FileSelectFolder, TargetFolder,, 3, Select a folder:
   If not TargetFolder  ; The user pressed cancel
       Return
   StringRight, LastChar, TargetFolder, 1
   If LastChar = \
      StringTrimRight, TargetFolder, TargetFolder, 1
   GuiControl, -Redraw, MyListView ; Improves performance by disabling redrawing
   Loop %TargetFolder%\*.*
   {
      FileName := A_LoopFileFullPath
      SplitPath, FileName,,, FileExt  ; Get the file extension
      If FileExt in avi,mkv,mp4
         LV_Add(Row, A_LoopFileName, "", A_LoopFileDir, FileExt)
   }
   GuiControl, +Redraw, MyListView  ; Turn redrawing back on
   LV_ModifyCol()  ; Resize each column to fit
   LV_ModifyCol(2, 60)  ; Expand "Preview" to keep the header visible
   LV_ModifyCol(4, 60)  ; Expand "Extension" to keep the header visible
   LV_ModifyCol(5, 110)  ; Expand "TVDB Series ID No" to keep the header visible
   ControlSetText, Edit1, Added folder %TargetFolder%, %WindowTitle%
   Return

ButtonAddFile:
   Gui +OwnDialogs
   FileSelectFile, TargetFile
   If not TargetFile
      Return
   SplitPath, TargetFile,,, FileExt  ; Get the file extension
   If FileExt in avi,mkv,mp4
   {
      SplitPath, TargetFile, FileName, TargetFolder
      LV_Add(Row, FileName, "", TargetFolder, FileExt)
      LV_ModifyCol()  ; Resize each column to fit
      LV_ModifyCol(2, 60)  ; Expand "Preview" to keep the header visible
      LV_ModifyCol(4, 60)  ; Expand "Extension" to keep the header visible
      LV_ModifyCol(5, 110)  ; Expand "TVDB Series ID No" to keep the header visible
      ControlSetText, Edit1, Added file %TargetFile%..., %WindowTitle%
   }
   Return

ButtonClear:
   TargetFolder =
   TargetFile =
   LV_Delete()
   ControlSetText, Edit1, Cleared Listview, %WindowTitle%
   Return

InternetCheckConnection(Url="",FIFC=1) {
   Return DllCall("Wininet.dll\InternetCheckConnectionA", Str,Url, Int,FIFC, Int,0)
}

ButtonGetTVDBInfo:
   LV_GetText(LVFileName, 1, 1)
   If not LVFileName
   {
      Gui +OwnDialogs
      MsgBox, 0,Fatal Error!, You must select a file or folder before connecting to TheTVDB.com!
      Return
   }
   LV_GetText(LVFileDir, 1, 3)  ; Get the file directory
   LV_GetText(LVFileExt, 1, 4)  ; Get the file extension

   URL := "http://www.thetvdb.com"

   If not InternetCheckConnection(URL)
   {
      Msgbox, 48, [%URL%]  , Connection Failed!
      Return
   }

   RowNumber = 1
   ShowInfo := GetTVDBShows(GetShowName(LVFileName, LVFileDir))
   StringSplit, ShowArray, ShowInfo, `,
   ShowName = %ShowArray1%
   SeriesIDNo = %ShowArray2%
   Loop
   {
      Gui +OwnDialogs
      RowNumber = %A_Index%
      LV_GetText(LVFileName, RowNumber, 1)  ; Get the filename
      If not LVFileName  ; Break the loop at the end of the list
         Break
      LV_GetText(LVFileDir, RowNumber, 3)  ; Get the file directory
      LV_GetText(LVFileExt, RowNumber, 4)  ; Get the file extension
      If A_Index > 1
      {
         LV_GetText(LVPrevFN, RowNumber - 1, 1)  ; Get the preceeding rows filename
         LV_GetText(LVPrevFD, RowNumber - 1, 3)  ; Get the preceeding rows file directory
         PrevShowName := GetShowName(LVPrevFN, LVPrevFD)
         StringUpper, UpperPrevSN, PrevShowName

         NewShowName := GetShowName(LVFileName, LVFileDir)
         StringUpper, UpperCurrSN, NewShowName
         If UpperCurrSN <> %UpperPrevSN%
         {
            ShowInfo := GetTVDBShows(NewShowName)
            StringSplit, ShowArray, ShowInfo, `,
            ShowName = %ShowArray1%
            SeriesIDNo = %ShowArray2%
         }
      }
      UpperPrevSN =
      SeasonNumber := GetSeasonNumber(LVFileName)
      EpisodeNumber := GetEpisodeNumber(LVFileName)
      ControlSetText, Edit1, Processing "%ShowName%" Season "%SeasonNumber%" Episode "%EpisodeNumber%", %WindowTitle%
      If SeriesIDNo
      {
         IfInString, ShowName, %A_Space%
            StringReplace, SafeShowName, ShowName, %A_Space%, _, All
         Else
            SafeShowName = %ShowName%
         EpisodeInfo := GetTVDBEpisodes(SeriesIDNo, SeasonNumber, EpisodeNumber, SafeShowName)
         StringSplit, OutputArray, EpisodeInfo, `,
         SeasonNumber = %OutputArray1%
         EpisodeNumber = %OutputArray2%
         EpisodeTitle = %OutputArray3%
         If EpisodeTitle
         {
            StringReplace, EpisodeTitle, EpisodeTitle, \, %A_Space%~%A_Space%, All
            StringReplace, EpisodeTitle, EpisodeTitle, /, %A_Space%~%A_Space%, All
            StringReplace, EpisodeTitle, EpisodeTitle, :, %A_Space%~%A_Space%, All
            StringReplace, EpisodeTitle, EpisodeTitle, *, %A_Space%~%A_Space%, All
            StringReplace, EpisodeTitle, EpisodeTitle, ?,, All
            StringReplace, EpisodeTitle, EpisodeTitle, ", ', All
            StringReplace, EpisodeTitle, EpisodeTitle, <, %A_Space%less than%A_Space%, All
            StringReplace, EpisodeTitle, EpisodeTitle, >, %A_Space%greater than%A_Space%, All
            StringReplace, EpisodeTitle, EpisodeTitle, |, %A_Space%~%A_Space%, All
            StringReplace, EpisodeTitle, EpisodeTitle, &`#44;, `,, All
            StringReplace, EpisodeTitle, EpisodeTitle, &, &, All
         }
      }
      GuiControlGet, PadZero,, Zero
      If PadZero = 1
      {
         SeasonNumber := PadZero(SeasonNumber)
         EpisodeNumber := PadZero(EpisodeNumber)
      }
      GuiControlGet, NamingScheme,, NameScheme
      If NamingScheme = 1
      {
         If EpisodeTitle
            NewFileName = %ShowName% - %SeasonNumber%x%EpisodeNumber% - %EpisodeTitle%.%LVFileExt%
         Else
            NewFileName = %ShowName% - %SeasonNumber%x%EpisodeNumber%.%LVFileExt%
      }
      Else if NamingScheme = 2
      {
         If EpisodeTitle
            NewFileName = %ShowName% - S%SeasonNumber%E%EpisodeNumber% - %EpisodeTitle%.%LVFileExt%
         Else
            NewFileName = %ShowName% - S%SeasonNumber%E%EpisodeNumber%.%LVFileExt%
      }
      Else If NamingScheme = 3
      {
         If EpisodeTitle
            NewFileName = %SeasonNumber%x%EpisodeNumber% - %EpisodeTitle%.%LVFileExt%
         Else
            NewFileName = %SeasonNumber%x%EpisodeNumber%.%LVFileExt%
      }
      Else If NamingScheme = 4
      {
         If EpisodeTitle
            NewFileName = S%SeasonNumber%E%EpisodeNumber% - %EpisodeTitle%.%LVFileExt%
         Else
            NewFileName = S%SeasonNumber%E%EpisodeNumber%.%LVFileExt%
      }
      LV_Modify(RowNumber, Col1, LVFileName, NewFileName, LVFileDir, LVFileExt, SeriesIDNo)
      LV_ModifyCol()
      LV_ModifyCol(4, 60)
      LV_ModifyCol(5, 110)  ; Expand "TVDB Series ID No" to keep the header visible
      LVFileName =
      LVPrevFN =
      ShowArray1 =
      OutputArray1 =
      OutputArray2 =
      OutputArray3 =
      SeasonNumber =
      EpisodeNumber =
      EpisodeTitle =
   }
   ControlSetText, Edit1, Finished querying TheTVDB.com. Ready to rename..., %WindowTitle%
   Return

ButtonRename:
   LV_GetText(LVNewFileName, 1, 2)
   If not LVNewFileName
   {
      Gui +OwnDialogs
      MsgBox, 0,Fatal Error!, You must scan your files against TheTVDB.com before you rename them!
      Return
   }
   Loop
   {
      RowNumber = %A_Index%
      LV_GetText(LVFileName, RowNumber, 1)  ; Get the original filename
      If not LVFileName  ; Break the loop at the end of the list
         Break
      LV_GetText(LVNewFileName, RowNumber, 2)  ; Get the new filename
      LV_GetText(LVFileDir, RowNumber, 3)  ; Get the file dir
      ControlSetText, Edit1, Renaming "%LVFileName%" to "%LVNewFileName%", %WindowTitle%
      FileMove, %LVFileDir%\%LVFileName%, %LVFileDir%\%LVNewFileName%  ; Finally, rename it
   }
   RenameCount := RowNumber - 1
   ControlSetText, Edit1, Finished renaming files! Refreshing file list., %WindowTitle%
   LV_Delete()
   Loop %LVFileDir%\*.*
   {
      FileName := A_LoopFileFullPath
      If not FileName
         Break
      SplitPath, FileName,,, FileExt  ; Get the file extension
      If FileExt in avi,mkv,mp4
         LV_Add(Row, A_LoopFileName, "", A_LoopFileDir, FileExt)
   }
   GuiControl, +Redraw, MyListView  ; Turn redrawing back on
   LV_ModifyCol()  ; Resize each column to fit
   LV_ModifyCol(2, 60)  ; Expand "Preview" to keep the header visible
   LV_ModifyCol(4, 60)  ; Expand "Extension" to keep the header visible
   LV_ModifyCol(5, 110)  ; Expand "TVDB Series ID No" to keep the header visible
   Return

;Provide a filename (s01e01.avi or greek.s01e01.avi) and Directory name (C:\TV\greek) and this should return the show name
GetShowName(FileName, FileDir)
{
   TempName := GetName(FileName)
   If not TempName
      TempName := GetNameFromDir(FileName, FileDir)
   Return TempName
}
;Provide a filename (greek.s01e01.avi) and this should return the show name
GetName(FileName)
{
   IfInString, FileName, .
      StringReplace, NormalName, FileName, ., %A_Space%, All
   IfInString, NormalName, _
      StringReplace, NormalName, NormalName, _, %A_Space%, All
   If RegExMatch(NormalName, "i)s[0-9][0-9]? ?e[0-9][0-9]?", SeasonAndEpisode)
   {
      StringGetPos, SeasonAndEpisodePos, NormalName, %SeasonAndEpisode%
      StringLeft, ShowName, NormalName, (SeasonAndEpisodePos - 1)
   }
   Else If RegExMatch(NormalName, "i)[0-9][0-9]?x[0-9][0-9]?", SeasonAndEpisode)
   {
      StringGetPos, SeasonAndEpisodePos, NormalName, %SeasonAndEpisode%
      StringLeft, ShowName, NormalName, (SeasonAndEpisodePos - 1)
   }
   Else If RegExMatch(NormalName, "[0-9][0-9][0-9][0-9]?", SeasonAndEpisode)
   {
      StringGetPos, SeasonAndEpisodePos, NormalName, %SeasonAndEpisode%
      StringLeft, ShowName, NormalName, (SeasonAndEpisodePos - 1)
   }
   Loop
   {
      StringRight, LastChar, ShowName, 1
      If (LastChar = "-" or LastChar = " ")
         StringTrimRight, ShowName, ShowName, 1
      Else
         Break
   }
   Return ShowName
}

;Provide a filename (s01e01.avi) and Directory name (C:\TV\greek) and this should return the show name
GetNameFromDir(FileName, FileDir)
{
   Directory = %FileDir% - %FileName%
   SplitPath , Directory, NewFileName, dir, ext, name
   Return GetName(NewFileName)
}

;Provide a filename (greek.s01e01.avi) and this should return the season number
GetSeasonNumber(FileName)
{
   If RegExMatch(FileName, "i)s\K[0-9][0-9]?.?e[0-9][0-9]?", SeasonAndEpisode)
   {
      StringSplit, OutputArray, SeasonAndEpisode, e E, .
      SeasonNumber = %OutputArray1%
      IfInString, SeasonNumber, 0
      {
         StringGetPos, ZeroLoc, SeasonNumber, 0
         If ZeroLoc = 0
            StringTrimLeft, SeasonNumber, SeasonNumber, 1
      }

   }
   Else If RegExMatch(FileName, "i)[0-9][0-9]?x[0-9][0-9]?", SeasonAndEpisode)
   {
      StringSplit, OutputArray, SeasonAndEpisode, x X
      SeasonNumber = %OutputArray1%
      IfInString, SeasonNumber, 0
      {
         StringGetPos, ZeroLoc, SeasonNumber, 0
         If ZeroLoc = 0
            StringTrimLeft, SeasonNumber, SeasonNumber, 1
      }
   }
   Else If RegExMatch(FileName, "[0-9][0-9][0-9][0-9]?", SeasonAndEpisode)
   {
      StringTrimRight, SeasonNumber, SeasonAndEpisode, 2
      IfInString, SeasonNumber, 0
      {
         StringGetPos, ZeroLoc, SeasonNumber, 0
         If ZeroLoc = 0
            StringTrimLeft, SeasonNumber, SeasonNumber, 1
      }
   }
   Return SeasonNumber
}

;Provide a filename (greek.s01e01.avi) and this should return the episode number
GetEpisodeNumber(FileName)
{
   If RegExMatch(FileName, "i)s\K[0-9][0-9]?.?e[0-9][0-9]?", SeasonAndEpisode)
   {
      StringSplit, OutputArray, SeasonAndEpisode, e E, .
      EpisodeNumber = %OutputArray2%
      IfInString, EpisodeNumber, 0
      {
         StringGetPos, ZeroLoc, EpisodeNumber, 0
         If ZeroLoc = 0
            StringTrimLeft, EpisodeNumber, EpisodeNumber, 1
      }
   }
   Else If RegExMatch(FileName, "i)[0-9][0-9]?.?x[0-9][0-9]?", SeasonAndEpisode)
   {
      StringSplit, OutputArray, SeasonAndEpisode, x X
      EpisodeNumber = %OutputArray2%
      IfInString, EpisodeNumber, 0
      {
         StringGetPos, ZeroLoc, EpisodeNumber, 0
         If ZeroLoc = 0
            StringTrimLeft, EpisodeNumber, EpisodeNumber, 1
      }
   }
   Else If RegExMatch(FileName, "[0-9][0-9][0-9][0-9]?", SeasonAndEpisode)
   {
      StringRight, EpisodeNumber, SeasonAndEpisode, 2
      IfInString, EpisodeNumber, 0
      {
         StringGetPos, ZeroLoc, EpisodeNumber, 0
         If ZeroLoc = 0
            StringTrimLeft, EpisodeNumber, EpisodeNumber, 1
      }
   }
   Return EpisodeNumber
}

;Provide a show name (greek) and it will return the TVDB data for the show name (Greek) and series ID (80301) as a CSV (Greek,80301)
GetTVDBShows(ShowName)
{
   Global SeriesName, SeriesIDNum
   IfExist, Series_ID.xml
      FileDelete, Series_ID.xml
   UrlDownloadToFile, http://www.thetvdb.com/api/GetSeries.php?seriesname="%ShowName%", Series_ID.xml
   XPath_Load(xml, "Series_ID.xml")
   FileDelete, Series_ID.xml
   SeriesNameNodeCount := XPath(xml, "/Data/Series/SeriesName/Count()")
   If SeriesNameNodeCount = 1
   {
      SeriesIDNum := XPath(xml, "/Data/Series/seriesid/text()")
      SeriesName := XPath(xml, "/Data/Series/SeriesName/text()")
   }
   Else If SeriesNameNodeCount > 1
   {
      SeriesIDNum := XPath(xml, "/Data/Series/seriesid/text()")
      SeriesName := XPath(xml, "/Data/Series/SeriesName/text()")
      SeriesOverview := XPath(xml, "/Data/Series/Overview/text()")
      StringSplit, OutputArraySID, SeriesIDNum, `,
      StringSplit, OutputArraySN, SeriesName, `,
      StringSplit, OutputArraySO, SeriesOverview, `,
      Gui, 2: Default
      Gui, 2: +ToolWindow +Owner1
      Gui, 2: Add, ListView, xm r15 w600, Show name|Show description|TVDB series ID no.
      Gui, 2: Add, Text, y+7
      Gui, 2: Add, Button, x+475, Select
      Gui, 2: Add, Button, x+15, Cancel
      Loop, %SeriesNameNodeCount%
      {
         SeriesIDNum := OutputArraySID%A_Index%
         SeriesName := OutputArraySN%A_Index%
         SeriesOverview := OutputArraySO%A_Index%
         IfInString, SeriesOverview, ,`;
            StringReplace, SeriesOverview, SeriesOverview, ,`;, `,, All
         If not SeriesOverview
            SeriesOverview = (No show description provided)
         LV_Add(Row, SeriesName, SeriesOverview, SeriesIDNum)
         LV_ModifyCol()
         LV_ModifyCol(3, 110)
         SeriesIDNum =
         SeriesName =
         SeriesOverview =
      }
      Gui, 2: Show,,Which Show?
      Gui, 1: Default
      WinWaitClose, Which Show?
   }
   If not SeriesName
      SeriesName = %ShowName%
   J = %SeriesName%,%SeriesIDNum%
   ShowName =
   SeriesIDNum =
   SeriesName =
   SeriesOverview =
   Return J
}

   ;Labels required for Gui 2
   2GuiEscape:
   2GuiClose:
   2ButtonCancel:
   {
      Gui, 2: Destroy
      Return
   }
   2ButtonSelect:
   {
      FocusedRowNumber := LV_GetNext(0, "F")
      If not FocusedRowNumber
      {
         MsgBox, 0, Warning!, You must select a show or press cancel!
         Return
      }
      LV_GetText(SeriesName, FocusedRowNumber, 1)
      LV_GetText(SeriesIDNum, FocusedRowNumber, 3)
      FocusedRowNumber =
      Gui, 2: Destroy
      Return
   }

;Provide the "TVDB series ID", "season number" and "episode number" and this will return the TVDB season number, episode number, and episode title as a CSV (3,1,The Day After)
GetTVDBEpisodes(SeriesIDNum, SeasonNum, EpisodeNum, ShowName)
{
   GuiControlGet, CacheInfo,, Cache
   FileName = data/%ShowName%_%SeasonNum%x%EpisodeNum%.xml
   If CacheInfo = 1
   {
      IfNotExist, FileName
         UrlDownloadToFile, http://www.thetvdb.com/api/563E39CDC7F666DF/series/%SeriesIDNum%/default/%SeasonNum%/%EpisodeNum%/en.xml, %FileName%
      If not XPath_Load(xml, FileName)
         Msgbox, 48, [XPath]  , Load of %FileName% Failed!
   }
   Else
   {
      IfExist, Episode_Info.xml
         FileDelete, Episode_Info.xml
      UrlDownloadToFile, http://www.thetvdb.com/api/563E39CDC7F666DF/series/%SeriesIDNum%/default/%SeasonNum%/%EpisodeNum%/en.xml, Episode_Info.xml
      If not XPath_Load(xml, "Episode_Info.xml")
         Msgbox, 48, [XPath]  , Load of "Episode_Info.xml" Failed!
      FileDelete, Episode_Info.xml
   }
   SeasonNumber := XPath(xml, "/Data/Episode/SeasonNumber/text()")
   EpisodeNumber := XPath(xml, "/Data/Episode/EpisodeNumber/text()")
   EpisodeTitle := XPath(xml, "/Data/Episode/EpisodeName/text()")
   If not EpisodeTitle
   {
      EpisodeTitle := XPath(xml, "/html/head/title/text()")
      IfExist, %FileName%
         FileDelete, %FileName%
   }
   If not SeasonNumber
      SeasonNumber = %SeasonNum%
   If not EpisodeNumber
      EpisodeNumber = %EpisodeNum%
   If not EpisodeTitle
      EpisodeTitle = Not Found!
   K = %SeasonNumber%,%EpisodeNumber%,%EpisodeTitle%
   SeasonNumber =
   EpisodeNumber =
   EpisodeTitle =
   Return K
}

;Pads a variable with a preceeding zero
PadZero(VarToPad)
{
   VarToPadLen := StrLen(VarToPad)
   If VarToPadLen = 1
      VarToPad = 0%VarToPad%
   VarToPadLen =
   Return VarToPad
}

/*
>>>>CHANGELOG<<<<

1.0 (10-5-2009)
   - Original script
1.1 (10-6-2009)
   - Fixed a bug with adding a single file where the file would not be renamed
   -- Forgot to define the TargetFile's TargetFolder when updating the GUI
1.2 (10-13-2009)
   - Fixed another bug with adding a single file where the file would not be renamed
   - Fixed a bug with parsing the series overview where the non-comma delimiter (,) would be displayed
   -- Titans XPath replaces commas with "," (no quotes)
1.30 (11-8-2009)
   - Added a new method of selecting a show name when multiple results are returned
   -- Secondary ListView gui is displayed allowing the user to select the correct show
   - Script now compares the current filename against the previous filename (filenames converted to UPPERCASE)
   -- Drasitically reduces the number of requests against the TVDB and speeds everything up when renaming multiple shows all with the same name
   - Added a check and replace system for invalid filename characters
   -- StringReplace these chars \ / : * ? "" < > | with descriptive replacements
   - Fixed a bug in the GetEpisodeNumber() function
   -- A single digit season number would sometimes cause too few of the episode numbers to be returned when SeasonAndEpisode contained (e|x)
   - Tweaked GetSeasonNumber() and GetEpisodeNumber() to more reliably return correct data
   -- StringGetPos and String(Left|Right) were swapped for StringSplit to more predictably split SeasonAndEpisode regardless of (e|x) char location
   - Added a check to make sure files have a new filename in the preview column before renaming
   - Added a static window title which may be needed for various features in the future as well as making things look nicer :P
1.40 (11-15-2009)
   - Added status bar
   - Fixed a bug where a file would not have a preceeding zero added if no info was found on TheTVDB by adding PadZero() function
   -- Preceeding zero was only added in GetTVDBEpisodes() which means that if SeriesIDNo was blank (i.e. no info pulled from TheTVDB) the Season and Episode number would not get padded
1.41 (12-10-2009)
   - Fixed a serious bug where no results would be returned for ShowName inside the GetTVDBShows function would return the first result infinitely
   -- Had to clear the SeriesName var at the end of the function so that on the next loop iteration the correct var contents would exist
1.42 (12-11-2009)
   - Fixed a minor bug where the second time the GetTVDBInfo button was pressed, the first item in the list view would not actually be rescanned
   -- Had to clear the UpperPrevSN and PrevShowName vars so that the second time the button was pressed it would compare the correct names

>>>>Paradox Changelog<<<<

1.42.1 (2-5-2010)
   - Added new checkbox and supporting code that allows you to save the xmls downloaded in data/%ShowName%_%SeasonNum%x%EpisodeNum%.xml to make future renames quicker.
   -- Added check that determines if you are connected to the internet and thetvdb.com is reachable
   - Added better handling for previous showname
   -- Clean up some code that caused shows to use the previous renamed file settings wrongly
   - Renamed GetShowName(FileName) to GetName(FileName) and added new GetShowName(FileName, FileDir) to implement the following feature without requiring big changes to existing scripts.
   -- Added GetNameFromDir(FileName, Directory) to handle using the directory name as the showname, in case you are renaming files named 01x01 - title.avi the directory must, of course, be named as the show name.
   - Added debug message box if the episode info xml can't be read for some reason.
   -- Fixed Bug where first file would be properly renamed "Castle [2009] - 01x01 - Title" and the rest would be improperly renamed Castle - 01x02 - Title"
   - I am planning to add more features including using the API properly to download All the Episode information for a show and cache it locally/update on a regular basis.
   -- Also Planning to add a feature that will recognize when you are missing episodes from a season and either create a .txt file with the show name, season, episode, and title in the directory, or, keep track of it in a log file of some sort.
*/


I didn't modify anything in xpath.ahk so, I didn't include it in this post.

Paradox
  • Members
  • 24 posts
  • Last active: Mar 05 2013 04:15 PM
  • Joined: 05 Feb 2010
1.42.2
See the changelog at the bottom of the file for changes.
; SceneRenamer by strictlyfocused02
; Modified By Paradox iamparadox at netscape.net
; AutoHotkey Version: 1.0.48+
;
; Script Function:
;   Extracts season and episode info from the filename
;   and uses that to retreive info from TheTVDB.com to rename
;   the file to a user-specified format

;   Special thanks to TheTVDB.com
;   This project would not have been possible without their top-notch API

#Include xpath.ahk

#NoEnv
SendMode, Input
SetWorkingDir, %A_ScriptDir%

WindowTitle = SceneRenamer v1.42.2 Modified By Paradox

Gui, Add, Button, Default gButtonAddFolder, &Add folder
Gui, Add, Button, x+20 gButtonAddFile, &Add file
Gui, Add, Button, x+20 gButtonClear, &Clear list
Gui, Add, Text, x+150 w50, Status:
Gui, Add, Edit, +ReadOnly x+0 w400, Waiting for user to add file(s)...

Gui, Add, ListView, xm r26 w800 -ReadOnly vMyListView, Name|Preview|Directory|Extension|TVDB Series ID No

Gui, Add, DropDownList, w250 AltSubmit vNameScheme, (Show Title) - (SS)x(EE) - (Episode Title)|(Show Title) - S(SS)E(EE) - (Episode Title)|(SS)x(EE) - Episode Title||S(SS)E(EE) - (Episode Title)
Gui, Add, DropDownList, x+10 w180 AltSubmit vSeparator, Use spaces as separators|Use.periods.as.separators||Use_underscores_as_separators
Gui, Add, Button, x+150 gButtonGetTVDBInfo, &Get TVDB Info
Gui, Add, Button, x+10 gButtonRename, &Rename files

Gui, Add, Checkbox, xm Checked vZero, Pad with zero?
Gui, Add, Checkbox, x+10 Checked vCache, Cache Episode Info?
Gui, Add, Checkbox, x+10 vRename, Allow Direct Rename?
Gui, Add, Checkbox, x+10 Checked vClear, Clear List after Rename?

Menu, MyContextMenu, Add, Open, ContextOpenFile
Menu, MyContextMenu, Add, Properties, ContextProperties
Menu, MyContextMenu, Add, Remove item, ContextRemoveItem

Gui, Show,, %WindowTitle%
Return

GuiClose:
   ExitApp

GuiContextMenu:
   If A_GuiControl <> MyListView
       Return
   Menu, MyContextMenu, Show, %A_GuiX%, %A_GuiY%
   Return

ContextOpenFile:
ContextProperties:
   FocusedRowNumber := LV_GetNext(0, "F")
   If not FocusedRowNumber
      return
   LV_GetText(FileName, FocusedRowNumber, 1)
   LV_GetText(FileDir, FocusedRowNumber, 3)
   IfInString A_ThisMenuItem, Open
      Run %FileDir%\%FileName%,, UseErrorLevel
   Else
      Run Properties "%FileDir%\%FileName%",, UseErrorLevel
   If ErrorLevel
      MsgBox Could not perform requested action on "%FileDir%\%FileName%".
   return

ContextRemoveItem:
   RowNumber = 0
   Loop
   {
      RowNumber := LV_GetNext(RowNumber - 1)
      If not RowNumber
           Break
      LV_Delete(RowNumber)
   }
   Return

ButtonAddFolder:
   Gui +OwnDialogs
   FileSelectFolder, TargetFolder,, 3, Select a folder:
   If not TargetFolder  ; The user pressed cancel
       Return
   StringRight, LastChar, TargetFolder, 1
   If LastChar = \
      StringTrimRight, TargetFolder, TargetFolder, 1
   GuiControl, -Redraw, MyListView ; Improves performance by disabling redrawing
   Loop %TargetFolder%\*.*
   {
      FileName := A_LoopFileFullPath
      SplitPath, FileName,,, FileExt  ; Get the file extension
      If FileExt in avi,mkv,mp4
         LV_Add(Row, A_LoopFileName, "", A_LoopFileDir, FileExt)
   }
   GuiControl, +Redraw, MyListView  ; Turn redrawing back on
   LV_ModifyCol()  ; Resize each column to fit
   LV_ModifyCol(2, 60)  ; Expand "Preview" to keep the header visible
   LV_ModifyCol(4, 60)  ; Expand "Extension" to keep the header visible
   LV_ModifyCol(5, 110)  ; Expand "TVDB Series ID No" to keep the header visible
   ControlSetText, Edit1, Added folder %TargetFolder%, %WindowTitle%
   Return

ButtonAddFile:
   Gui +OwnDialogs
   FileSelectFile, TargetFile
   If not TargetFile
      Return
   SplitPath, TargetFile,,, FileExt  ; Get the file extension
   If FileExt in avi,mkv,mp4
   {
      SplitPath, TargetFile, FileName, TargetFolder
      LV_Add(Row, FileName, "", TargetFolder, FileExt)
      LV_ModifyCol()  ; Resize each column to fit
      LV_ModifyCol(2, 60)  ; Expand "Preview" to keep the header visible
      LV_ModifyCol(4, 60)  ; Expand "Extension" to keep the header visible
      LV_ModifyCol(5, 110)  ; Expand "TVDB Series ID No" to keep the header visible
      ControlSetText, Edit1, Added file %TargetFile%..., %WindowTitle%
   }
   Return

ButtonClear:
   ClearList()
   Return

ClearList()
{
   TargetFolder =
   TargetFile =
   LV_Delete()
   ControlSetText, Edit1, Cleared Listview, %WindowTitle%
   Return
}

InternetCheckConnection(Url="",FIFC=1) {
   Return DllCall("Wininet.dll\InternetCheckConnectionA", Str,Url, Int,FIFC, Int,0)
}

ButtonGetTVDBInfo:
   GetTVDBInfo()
   Return

GetTVDBInfo()
{
   LV_GetText(LVFileName, 1, 1)
   If not LVFileName
   {
      Gui +OwnDialogs
      MsgBox, 0,Fatal Error!, You must select a file or folder before connecting to TheTVDB.com!
      Return
   }
   LV_GetText(LVFileDir, 1, 3)  ; Get the file directory
   LV_GetText(LVFileExt, 1, 4)  ; Get the file extension

   URL := "http://www.thetvdb.com"

   If not InternetCheckConnection(URL)
   {
      Msgbox, 48, [%URL%]  , Connection Failed!
      Return
   }

   RowNumber = 1
   ShowInfo := GetTVDBShows(GetShowName(LVFileName, LVFileDir))
   StringSplit, ShowArray, ShowInfo, `,
   ShowName = %ShowArray1%
   SeriesIDNo = %ShowArray2%
   Loop
   {
      Gui +OwnDialogs
      If A_Index > 1
      {
         LV_GetText(LVPrevFN, RowNumber - 1, 1)  ; Get the preceeding rows filename
         LV_GetText(LVPrevFD, RowNumber - 1, 3)  ; Get the preceeding rows file directory
         PrevShowName := GetShowName(LVPrevFN, LVPrevFD)
         StringUpper, UpperPrevSN, PrevShowName

         NewShowName := GetShowName(LVFileName, LVFileDir)
         StringUpper, UpperCurrSN, NewShowName
         If UpperCurrSN <> %UpperPrevSN%
         {
            ShowInfo := GetTVDBShows(NewShowName)
            StringSplit, ShowArray, ShowInfo, `,
            ShowName = %ShowArray1%
            SeriesIDNo = %ShowArray2%
         }
      }
      UpperPrevSN =
      SeasonNumber := GetSeasonNumber(LVFileName)
      EpisodeNumber := GetEpisodeNumber(LVFileName)
      ControlSetText, Edit1, Processing "%ShowName%" Season "%SeasonNumber%" Episode "%EpisodeNumber%", %WindowTitle%
      If SeriesIDNo
      {
         IfInString, ShowName, %A_Space%
            StringReplace, SafeShowName, ShowName, %A_Space%, _, All
         Else
            SafeShowName = %ShowName%
         EpisodeInfo := GetTVDBEpisodes(SeriesIDNo, SeasonNumber, EpisodeNumber, SafeShowName)
         StringSplit, OutputArray, EpisodeInfo, `,
         SeasonNumber = %OutputArray1%
         EpisodeNumber = %OutputArray2%
         EpisodeTitle = %OutputArray3%
         If EpisodeTitle
         {
            StringReplace, EpisodeTitle, EpisodeTitle, \, %A_Space%~%A_Space%, All
            StringReplace, EpisodeTitle, EpisodeTitle, /, %A_Space%~%A_Space%, All
            StringReplace, EpisodeTitle, EpisodeTitle, :, %A_Space%~%A_Space%, All
            StringReplace, EpisodeTitle, EpisodeTitle, *, %A_Space%~%A_Space%, All
            StringReplace, EpisodeTitle, EpisodeTitle, ?,, All
            StringReplace, EpisodeTitle, EpisodeTitle, ", ', All
            StringReplace, EpisodeTitle, EpisodeTitle, <, %A_Space%less than%A_Space%, All
            StringReplace, EpisodeTitle, EpisodeTitle, >, %A_Space%greater than%A_Space%, All
            StringReplace, EpisodeTitle, EpisodeTitle, |, %A_Space%~%A_Space%, All
            StringReplace, EpisodeTitle, EpisodeTitle, &`#44;, `,, All
            StringReplace, EpisodeTitle, EpisodeTitle, &, &, All
         }
      }
      GuiControlGet, PadZero,, Zero
      If PadZero = 1
      {
         SeasonNumber := PadZero(SeasonNumber)
         EpisodeNumber := PadZero(EpisodeNumber)
      }
      GuiControlGet, NamingScheme,, NameScheme
      If NamingScheme = 1
      {
         If EpisodeTitle
            NewFileName = %ShowName% - %SeasonNumber%x%EpisodeNumber% - %EpisodeTitle%
         Else
            NewFileName = %ShowName% - %SeasonNumber%x%EpisodeNumber%
      }
      Else if NamingScheme = 2
      {
         If EpisodeTitle
            NewFileName = %ShowName% - S%SeasonNumber%E%EpisodeNumber% - %EpisodeTitle%
         Else
            NewFileName = %ShowName% - S%SeasonNumber%E%EpisodeNumber%
      }
      Else If NamingScheme = 3
      {
         If EpisodeTitle
            NewFileName = %SeasonNumber%x%EpisodeNumber% - %EpisodeTitle%
         Else
            NewFileName = %SeasonNumber%x%EpisodeNumber%
      }
      Else If NamingScheme = 4
      {
         If EpisodeTitle
            NewFileName = S%SeasonNumber%E%EpisodeNumber% - %EpisodeTitle%
         Else
            NewFileName = S%SeasonNumber%E%EpisodeNumber%
      }
      GuiControlGet, Sep,, Separator
      If Sep = 2
      {
         StringReplace, NewFileName, NewFileName, %A_Space%, ., All
      }
      Else If Sep = 3
      {
         StringReplace, NewFileName, NewFileName, %A_Space%, _, All
      }
      NewFileName = %NewFileName%.%LVFileExt%
      LV_Modify(RowNumber, Col1, LVFileName, NewFileName, LVFileDir, LVFileExt, SeriesIDNo)
      LV_ModifyCol()
      LV_ModifyCol(4, 60)
      LV_ModifyCol(5, 110)  ; Expand "TVDB Series ID No" to keep the header visible
      LVFileName =
      LVPrevFN =
      ShowArray1 =
      OutputArray1 =
      OutputArray2 =
      OutputArray3 =
      SeasonNumber =
      EpisodeNumber =
      EpisodeTitle =
      RowNumber := RowNumber + 1
      LV_GetText(LVFileName, RowNumber, 1)  ; Get the filename
      If not LVFileName  ; Break the loop at the end of the list
         Break
      LV_GetText(LVFileDir, RowNumber, 3)  ; Get the file directory
      LV_GetText(LVFileExt, RowNumber, 4)  ; Get the file extension
   }
   ControlSetText, Edit1, Finished querying TheTVDB.com. Ready to rename..., %WindowTitle%
   Return
}

ButtonRename:
   LV_GetText(LVNewFileName, 1, 2)
   If not LVNewFileName
   {
      GuiControlGet, DirectRename,, Rename
      If DirectRename = 1
      {
         GetTVDBInfo()
      }
      Else
      {
         Gui +OwnDialogs
         MsgBox, 0,Fatal Error!, You must scan your files against TheTVDB.com before you rename them!
         Return
      }
   }
   Loop
   {
      RowNumber = %A_Index%
      LV_GetText(LVFileName, RowNumber, 1)  ; Get the original filename
      LV_GetText(LVNewFileName, RowNumber, 2)  ; Get the new filename
      LV_GetText(LVFileDir, RowNumber, 3)  ; Get the file dir
      LV_GetText(LVFileExt, RowNumber, 4)  ; Get the file extension
      If not LVNewFileName  ; Break the loop at the end of the list
         Break
      ControlSetText, Edit1, Renaming "%LVFileName%" to "%LVNewFileName%", %WindowTitle%
      FileMove, %LVFileDir%\%LVFileName%, %LVFileDir%\%LVNewFileName%  ; Finally, rename it
      LV_Add(Row, LVNewFileName, "", LVFileDir, LVFileExt)
   }
   RenameCount := RowNumber - 1
   Loop %RenameCount%
   {
      ControlSetText, Edit1, Cleaning up..., %WindowTitle%
      RowNumber := RowNumber - 1
      LV_GetText(LVFileName, RowNumber, 1)  ; Get the original filename
      LV_GetText(LVNewFileName, RowNumber, 2)  ; Get the new filename
      LV_GetText(LVFileDir, RowNumber, 3)  ; Get the file dir
      LV_GetText(LVFileExt, RowNumber, 4)  ; Get the file extension
      If LVNewFileName  ; Clean up the list
         LV_Delete(1)
      Else
         Break

   }
   ControlSetText, Edit1, Finished renaming files! Refreshing file list., %WindowTitle%
   GuiControlGet, ClearIt,, Clear
   If ClearIt = 1
   {
      ClearList()
   }
   Else
   {
      GuiControl, +Redraw, MyListView  ; Turn redrawing back on
      LV_ModifyCol()  ; Resize each column to fit
      LV_ModifyCol(2, 60)  ; Expand "Preview" to keep the header visible
      LV_ModifyCol(4, 60)  ; Expand "Extension" to keep the header visible
      LV_ModifyCol(5, 110)  ; Expand "TVDB Series ID No" to keep the header visible
   }
   ControlSetText, Edit1, Finished Successfully!, %WindowTitle%
   Return

;Provide a filename (s01e01.avi or greek.s01e01.avi) and Directory name (C:\TV\greek) and this should return the show name
GetShowName(FileName, FileDir)
{
   TempName := GetName(FileName)
   If not TempName
      TempName := GetNameFromDir(FileName, FileDir)
   Return TempName
}
;Provide a filename (greek.s01e01.avi) and this should return the show name
GetName(FileName)
{
   IfInString, FileName, .
      StringReplace, NormalName, FileName, ., %A_Space%, All
   IfInString, NormalName, _
      StringReplace, NormalName, NormalName, _, %A_Space%, All
   If RegExMatch(NormalName, "i)s[0-9][0-9]? ?e[0-9][0-9]?", SeasonAndEpisode)
   {
      StringGetPos, SeasonAndEpisodePos, NormalName, %SeasonAndEpisode%
      StringLeft, ShowName, NormalName, (SeasonAndEpisodePos - 1)
   }
   Else If RegExMatch(NormalName, "i)[0-9][0-9]?x[0-9][0-9]?", SeasonAndEpisode)
   {
      StringGetPos, SeasonAndEpisodePos, NormalName, %SeasonAndEpisode%
      StringLeft, ShowName, NormalName, (SeasonAndEpisodePos - 1)
   }
   Else If RegExMatch(NormalName, "[0-9][0-9][0-9][0-9]?", SeasonAndEpisode)
   {
      StringGetPos, SeasonAndEpisodePos, NormalName, %SeasonAndEpisode%
      StringLeft, ShowName, NormalName, (SeasonAndEpisodePos - 1)
   }
   Loop
   {
      StringRight, LastChar, ShowName, 1
      If (LastChar = "-" or LastChar = " ")
         StringTrimRight, ShowName, ShowName, 1
      Else
         Break
   }
   Return ShowName
}

;Provide a filename (s01e01.avi) and Directory name (C:\TV\greek) and this should return the show name
GetNameFromDir(FileName, FileDir)
{
   Directory = %FileDir% - %FileName%
   SplitPath , Directory, NewFileName, dir, ext, name
   Return GetName(NewFileName)
}

;Provide a filename (greek.s01e01.avi) and this should return the season number
GetSeasonNumber(FileName)
{
   If RegExMatch(FileName, "i)s\K[0-9][0-9]?.?e[0-9][0-9]?", SeasonAndEpisode)
   {
      StringSplit, OutputArray, SeasonAndEpisode, e E, .
      SeasonNumber = %OutputArray1%
      IfInString, SeasonNumber, 0
      {
         StringGetPos, ZeroLoc, SeasonNumber, 0
         If ZeroLoc = 0
            StringTrimLeft, SeasonNumber, SeasonNumber, 1
      }

   }
   Else If RegExMatch(FileName, "i)[0-9][0-9]?x[0-9][0-9]?", SeasonAndEpisode)
   {
      StringSplit, OutputArray, SeasonAndEpisode, x X
      SeasonNumber = %OutputArray1%
      IfInString, SeasonNumber, 0
      {
         StringGetPos, ZeroLoc, SeasonNumber, 0
         If ZeroLoc = 0
            StringTrimLeft, SeasonNumber, SeasonNumber, 1
      }
   }
   Else If RegExMatch(FileName, "[0-9][0-9][0-9][0-9]?", SeasonAndEpisode)
   {
      StringTrimRight, SeasonNumber, SeasonAndEpisode, 2
      IfInString, SeasonNumber, 0
      {
         StringGetPos, ZeroLoc, SeasonNumber, 0
         If ZeroLoc = 0
            StringTrimLeft, SeasonNumber, SeasonNumber, 1
      }
   }
   Return SeasonNumber
}

;Provide a filename (greek.s01e01.avi) and this should return the episode number
GetEpisodeNumber(FileName)
{
   If RegExMatch(FileName, "i)s\K[0-9][0-9]?.?e[0-9][0-9]?", SeasonAndEpisode)
   {
      StringSplit, OutputArray, SeasonAndEpisode, e E, .
      EpisodeNumber = %OutputArray2%
      IfInString, EpisodeNumber, 0
      {
         StringGetPos, ZeroLoc, EpisodeNumber, 0
         If ZeroLoc = 0
            StringTrimLeft, EpisodeNumber, EpisodeNumber, 1
      }
   }
   Else If RegExMatch(FileName, "i)[0-9][0-9]?.?x[0-9][0-9]?", SeasonAndEpisode)
   {
      StringSplit, OutputArray, SeasonAndEpisode, x X
      EpisodeNumber = %OutputArray2%
      IfInString, EpisodeNumber, 0
      {
         StringGetPos, ZeroLoc, EpisodeNumber, 0
         If ZeroLoc = 0
            StringTrimLeft, EpisodeNumber, EpisodeNumber, 1
      }
   }
   Else If RegExMatch(FileName, "[0-9][0-9][0-9][0-9]?", SeasonAndEpisode)
   {
      StringRight, EpisodeNumber, SeasonAndEpisode, 2
      IfInString, EpisodeNumber, 0
      {
         StringGetPos, ZeroLoc, EpisodeNumber, 0
         If ZeroLoc = 0
            StringTrimLeft, EpisodeNumber, EpisodeNumber, 1
      }
   }
   Return EpisodeNumber
}

;Provide a show name (greek) and it will return the TVDB data for the show name (Greek) and series ID (80301) as a CSV (Greek,80301)
GetTVDBShows(ShowName)
{
   Global SeriesName, SeriesIDNum
   IfExist, Series_ID.xml
      FileDelete, Series_ID.xml
   UrlDownloadToFile, http://www.thetvdb.com/api/GetSeries.php?seriesname="%ShowName%", Series_ID.xml
   XPath_Load(xml, "Series_ID.xml")
   FileDelete, Series_ID.xml
   SeriesNameNodeCount := XPath(xml, "/Data/Series/SeriesName/Count()")
   If SeriesNameNodeCount = 1
   {
      SeriesIDNum := XPath(xml, "/Data/Series/seriesid/text()")
      SeriesName := XPath(xml, "/Data/Series/SeriesName/text()")
   }
   Else If SeriesNameNodeCount > 1
   {
      SeriesIDNum := XPath(xml, "/Data/Series/seriesid/text()")
      SeriesName := XPath(xml, "/Data/Series/SeriesName/text()")
      SeriesOverview := XPath(xml, "/Data/Series/Overview/text()")
      StringSplit, OutputArraySID, SeriesIDNum, `,
      StringSplit, OutputArraySN, SeriesName, `,
      StringSplit, OutputArraySO, SeriesOverview, `,
      Gui, 2: Default
      Gui, 2: +ToolWindow +Owner1
      Gui, 2: Add, ListView, xm r15 w600, Show name|Show description|TVDB series ID no.
      Gui, 2: Add, Text, y+7
      Gui, 2: Add, Button, x+475, Select
      Gui, 2: Add, Button, x+15, Cancel
      Loop, %SeriesNameNodeCount%
      {
         SeriesIDNum := OutputArraySID%A_Index%
         SeriesName := OutputArraySN%A_Index%
         SeriesOverview := OutputArraySO%A_Index%
         IfInString, SeriesOverview, ,`;
            StringReplace, SeriesOverview, SeriesOverview, ,`;, `,, All
         If not SeriesOverview
            SeriesOverview = (No show description provided)
         LV_Add(Row, SeriesName, SeriesOverview, SeriesIDNum)
         LV_ModifyCol()
         LV_ModifyCol(3, 110)
         SeriesIDNum =
         SeriesName =
         SeriesOverview =
      }
      Gui, 2: Show,,Which Show?
      Gui, 1: Default
      WinWaitClose, Which Show?
   }
   If not SeriesName
      SeriesName = %ShowName%
   J = %SeriesName%,%SeriesIDNum%
   ShowName =
   SeriesIDNum =
   SeriesName =
   SeriesOverview =
   Return J
}

   ;Labels required for Gui 2
   2GuiEscape:
   2GuiClose:
   2ButtonCancel:
   {
      Gui, 2: Destroy
      Return
   }
   2ButtonSelect:
   {
      FocusedRowNumber := LV_GetNext(0, "F")
      If not FocusedRowNumber
      {
         MsgBox, 0, Warning!, You must select a show or press cancel!
         Return
      }
      LV_GetText(SeriesName, FocusedRowNumber, 1)
      LV_GetText(SeriesIDNum, FocusedRowNumber, 3)
      FocusedRowNumber =
      Gui, 2: Destroy
      Return
   }

;Provide the "TVDB series ID", "season number" and "episode number" and this will return the TVDB season number, episode number, and episode title as a CSV (3,1,The Day After)
GetTVDBEpisodes(SeriesIDNum, SeasonNum, EpisodeNum, ShowName)
{
   GuiControlGet, CacheInfo,, Cache
   FileName = data/%ShowName%_%SeasonNum%x%EpisodeNum%.xml
   If CacheInfo = 1
   {
      IfNotExist, FileName
         UrlDownloadToFile, http://www.thetvdb.com/api/563E39CDC7F666DF/series/%SeriesIDNum%/default/%SeasonNum%/%EpisodeNum%/en.xml, %FileName%
      If not XPath_Load(xml, FileName)
         Msgbox, 48, [XPath]  , Load of %FileName% Failed!
   }
   Else
   {
      IfExist, Episode_Info.xml
         FileDelete, Episode_Info.xml
      UrlDownloadToFile, http://www.thetvdb.com/api/563E39CDC7F666DF/series/%SeriesIDNum%/default/%SeasonNum%/%EpisodeNum%/en.xml, Episode_Info.xml
      If not XPath_Load(xml, "Episode_Info.xml")
         Msgbox, 48, [XPath]  , Load of "Episode_Info.xml" Failed!
      FileDelete, Episode_Info.xml
   }
   SeasonNumber := XPath(xml, "/Data/Episode/SeasonNumber/text()")
   EpisodeNumber := XPath(xml, "/Data/Episode/EpisodeNumber/text()")
   EpisodeTitle := XPath(xml, "/Data/Episode/EpisodeName/text()")
   If not EpisodeTitle
   {
      EpisodeTitle := XPath(xml, "/html/head/title/text()")
      IfExist, %FileName%
         FileDelete, %FileName%
   }
   If not SeasonNumber
      SeasonNumber = %SeasonNum%
   If not EpisodeNumber
      EpisodeNumber = %EpisodeNum%
   If not EpisodeTitle
      EpisodeTitle = Not Found!
   K = %SeasonNumber%,%EpisodeNumber%,%EpisodeTitle%
   SeasonNumber =
   EpisodeNumber =
   EpisodeTitle =
   Return K
}

;Pads a variable with a preceeding zero
PadZero(VarToPad)
{
   VarToPadLen := StrLen(VarToPad)
   If VarToPadLen = 1
      VarToPad = 0%VarToPad%
   VarToPadLen =
   Return VarToPad
}

/*
>>>>CHANGELOG<<<<

1.0 (10-5-2009)
   - Original script
1.1 (10-6-2009)
   - Fixed a bug with adding a single file where the file would not be renamed
   -- Forgot to define the TargetFile's TargetFolder when updating the GUI
1.2 (10-13-2009)
   - Fixed another bug with adding a single file where the file would not be renamed
   - Fixed a bug with parsing the series overview where the non-comma delimiter (,) would be displayed
   -- Titans XPath replaces commas with "," (no quotes)
1.30 (11-8-2009)
   - Added a new method of selecting a show name when multiple results are returned
   -- Secondary ListView gui is displayed allowing the user to select the correct show
   - Script now compares the current filename against the previous filename (filenames converted to UPPERCASE)
   -- Drasitically reduces the number of requests against the TVDB and speeds everything up when renaming multiple shows all with the same name
   - Added a check and replace system for invalid filename characters
   -- StringReplace these chars \ / : * ? "" < > | with descriptive replacements
   - Fixed a bug in the GetEpisodeNumber() function
   -- A single digit season number would sometimes cause too few of the episode numbers to be returned when SeasonAndEpisode contained (e|x)
   - Tweaked GetSeasonNumber() and GetEpisodeNumber() to more reliably return correct data
   -- StringGetPos and String(Left|Right) were swapped for StringSplit to more predictably split SeasonAndEpisode regardless of (e|x) char location
   - Added a check to make sure files have a new filename in the preview column before renaming
   - Added a static window title which may be needed for various features in the future as well as making things look nicer :P
1.40 (11-15-2009)
   - Added status bar
   - Fixed a bug where a file would not have a preceeding zero added if no info was found on TheTVDB by adding PadZero() function
   -- Preceeding zero was only added in GetTVDBEpisodes() which means that if SeriesIDNo was blank (i.e. no info pulled from TheTVDB) the Season and Episode number would not get padded
1.41 (12-10-2009)
   - Fixed a serious bug where no results would be returned for ShowName inside the GetTVDBShows function would return the first result infinitely
   -- Had to clear the SeriesName var at the end of the function so that on the next loop iteration the correct var contents would exist
1.42 (12-11-2009)
   - Fixed a minor bug where the second time the GetTVDBInfo button was pressed, the first item in the list view would not actually be rescanned
   -- Had to clear the UpperPrevSN and PrevShowName vars so that the second time the button was pressed it would compare the correct names

>>>>Paradox Changelog<<<<

1.42.1 (2-5-2010)
   - Added new checkbox and supporting code that allows you to save the xmls downloaded in data/%ShowName%_%SeasonNum%x%EpisodeNum%.xml to make future renames quicker.
   -- Added check that determines if you are connected to the internet and thetvdb.com is reachable
   - Added better handling for previous showname
   -- Clean up some code that caused shows to use the previous renamed file settings wrongly
   - Renamed GetShowName(FileName) to GetName(FileName) and added new GetShowName(FileName, FileDir) to implement the following feature without requiring big changes to existing scripts.
   -- Added GetNameFromDir(FileName, Directory) to handle using the directory name as the showname, in case you are renaming files named 01x01 - title.avi the directory must, of course, be named as the show name.
   - Added debug message box if the episode info xml can't be read for some reason.
   -- Fixed Bug where first file would be properly renamed "Castle [2009] - 01x01 - Title" and the rest would be improperly renamed Castle - 01x02 - Title"
   - I am planning to add more features including using the API properly to download All the Episode information for a show and cache it locally/update on a regular basis.
   -- Also Planning to add a feature that will recognize when you are missing episodes from a season and either create a .txt file with the show name, season, episode, and title in the directory, or, keep track of it in a log file of some sort.
1.42.2 (2-5-2010)
   - Added support for choosing if you want to use spaces, periods or underscores as separators
   -- Added A checkbox that allows you to clear the list after renaming, so you don't have to click the button :)
   - Moved some things on the interface around a bit to accommodate previous features.
   -- Fixed an error where the list of files in the directory were being displayed after renaming instead of the previous items, renamed.
   - Added an option that allows you to click on rename and have it do the TVDB lookup and rename all in one (Be careful with this option)
   -- Fix up a few other small bugs
*/


Paradox
  • Members
  • 24 posts
  • Last active: Mar 05 2013 04:15 PM
  • Joined: 05 Feb 2010
1.42.3

; SceneRenamer by strictlyfocused02
; Modified By Paradox iamparadox at netscape.net
; AutoHotkey Version: 1.0.48+
;
; Script Function:
;   Extracts season and episode info from the filename
;   and uses that to retreive info from TheTVDB.com to rename
;   the file to a user-specified format

;   Special thanks to TheTVDB.com
;   This project would not have been possible without their top-notch API

#Include xpath.ahk

#NoEnv
SendMode, Input
SetWorkingDir, %A_ScriptDir%

WindowTitle = SceneRenamer v1.42.3 Modified By Paradox

Gui, Add, Button, Default gButtonAddFolder, &Add folder
Gui, Add, Button, x+20 gButtonAddFile, &Add file
Gui, Add, Button, x+20 gButtonClear, &Clear list
Gui, Add, Text, x+150 w50, Status:
Gui, Add, Edit, +ReadOnly x+0 w400, Waiting for user to add file(s)...

Gui, Add, ListView, xm r26 w800 -ReadOnly vMyListView, Name|Preview|Directory|Extension|TVDB Series ID No

Gui, Add, DropDownList, w250 AltSubmit vNameScheme, (Show Title) - (SS)x(EE) - (Episode Title)|(Show Title) - S(SS)E(EE) - (Episode Title)|(SS)x(EE) - Episode Title||S(SS)E(EE) - (Episode Title)
Gui, Add, DropDownList, x+10 w180 AltSubmit vSeparator, Use spaces as separators|Use.periods.as.separators||Use_underscores_as_separators
Gui, Add, Button, x+150 gButtonGetTVDBInfo, &Get TVDB Info
Gui, Add, Button, x+10 gButtonRename, &Rename files

Gui, Add, Checkbox, xm Checked vZero, Pad with zero?
Gui, Add, Checkbox, x+10 Checked vCache, Cache Episode Info?
Gui, Add, Checkbox, x+10 vRename, Allow Direct Rename?
Gui, Add, Checkbox, x+10 Checked vClear, Clear List after Rename?

Menu, MyContextMenu, Add, Open, ContextOpenFile
Menu, MyContextMenu, Add, Properties, ContextProperties
Menu, MyContextMenu, Add, Remove item, ContextRemoveItem

Gui, Show,, %WindowTitle%
Return

GuiClose:
   ExitApp

GuiContextMenu:
   If A_GuiControl <> MyListView
       Return
   Menu, MyContextMenu, Show, %A_GuiX%, %A_GuiY%
   Return

ContextOpenFile:
ContextProperties:
   FocusedRowNumber := LV_GetNext(0, "F")
   If not FocusedRowNumber
      return
   LV_GetText(FileName, FocusedRowNumber, 1)
   LV_GetText(FileDir, FocusedRowNumber, 3)
   IfInString A_ThisMenuItem, Open
      Run %FileDir%\%FileName%,, UseErrorLevel
   Else
      Run Properties "%FileDir%\%FileName%",, UseErrorLevel
   If ErrorLevel
      MsgBox Could not perform requested action on "%FileDir%\%FileName%".
   return

ContextRemoveItem:
   RowNumber = 0
   Loop
   {
      RowNumber := LV_GetNext(RowNumber - 1)
      If not RowNumber
           Break
      LV_Delete(RowNumber)
   }
   Return

ButtonAddFolder:
   Gui +OwnDialogs
   FileSelectFolder, TargetFolder,, 3, Select a folder:
   If not TargetFolder  ; The user pressed cancel
       Return
   StringRight, LastChar, TargetFolder, 1
   If LastChar = \
      StringTrimRight, TargetFolder, TargetFolder, 1
   GuiControl, -Redraw, MyListView ; Improves performance by disabling redrawing
   Loop %TargetFolder%\*.*
   {
      FileName := A_LoopFileFullPath
      SplitPath, FileName,,, FileExt  ; Get the file extension
      If FileExt in avi,mkv,mp4
         LV_Add(Row, A_LoopFileName, "", A_LoopFileDir, FileExt)
   }
   GuiControl, +Redraw, MyListView  ; Turn redrawing back on
   LV_ModifyCol()  ; Resize each column to fit
   LV_ModifyCol(2, 60)  ; Expand "Preview" to keep the header visible
   LV_ModifyCol(4, 60)  ; Expand "Extension" to keep the header visible
   LV_ModifyCol(5, 110)  ; Expand "TVDB Series ID No" to keep the header visible
   ControlSetText, Edit1, Added folder %TargetFolder%, %WindowTitle%
   Return

ButtonAddFile:
   Gui +OwnDialogs
   FileSelectFile, TargetFile
   If not TargetFile
      Return
   SplitPath, TargetFile,,, FileExt  ; Get the file extension
   If FileExt in avi,mkv,mp4
   {
      SplitPath, TargetFile, FileName, TargetFolder
      LV_Add(Row, FileName, "", TargetFolder, FileExt)
      LV_ModifyCol()  ; Resize each column to fit
      LV_ModifyCol(2, 60)  ; Expand "Preview" to keep the header visible
      LV_ModifyCol(4, 60)  ; Expand "Extension" to keep the header visible
      LV_ModifyCol(5, 110)  ; Expand "TVDB Series ID No" to keep the header visible
      ControlSetText, Edit1, Added file %TargetFile%..., %WindowTitle%
   }
   Return

ButtonClear:
   ClearList()
   Return

ClearList()
{
   TargetFolder =
   TargetFile =
   LV_Delete()
   ControlSetText, Edit1, Cleared Listview, %WindowTitle%
   Return
}

InternetCheckConnection(Url="",FIFC=1) {
   Return DllCall("Wininet.dll\InternetCheckConnectionA", Str,Url, Int,FIFC, Int,0)
}

ButtonGetTVDBInfo:
   GetTVDBInfo()
   Return

GetTVDBInfo()
{
   LV_GetText(LVFileName, 1, 1)
   If not LVFileName
   {
      Gui +OwnDialogs
      MsgBox, 0,Fatal Error!, You must select a file or folder before connecting to TheTVDB.com!
      Return
   }
   LV_GetText(LVFileDir, 1, 3)  ; Get the file directory
   LV_GetText(LVFileExt, 1, 4)  ; Get the file extension

   URL := "http://www.thetvdb.com"

   If not InternetCheckConnection(URL)
   {
      Msgbox, 48, [%URL%]  , Connection Failed!
      Return
   }

   RowNumber = 1
   ShowInfo := GetTVDBShows(GetShowName(LVFileName, LVFileDir))
   StringSplit, ShowArray, ShowInfo, `,
   ShowName = %ShowArray1%
   SeriesIDNo = %ShowArray2%
   Loop
   {
      Gui +OwnDialogs
      If A_Index > 1
      {
         LV_GetText(LVPrevFN, RowNumber - 1, 1)  ; Get the preceeding rows filename
         LV_GetText(LVPrevFD, RowNumber - 1, 3)  ; Get the preceeding rows file directory
         PrevShowName := GetShowName(LVPrevFN, LVPrevFD)
         StringUpper, UpperPrevSN, PrevShowName

         NewShowName := GetShowName(LVFileName, LVFileDir)
         StringUpper, UpperCurrSN, NewShowName
         If UpperCurrSN <> %UpperPrevSN%
         {
            ShowInfo := GetTVDBShows(NewShowName)
            StringSplit, ShowArray, ShowInfo, `,
            ShowName = %ShowArray1%
            SeriesIDNo = %ShowArray2%
         }
      }
      UpperPrevSN =
      SeasonNumber := GetSeasonNumber(LVFileName)
      EpisodeNumber := GetEpisodeNumber(LVFileName)
      OriginalTitle := GetTitle(LVFileName)
      ControlSetText, Edit1, Processing "%ShowName%" Season "%SeasonNumber%" Episode "%EpisodeNumber%", %WindowTitle%
      If SeriesIDNo
      {
         IfInString, ShowName, %A_Space%
            StringReplace, SafeShowName, ShowName, %A_Space%, _, All
         Else
            SafeShowName = %ShowName%
         EpisodeInfo := GetTVDBEpisodes(SeriesIDNo, SeasonNumber, EpisodeNumber, SafeShowName)
         StringSplit, OutputArray, EpisodeInfo, `,
         SeasonNumber = %OutputArray1%
         EpisodeNumber = %OutputArray2%
         EpisodeTitle = %OutputArray3%
         If EpisodeTitle
         {
            StringReplace, EpisodeTitle, EpisodeTitle, \, %A_Space%~%A_Space%, All
            StringReplace, EpisodeTitle, EpisodeTitle, /, %A_Space%~%A_Space%, All
            StringReplace, EpisodeTitle, EpisodeTitle, :, %A_Space%~%A_Space%, All
            StringReplace, EpisodeTitle, EpisodeTitle, *, %A_Space%~%A_Space%, All
            StringReplace, EpisodeTitle, EpisodeTitle, ?,, All
            StringReplace, EpisodeTitle, EpisodeTitle, ", ', All
            StringReplace, EpisodeTitle, EpisodeTitle, <, %A_Space%less than%A_Space%, All
            StringReplace, EpisodeTitle, EpisodeTitle, >, %A_Space%greater than%A_Space%, All
            StringReplace, EpisodeTitle, EpisodeTitle, |, %A_Space%~%A_Space%, All
            StringReplace, EpisodeTitle, EpisodeTitle, &`#44;, `,, All
            StringReplace, EpisodeTitle, EpisodeTitle, &, &, All
         }
         If OriginalTitle
         {
            StringReplace, OriginalTitle, OriginalTitle, \, %A_Space%~%A_Space%, All
            StringReplace, OriginalTitle, OriginalTitle, /, %A_Space%~%A_Space%, All
            StringReplace, OriginalTitle, OriginalTitle, :, %A_Space%~%A_Space%, All
            StringReplace, OriginalTitle, OriginalTitle, *, %A_Space%~%A_Space%, All
            StringReplace, OriginalTitle, OriginalTitle, ?,, All
            StringReplace, OriginalTitle, OriginalTitle, ", ', All
            StringReplace, OriginalTitle, OriginalTitle, <, %A_Space%less than%A_Space%, All
            StringReplace, OriginalTitle, OriginalTitle, >, %A_Space%greater than%A_Space%, All
            StringReplace, OriginalTitle, OriginalTitle, |, %A_Space%~%A_Space%, All
            StringReplace, OriginalTitle, OriginalTitle, &`#44;, `,, All
            StringReplace, OriginalTitle, OriginalTitle, &, &, All
         }
      }
      GuiControlGet, PadZero,, Zero
      If PadZero = 1
      {
         SeasonNumber := PadZero(SeasonNumber)
         EpisodeNumber := PadZero(EpisodeNumber)
      }
      GuiControlGet, NamingScheme,, NameScheme
      If NamingScheme = 1
      {
         If EpisodeTitle
            NewFileName = %ShowName% - %SeasonNumber%x%EpisodeNumber% - %EpisodeTitle%
         Else If OriginalTitle
            NewFileName = %ShowName% - %SeasonNumber%x%EpisodeNumber% - %OriginalTitle%
         Else
            NewFileName = %ShowName% - %SeasonNumber%x%EpisodeNumber%
      }
      Else if NamingScheme = 2
      {
         If EpisodeTitle
            NewFileName = %ShowName% - S%SeasonNumber%E%EpisodeNumber% - %EpisodeTitle%
         Else If OriginalTitle
            NewFileName = %ShowName% - S%SeasonNumber%E%EpisodeNumber% - %OriginalTitle%
         Else
            NewFileName = %ShowName% - S%SeasonNumber%E%EpisodeNumber%
      }
      Else If NamingScheme = 3
      {
         If EpisodeTitle
            NewFileName = %SeasonNumber%x%EpisodeNumber% - %EpisodeTitle%
         Else If OriginalTitle
            NewFileName = %SeasonNumber%x%EpisodeNumber% - %OriginalTitle%
         Else
            NewFileName = %SeasonNumber%x%EpisodeNumber%
      }
      Else If NamingScheme = 4
      {
         If EpisodeTitle
            NewFileName = S%SeasonNumber%E%EpisodeNumber% - %EpisodeTitle%
         Else If OriginalTitle
            NewFileName = S%SeasonNumber%E%EpisodeNumber% - %OriginalTitle%
         Else
            NewFileName = S%SeasonNumber%E%EpisodeNumber%
      }
      GuiControlGet, Sep,, Separator
      If Sep = 2
      {
         StringReplace, NewFileName, NewFileName, %A_Space%, ., All
      }
      Else If Sep = 3
      {
         StringReplace, NewFileName, NewFileName, %A_Space%, _, All
      }
      NewFileName = %NewFileName%.%LVFileExt%
      LV_Modify(RowNumber, Col1, LVFileName, NewFileName, LVFileDir, LVFileExt, SeriesIDNo)
      LV_ModifyCol()
      LV_ModifyCol(4, 60)
      LV_ModifyCol(5, 110)  ; Expand "TVDB Series ID No" to keep the header visible
      LVFileName =
      LVPrevFN =
      ShowArray1 =
      OutputArray1 =
      OutputArray2 =
      OutputArray3 =
      SeasonNumber =
      EpisodeNumber =
      EpisodeTitle =
      OriginalTitle =
      RowNumber := RowNumber + 1
      LV_GetText(LVFileName, RowNumber, 1)  ; Get the filename
      If not LVFileName  ; Break the loop at the end of the list
         Break
      LV_GetText(LVFileDir, RowNumber, 3)  ; Get the file directory
      LV_GetText(LVFileExt, RowNumber, 4)  ; Get the file extension
   }
   ControlSetText, Edit1, Finished querying TheTVDB.com. Ready to rename..., %WindowTitle%
   Return
}

ButtonRename:
   LV_GetText(LVNewFileName, 1, 2)
   If not LVNewFileName
   {
      GuiControlGet, DirectRename,, Rename
      If DirectRename = 1
      {
         GetTVDBInfo()
      }
      Else
      {
         Gui +OwnDialogs
         MsgBox, 0,Fatal Error!, You must scan your files against TheTVDB.com before you rename them!
         Return
      }
   }
   Loop
   {
      RowNumber = %A_Index%
      LV_GetText(LVFileName, RowNumber, 1)  ; Get the original filename
      LV_GetText(LVNewFileName, RowNumber, 2)  ; Get the new filename
      LV_GetText(LVFileDir, RowNumber, 3)  ; Get the file dir
      LV_GetText(LVFileExt, RowNumber, 4)  ; Get the file extension
      If not LVNewFileName  ; Break the loop at the end of the list
         Break
      ControlSetText, Edit1, Renaming "%LVFileName%" to "%LVNewFileName%", %WindowTitle%
      FileMove, %LVFileDir%\%LVFileName%, %LVFileDir%\%LVNewFileName%  ; Finally, rename it
      LV_Modify(RowNumber, Col1, LVNewFileName, "", LVFileDir, LVFileExt, SeriesIDNo)
   }
   RenameCount := RowNumber - 1
   ControlSetText, Edit1, Finished renaming files! Refreshing file list., %WindowTitle%
   GuiControlGet, ClearIt,, Clear
   If ClearIt = 1
   {
      ClearList()
   }
   Else
   {
      GuiControl, +Redraw, MyListView  ; Turn redrawing back on
      LV_ModifyCol()  ; Resize each column to fit
      LV_ModifyCol(2, 60)  ; Expand "Preview" to keep the header visible
      LV_ModifyCol(4, 60)  ; Expand "Extension" to keep the header visible
      LV_ModifyCol(5, 110)  ; Expand "TVDB Series ID No" to keep the header visible
   }
   ControlSetText, Edit1, Finished Successfully!, %WindowTitle%
   Return

;Provide a filename (greek.s01e01.original.title.avi) and this should return the original title (in case a title isn't found)
GetTitle(FileName)
{
   SplitPath , FileName, name, dir, ext, FileName
   IfInString, FileName, .
      StringReplace, NormalName, FileName, ., %A_Space%, All
   IfInString, NormalName, _
      StringReplace, NormalName, NormalName, _, %A_Space%, All
   If RegExMatch(NormalName, "i)s[0-9][0-9]? ?e[0-9][0-9]?", SeasonAndEpisode)
   {
      StringGetPos, SeasonAndEpisodePos, NormalName, %SeasonAndEpisode%
      NumberOfChars := (StrLen(NormalName)-(StrLen(SeasonAndEpisode)+SeasonAndEpisodePos))
      StringRight, ShowTitle, NormalName, NumberOfChars
   }
   Else If RegExMatch(NormalName, "i)[0-9][0-9]?x[0-9][0-9]?", SeasonAndEpisode)
   {
      StringGetPos, SeasonAndEpisodePos, NormalName, %SeasonAndEpisode%
      NumberOfChars := (StrLen(NormalName)-(StrLen(SeasonAndEpisode)+SeasonAndEpisodePos))
      StringRight, ShowTitle, NormalName, NumberOfChars
   }
   Else If RegExMatch(NormalName, "[0-9][0-9][0-9][0-9]?", SeasonAndEpisode)
   {
      StringGetPos, SeasonAndEpisodePos, NormalName, %SeasonAndEpisode%
      NumberOfChars := (StrLen(NormalName)-(StrLen(SeasonAndEpisode)+SeasonAndEpisodePos))
      StringRight, ShowTitle, NormalName, NumberOfChars
   }
   Loop
   {
      StringRight, LastChar, ShowTitle, 1
      If (LastChar = "-" or LastChar = " ")
         StringTrimRight, ShowTitle, ShowTitle, 1
      Else
         Break
   }
   Loop
   {
      StringLeft, FirstChar, ShowTitle, 1
      If (FirstChar = "-" or FirstChar = " ")
         StringTrimLeft, ShowTitle, ShowTitle, 1
      Else
         Break
   }
   Return ShowTitle
}

;Provide a filename (s01e01.avi or greek.s01e01.avi) and Directory name (C:\TV\greek) and this should return the show name
GetShowName(FileName, FileDir)
{
   TempName := GetName(FileName)
   If not TempName
      TempName := GetNameFromDir(FileName, FileDir)
   Return TempName
}
;Provide a filename (greek.s01e01.avi) and this should return the show name
GetName(FileName)
{
   IfInString, FileName, .
      StringReplace, NormalName, FileName, ., %A_Space%, All
   IfInString, NormalName, _
      StringReplace, NormalName, NormalName, _, %A_Space%, All
   If RegExMatch(NormalName, "i)s[0-9][0-9]? ?e[0-9][0-9]?", SeasonAndEpisode)
   {
      StringGetPos, SeasonAndEpisodePos, NormalName, %SeasonAndEpisode%
      StringLeft, ShowName, NormalName, (SeasonAndEpisodePos - 1)
   }
   Else If RegExMatch(NormalName, "i)[0-9][0-9]?x[0-9][0-9]?", SeasonAndEpisode)
   {
      StringGetPos, SeasonAndEpisodePos, NormalName, %SeasonAndEpisode%
      StringLeft, ShowName, NormalName, (SeasonAndEpisodePos - 1)
   }
   Else If RegExMatch(NormalName, "[0-9][0-9][0-9][0-9]?", SeasonAndEpisode)
   {
      StringGetPos, SeasonAndEpisodePos, NormalName, %SeasonAndEpisode%
      StringLeft, ShowName, NormalName, (SeasonAndEpisodePos - 1)
   }
   Loop
   {
      StringRight, LastChar, ShowName, 1
      If (LastChar = "-" or LastChar = " ")
         StringTrimRight, ShowName, ShowName, 1
      Else
         Break
   }
   Return ShowName
}

;Provide a filename (s01e01.avi) and Directory name (C:\TV\greek) and this should return the show name
GetNameFromDir(FileName, FileDir)
{
   Directory = %FileDir% - %FileName%
   SplitPath , Directory, NewFileName, dir, ext, name
   Return GetName(NewFileName)
}

;Provide a filename (greek.s01e01.avi) and this should return the season number
GetSeasonNumber(FileName)
{
   If RegExMatch(FileName, "i)s\K[0-9][0-9]?.?e[0-9][0-9]?", SeasonAndEpisode)
   {
      StringSplit, OutputArray, SeasonAndEpisode, e E, .
      SeasonNumber = %OutputArray1%
      IfInString, SeasonNumber, 0
      {
         StringGetPos, ZeroLoc, SeasonNumber, 0
         If ZeroLoc = 0
            StringTrimLeft, SeasonNumber, SeasonNumber, 1
      }

   }
   Else If RegExMatch(FileName, "i)[0-9][0-9]?x[0-9][0-9]?", SeasonAndEpisode)
   {
      StringSplit, OutputArray, SeasonAndEpisode, x X
      SeasonNumber = %OutputArray1%
      IfInString, SeasonNumber, 0
      {
         StringGetPos, ZeroLoc, SeasonNumber, 0
         If ZeroLoc = 0
            StringTrimLeft, SeasonNumber, SeasonNumber, 1
      }
   }
   Else If RegExMatch(FileName, "[0-9][0-9][0-9][0-9]?", SeasonAndEpisode)
   {
      StringTrimRight, SeasonNumber, SeasonAndEpisode, 2
      IfInString, SeasonNumber, 0
      {
         StringGetPos, ZeroLoc, SeasonNumber, 0
         If ZeroLoc = 0
            StringTrimLeft, SeasonNumber, SeasonNumber, 1
      }
   }
   Return SeasonNumber
}

;Provide a filename (greek.s01e01.avi) and this should return the episode number
GetEpisodeNumber(FileName)
{
   If RegExMatch(FileName, "i)s\K[0-9][0-9]?.?e[0-9][0-9]?", SeasonAndEpisode)
   {
      StringSplit, OutputArray, SeasonAndEpisode, e E, .
      EpisodeNumber = %OutputArray2%
      IfInString, EpisodeNumber, 0
      {
         StringGetPos, ZeroLoc, EpisodeNumber, 0
         If ZeroLoc = 0
            StringTrimLeft, EpisodeNumber, EpisodeNumber, 1
      }
   }
   Else If RegExMatch(FileName, "i)[0-9][0-9]?.?x[0-9][0-9]?", SeasonAndEpisode)
   {
      StringSplit, OutputArray, SeasonAndEpisode, x X
      EpisodeNumber = %OutputArray2%
      IfInString, EpisodeNumber, 0
      {
         StringGetPos, ZeroLoc, EpisodeNumber, 0
         If ZeroLoc = 0
            StringTrimLeft, EpisodeNumber, EpisodeNumber, 1
      }
   }
   Else If RegExMatch(FileName, "[0-9][0-9][0-9][0-9]?", SeasonAndEpisode)
   {
      StringRight, EpisodeNumber, SeasonAndEpisode, 2
      IfInString, EpisodeNumber, 0
      {
         StringGetPos, ZeroLoc, EpisodeNumber, 0
         If ZeroLoc = 0
            StringTrimLeft, EpisodeNumber, EpisodeNumber, 1
      }
   }
   Return EpisodeNumber
}

;Provide a show name (greek) and it will return the TVDB data for the show name (Greek) and series ID (80301) as a CSV (Greek,80301)
GetTVDBShows(ShowName)
{
   Global SeriesName, SeriesIDNum
   IfExist, Series_ID.xml
      FileDelete, Series_ID.xml
   UrlDownloadToFile, http://www.thetvdb.com/api/GetSeries.php?seriesname="%ShowName%", Series_ID.xml
   XPath_Load(xml, "Series_ID.xml")
   FileDelete, Series_ID.xml
   SeriesNameNodeCount := XPath(xml, "/Data/Series/SeriesName/Count()")
   If SeriesNameNodeCount = 1
   {
      SeriesIDNum := XPath(xml, "/Data/Series/seriesid/text()")
      SeriesName := XPath(xml, "/Data/Series/SeriesName/text()")
   }
   Else If SeriesNameNodeCount > 1
   {
      SeriesIDNum := XPath(xml, "/Data/Series/seriesid/text()")
      SeriesName := XPath(xml, "/Data/Series/SeriesName/text()")
      SeriesOverview := XPath(xml, "/Data/Series/Overview/text()")
      StringSplit, OutputArraySID, SeriesIDNum, `,
      StringSplit, OutputArraySN, SeriesName, `,
      StringSplit, OutputArraySO, SeriesOverview, `,
      Gui, 2: Default
      Gui, 2: +ToolWindow +Owner1
      Gui, 2: Add, ListView, xm r15 w600, Show name|Show description|TVDB series ID no.
      Gui, 2: Add, Text, y+7
      Gui, 2: Add, Button, x+475, Select
      Gui, 2: Add, Button, x+15, Cancel
      Loop, %SeriesNameNodeCount%
      {
         SeriesIDNum := OutputArraySID%A_Index%
         SeriesName := OutputArraySN%A_Index%
         SeriesOverview := OutputArraySO%A_Index%
         IfInString, SeriesOverview, ,`;
            StringReplace, SeriesOverview, SeriesOverview, ,`;, `,, All
         If not SeriesOverview
            SeriesOverview = (No show description provided)
         LV_Add(Row, SeriesName, SeriesOverview, SeriesIDNum)
         LV_ModifyCol()
         LV_ModifyCol(3, 110)
         SeriesIDNum =
         SeriesName =
         SeriesOverview =
      }
      Gui, 2: Show,,Which Show?
      Gui, 1: Default
      WinWaitClose, Which Show?
   }
   If not SeriesName
      SeriesName = %ShowName%
   J = %SeriesName%,%SeriesIDNum%
   ShowName =
   SeriesIDNum =
   SeriesName =
   SeriesOverview =
   Return J
}

   ;Labels required for Gui 2
   2GuiEscape:
   2GuiClose:
   2ButtonCancel:
   {
      Gui, 2: Destroy
      Return
   }
   2ButtonSelect:
   {
      FocusedRowNumber := LV_GetNext(0, "F")
      If not FocusedRowNumber
      {
         MsgBox, 0, Warning!, You must select a show or press cancel!
         Return
      }
      LV_GetText(SeriesName, FocusedRowNumber, 1)
      LV_GetText(SeriesIDNum, FocusedRowNumber, 3)
      FocusedRowNumber =
      Gui, 2: Destroy
      Return
   }

;Provide the "TVDB series ID", "season number" and "episode number" and this will return the TVDB season number, episode number, and episode title as a CSV (3,1,The Day After)
GetTVDBEpisodes(SeriesIDNum, SeasonNum, EpisodeNum, ShowName)
{
   GuiControlGet, CacheInfo,, Cache
   FileName = data/%ShowName%_%SeasonNum%x%EpisodeNum%.xml
   If CacheInfo = 1
   {
      IfNotExist, FileName
         UrlDownloadToFile, http://www.thetvdb.com/api/563E39CDC7F666DF/series/%SeriesIDNum%/default/%SeasonNum%/%EpisodeNum%/en.xml, %FileName%
      If not XPath_Load(xml, FileName)
         Msgbox, 48, [XPath]  , Load of %FileName% Failed!
   }
   Else
   {
      IfExist, Episode_Info.xml
         FileDelete, Episode_Info.xml
      UrlDownloadToFile, http://www.thetvdb.com/api/563E39CDC7F666DF/series/%SeriesIDNum%/default/%SeasonNum%/%EpisodeNum%/en.xml, Episode_Info.xml
      If not XPath_Load(xml, "Episode_Info.xml")
         Msgbox, 48, [XPath]  , Load of "Episode_Info.xml" Failed!
      FileDelete, Episode_Info.xml
   }
   SeasonNumber := XPath(xml, "/Data/Episode/SeasonNumber/text()")
   EpisodeNumber := XPath(xml, "/Data/Episode/EpisodeNumber/text()")
   EpisodeTitle := XPath(xml, "/Data/Episode/EpisodeName/text()")
   If not EpisodeTitle
   {
      IfExist, %FileName%
         FileDelete, %FileName%
   }
   If not SeasonNumber
      SeasonNumber = %SeasonNum%
   If not EpisodeNumber
      EpisodeNumber = %EpisodeNum%
   K = %SeasonNumber%,%EpisodeNumber%,%EpisodeTitle%
   SeasonNumber =
   EpisodeNumber =
   EpisodeTitle =
   Return K
}

;Pads a variable with a preceeding zero
PadZero(VarToPad)
{
   VarToPadLen := StrLen(VarToPad)
   If VarToPadLen = 1
      VarToPad = 0%VarToPad%
   VarToPadLen =
   Return VarToPad
}

/*
>>>>CHANGELOG<<<<

1.0 (10-5-2009)
   - Original script
1.1 (10-6-2009)
   - Fixed a bug with adding a single file where the file would not be renamed
   -- Forgot to define the TargetFile's TargetFolder when updating the GUI
1.2 (10-13-2009)
   - Fixed another bug with adding a single file where the file would not be renamed
   - Fixed a bug with parsing the series overview where the non-comma delimiter (,) would be displayed
   -- Titans XPath replaces commas with "," (no quotes)
1.30 (11-8-2009)
   - Added a new method of selecting a show name when multiple results are returned
   -- Secondary ListView gui is displayed allowing the user to select the correct show
   - Script now compares the current filename against the previous filename (filenames converted to UPPERCASE)
   -- Drasitically reduces the number of requests against the TVDB and speeds everything up when renaming multiple shows all with the same name
   - Added a check and replace system for invalid filename characters
   -- StringReplace these chars \ / : * ? "" < > | with descriptive replacements
   - Fixed a bug in the GetEpisodeNumber() function
   -- A single digit season number would sometimes cause too few of the episode numbers to be returned when SeasonAndEpisode contained (e|x)
   - Tweaked GetSeasonNumber() and GetEpisodeNumber() to more reliably return correct data
   -- StringGetPos and String(Left|Right) were swapped for StringSplit to more predictably split SeasonAndEpisode regardless of (e|x) char location
   - Added a check to make sure files have a new filename in the preview column before renaming
   - Added a static window title which may be needed for various features in the future as well as making things look nicer :P
1.40 (11-15-2009)
   - Added status bar
   - Fixed a bug where a file would not have a preceeding zero added if no info was found on TheTVDB by adding PadZero() function
   -- Preceeding zero was only added in GetTVDBEpisodes() which means that if SeriesIDNo was blank (i.e. no info pulled from TheTVDB) the Season and Episode number would not get padded
1.41 (12-10-2009)
   - Fixed a serious bug where no results would be returned for ShowName inside the GetTVDBShows function would return the first result infinitely
   -- Had to clear the SeriesName var at the end of the function so that on the next loop iteration the correct var contents would exist
1.42 (12-11-2009)
   - Fixed a minor bug where the second time the GetTVDBInfo button was pressed, the first item in the list view would not actually be rescanned
   -- Had to clear the UpperPrevSN and PrevShowName vars so that the second time the button was pressed it would compare the correct names

>>>>Paradox Changelog<<<<

1.42.1 (2-5-2010)
   - Added new checkbox and supporting code that allows you to save the xmls downloaded in data/%ShowName%_%SeasonNum%x%EpisodeNum%.xml to make future renames quicker.
   -- Added check that determines if you are connected to the internet and thetvdb.com is reachable
   - Added better handling for previous showname
   -- Clean up some code that caused shows to use the previous renamed file settings wrongly
   - Renamed GetShowName(FileName) to GetName(FileName) and added new GetShowName(FileName, FileDir) to implement the following feature without requiring big changes to existing scripts.
   -- Added GetNameFromDir(FileName, Directory) to handle using the directory name as the showname, in case you are renaming files named 01x01 - title.avi the directory must, of course, be named as the show name.
   - Added debug message box if the episode info xml can't be read for some reason.
   -- Fixed Bug where first file would be properly renamed "Castle [2009] - 01x01 - Title" and the rest would be improperly renamed Castle - 01x02 - Title"
   - I am planning to add more features including using the API properly to download All the Episode information for a show and cache it locally/update on a regular basis.
   -- Also Planning to add a feature that will recognize when you are missing episodes from a season and either create a .txt file with the show name, season, episode, and title in the directory, or, keep track of it in a log file of some sort.
1.42.2 (2-5-2010)
   - Added support for choosing if you want to use spaces, periods or underscores as separators
   -- Added A checkbox that allows you to clear the list after renaming, so you don't have to click the button :)
   - Moved some things on the interface around a bit to accommodate previous features.
   -- Fixed an error where the list of files in the directory were being displayed after renaming instead of the previous items, renamed.
   - Added an option that allows you to click on rename and have it do the TVDB lookup and rename all in one (Be careful with this option)
   -- Fix up a few other small bugs
1.42.3 (2-5-2010)
   - Remove Some debug code I forgot to remove before.
   -- Save original title (The part between the 01x01 and the extension), if any to be added back later if no official title is found.
   - Implement better way of refreshing the display after a rename.
*/


Paradox
  • Members
  • 24 posts
  • Last active: Mar 05 2013 04:15 PM
  • Joined: 05 Feb 2010
1.42.4
; SceneRenamer by strictlyfocused02
; Modified By Paradox iamparadox at netscape.net
; AutoHotkey Version: 1.0.48+
;
; Script Function:
;   Extracts season and episode info from the filename
;   and uses that to retreive info from TheTVDB.com to rename
;   the file to a user-specified format

;   Special thanks to TheTVDB.com
;   This project would not have been possible without their top-notch API

#Include xpath.ahk

#NoEnv
SendMode, Input
SetWorkingDir, %A_ScriptDir%

WindowTitle = SceneRenamer v1.42.4 Modified By Paradox

Gui, Add, Button, Default gButtonAddFolder, &Add folder
Gui, Add, Button, x+20 gButtonAddFile, &Add file
Gui, Add, Button, x+20 gButtonClear, &Clear list
Gui, Add, Text, x+150 w50, Status:
Gui, Add, Edit, +ReadOnly x+0 w400, Waiting for user to add file(s)...

Gui, Add, ListView, xm r26 w800 -ReadOnly vMyListView, Name|Preview|Directory|Extension|TVDB Series ID No

Gui, Add, DropDownList, w250 AltSubmit vNameScheme, (Show Title) - (SS)x(EE) - (Episode Title)|(Show Title) - S(SS)E(EE) - (Episode Title)|(SS)x(EE) - Episode Title||S(SS)E(EE) - (Episode Title)
Gui, Add, DropDownList, x+10 w180 AltSubmit vSeparator, Use spaces as separators|Use.periods.as.separators||Use_underscores_as_separators
Gui, Add, Button, x+150 gButtonGetTVDBInfo, &Get TVDB Info
Gui, Add, Button, x+10 gButtonRename, &Rename files

Gui, Add, Checkbox, xm Checked vZero, Pad with zero?
Gui, Add, Checkbox, x+10 Checked vCache, Cache Episode Info?
Gui, Add, Checkbox, x+10 vRename, Allow Direct Rename?
Gui, Add, Checkbox, x+10 Checked vClear, Clear List after Rename?

Menu, MyContextMenu, Add, Open, ContextOpenFile
Menu, MyContextMenu, Add, Properties, ContextProperties
Menu, MyContextMenu, Add, Remove item, ContextRemoveItem

Gui, Show,, %WindowTitle%
Return

GuiClose:
   ExitApp

GuiContextMenu:
   If A_GuiControl <> MyListView
       Return
   Menu, MyContextMenu, Show, %A_GuiX%, %A_GuiY%
   Return

ContextOpenFile:
ContextProperties:
   FocusedRowNumber := LV_GetNext(0, "F")
   If not FocusedRowNumber
      return
   LV_GetText(FileName, FocusedRowNumber, 1)
   LV_GetText(FileDir, FocusedRowNumber, 3)
   IfInString A_ThisMenuItem, Open
      Run %FileDir%\%FileName%,, UseErrorLevel
   Else
      Run Properties "%FileDir%\%FileName%",, UseErrorLevel
   If ErrorLevel
      MsgBox Could not perform requested action on "%FileDir%\%FileName%".
   return

ContextRemoveItem:
   RowNumber = 0
   Loop
   {
      RowNumber := LV_GetNext(RowNumber - 1)
      If not RowNumber
           Break
      LV_Delete(RowNumber)
   }
   Return

ButtonAddFolder:
   Gui +OwnDialogs
   FileSelectFolder, TargetFolder,, 3, Select a folder:
   If not TargetFolder  ; The user pressed cancel
       Return
   StringRight, LastChar, TargetFolder, 1
   If LastChar = \
      StringTrimRight, TargetFolder, TargetFolder, 1
   GuiControl, -Redraw, MyListView ; Improves performance by disabling redrawing
   Loop %TargetFolder%\*.*
   {
      FileName := A_LoopFileFullPath
      SplitPath, FileName,,, FileExt  ; Get the file extension
      If FileExt in avi,mkv,mp4
         LV_Add(Row, A_LoopFileName, "", A_LoopFileDir, FileExt)
   }
   GuiControl, +Redraw, MyListView  ; Turn redrawing back on
   LV_ModifyCol()  ; Resize each column to fit
   LV_ModifyCol(2, 60)  ; Expand "Preview" to keep the header visible
   LV_ModifyCol(4, 60)  ; Expand "Extension" to keep the header visible
   LV_ModifyCol(5, 110)  ; Expand "TVDB Series ID No" to keep the header visible
   ControlSetText, Edit1, Added folder %TargetFolder%, %WindowTitle%
   Return

ButtonAddFile:
   Gui +OwnDialogs
   FileSelectFile, TargetFile
   If not TargetFile
      Return
   SplitPath, TargetFile,,, FileExt  ; Get the file extension
   If FileExt in avi,mkv,mp4
   {
      SplitPath, TargetFile, FileName, TargetFolder
      LV_Add(Row, FileName, "", TargetFolder, FileExt)
      LV_ModifyCol()  ; Resize each column to fit
      LV_ModifyCol(2, 60)  ; Expand "Preview" to keep the header visible
      LV_ModifyCol(4, 60)  ; Expand "Extension" to keep the header visible
      LV_ModifyCol(5, 110)  ; Expand "TVDB Series ID No" to keep the header visible
      ControlSetText, Edit1, Added file %TargetFile%..., %WindowTitle%
   }
   Return

ButtonClear:
   ClearList()
   Return

ClearList()
{
   TargetFolder =
   TargetFile =
   LV_Delete()
   ControlSetText, Edit1, Cleared Listview, %WindowTitle%
   Return
}

InternetCheckConnection(Url="",FIFC=1) {
   Return DllCall("Wininet.dll\InternetCheckConnectionA", Str,Url, Int,FIFC, Int,0)
}

ButtonGetTVDBInfo:
   GetTVDBInfo()
   Return

GetTVDBInfo()
{
   LV_GetText(LVFileName, 1, 1)
   If not LVFileName
   {
      Gui +OwnDialogs
      MsgBox, 0,Fatal Error!, You must select a file or folder before connecting to TheTVDB.com!
      Return
   }
   LV_GetText(LVFileDir, 1, 3)  ; Get the file directory
   LV_GetText(LVFileExt, 1, 4)  ; Get the file extension

   URL := "http://www.thetvdb.com"

   If not InternetCheckConnection(URL)
   {
      Msgbox, 48, [%URL%]  , Connection Failed!
      Return
   }

   RowNumber = 1
   ShowInfo := GetTVDBShows(GetShowName(LVFileName, LVFileDir))
   StringSplit, ShowArray, ShowInfo, `,
   ShowName = %ShowArray1%
   SeriesIDNo = %ShowArray2%
   Loop
   {
      Gui +OwnDialogs
      If A_Index > 1
      {
         LV_GetText(LVPrevFN, RowNumber - 1, 1)  ; Get the preceeding rows filename
         LV_GetText(LVPrevFD, RowNumber - 1, 3)  ; Get the preceeding rows file directory
         PrevShowName := GetShowName(LVPrevFN, LVPrevFD)
         StringUpper, UpperPrevSN, PrevShowName

         NewShowName := GetShowName(LVFileName, LVFileDir)
         StringUpper, UpperCurrSN, NewShowName
         If UpperCurrSN <> %UpperPrevSN%
         {
            ShowInfo := GetTVDBShows(NewShowName)
            StringSplit, ShowArray, ShowInfo, `,
            ShowName = %ShowArray1%
            SeriesIDNo = %ShowArray2%
         }
      }
      UpperPrevSN =
      SeasonNumber := GetSeasonNumber(LVFileName)
      EpisodeNumber := GetEpisodeNumber(LVFileName)
      OriginalTitle := GetTitle(LVFileName)
      ControlSetText, Edit1, Processing "%ShowName%" Season "%SeasonNumber%" Episode "%EpisodeNumber%", %WindowTitle%
      If SeriesIDNo
      {
         IfInString, ShowName, %A_Space%
            StringReplace, SafeShowName, ShowName, %A_Space%, _, All
         Else
            SafeShowName = %ShowName%
         EpisodeInfo := GetTVDBEpisodes(SeriesIDNo, SeasonNumber, EpisodeNumber, SafeShowName)
         StringSplit, OutputArray, EpisodeInfo, `,
         SeasonNumber = %OutputArray1%
         EpisodeNumber = %OutputArray2%
         EpisodeTitle = %OutputArray3%
         If EpisodeTitle
         {
            StringReplace, EpisodeTitle, EpisodeTitle, \, %A_Space%~%A_Space%, All
            StringReplace, EpisodeTitle, EpisodeTitle, /, %A_Space%~%A_Space%, All
            StringReplace, EpisodeTitle, EpisodeTitle, :, %A_Space%~%A_Space%, All
            StringReplace, EpisodeTitle, EpisodeTitle, *, %A_Space%~%A_Space%, All
            StringReplace, EpisodeTitle, EpisodeTitle, ?,, All
            StringReplace, EpisodeTitle, EpisodeTitle, ", ', All
            StringReplace, EpisodeTitle, EpisodeTitle, <, %A_Space%less than%A_Space%, All
            StringReplace, EpisodeTitle, EpisodeTitle, >, %A_Space%greater than%A_Space%, All
            StringReplace, EpisodeTitle, EpisodeTitle, |, %A_Space%~%A_Space%, All
            StringReplace, EpisodeTitle, EpisodeTitle, &`#44;, `,, All
            StringReplace, EpisodeTitle, EpisodeTitle, &, &, All
         }
         If OriginalTitle
         {
            StringReplace, OriginalTitle, OriginalTitle, \, %A_Space%~%A_Space%, All
            StringReplace, OriginalTitle, OriginalTitle, /, %A_Space%~%A_Space%, All
            StringReplace, OriginalTitle, OriginalTitle, :, %A_Space%~%A_Space%, All
            StringReplace, OriginalTitle, OriginalTitle, *, %A_Space%~%A_Space%, All
            StringReplace, OriginalTitle, OriginalTitle, ?,, All
            StringReplace, OriginalTitle, OriginalTitle, ", ', All
            StringReplace, OriginalTitle, OriginalTitle, <, %A_Space%less than%A_Space%, All
            StringReplace, OriginalTitle, OriginalTitle, >, %A_Space%greater than%A_Space%, All
            StringReplace, OriginalTitle, OriginalTitle, |, %A_Space%~%A_Space%, All
            StringReplace, OriginalTitle, OriginalTitle, &`#44;, `,, All
            StringReplace, OriginalTitle, OriginalTitle, &, &, All
         }
      }
      GuiControlGet, PadZero,, Zero
      If PadZero = 1
      {
         SeasonNumber := PadZero(SeasonNumber)
         EpisodeNumber := PadZero(EpisodeNumber)
      }
      GuiControlGet, NamingScheme,, NameScheme
      If NamingScheme = 1
      {
         If EpisodeTitle
            NewFileName = %ShowName% - %SeasonNumber%x%EpisodeNumber% - %EpisodeTitle%
         Else If OriginalTitle
            NewFileName = %ShowName% - %SeasonNumber%x%EpisodeNumber% - %OriginalTitle%
         Else
            NewFileName = %ShowName% - %SeasonNumber%x%EpisodeNumber%
      }
      Else if NamingScheme = 2
      {
         If EpisodeTitle
            NewFileName = %ShowName% - S%SeasonNumber%E%EpisodeNumber% - %EpisodeTitle%
         Else If OriginalTitle
            NewFileName = %ShowName% - S%SeasonNumber%E%EpisodeNumber% - %OriginalTitle%
         Else
            NewFileName = %ShowName% - S%SeasonNumber%E%EpisodeNumber%
      }
      Else If NamingScheme = 3
      {
         If EpisodeTitle
            NewFileName = %SeasonNumber%x%EpisodeNumber% - %EpisodeTitle%
         Else If OriginalTitle
            NewFileName = %SeasonNumber%x%EpisodeNumber% - %OriginalTitle%
         Else
            NewFileName = %SeasonNumber%x%EpisodeNumber%
      }
      Else If NamingScheme = 4
      {
         If EpisodeTitle
            NewFileName = S%SeasonNumber%E%EpisodeNumber% - %EpisodeTitle%
         Else If OriginalTitle
            NewFileName = S%SeasonNumber%E%EpisodeNumber% - %OriginalTitle%
         Else
            NewFileName = S%SeasonNumber%E%EpisodeNumber%
      }
      GuiControlGet, Sep,, Separator
      If Sep = 2
      {
         StringReplace, NewFileName, NewFileName, %A_Space%, ., All
      }
      Else If Sep = 3
      {
         StringReplace, NewFileName, NewFileName, %A_Space%, _, All
      }
      NewFileName = %NewFileName%.%LVFileExt%
      LV_Modify(RowNumber, Col1, LVFileName, NewFileName, LVFileDir, LVFileExt, SeriesIDNo)
      LV_ModifyCol()
      LV_ModifyCol(4, 60)
      LV_ModifyCol(5, 110)  ; Expand "TVDB Series ID No" to keep the header visible
      LVFileName =
      LVPrevFN =
      ShowArray1 =
      OutputArray1 =
      OutputArray2 =
      OutputArray3 =
      SeasonNumber =
      EpisodeNumber =
      EpisodeTitle =
      OriginalTitle =
      RowNumber := RowNumber + 1
      LV_GetText(LVFileName, RowNumber, 1)  ; Get the filename
      If not LVFileName  ; Break the loop at the end of the list
         Break
      LV_GetText(LVFileDir, RowNumber, 3)  ; Get the file directory
      LV_GetText(LVFileExt, RowNumber, 4)  ; Get the file extension
   }
   ControlSetText, Edit1, Finished querying TheTVDB.com. Ready to rename..., %WindowTitle%
   Return
}

ButtonRename:
   LV_GetText(LVNewFileName, 1, 2)
   If not LVNewFileName
   {
      GuiControlGet, DirectRename,, Rename
      If DirectRename = 1
      {
         GetTVDBInfo()
      }
      Else
      {
         Gui +OwnDialogs
         MsgBox, 0,Fatal Error!, You must scan your files against TheTVDB.com before you rename them!
         Return
      }
   }
   Loop
   {
      RowNumber = %A_Index%
      LV_GetText(LVFileName, RowNumber, 1)  ; Get the original filename
      LV_GetText(LVNewFileName, RowNumber, 2)  ; Get the new filename
      LV_GetText(LVFileDir, RowNumber, 3)  ; Get the file dir
      LV_GetText(LVFileExt, RowNumber, 4)  ; Get the file extension
      If not LVNewFileName  ; Break the loop at the end of the list
         Break
      ControlSetText, Edit1, Renaming "%LVFileName%" to "%LVNewFileName%", %WindowTitle%
      FileMove, %LVFileDir%\%LVFileName%, %LVFileDir%\%LVNewFileName%  ; Finally, rename it
      LV_Modify(RowNumber, Col1, LVNewFileName, "", LVFileDir, LVFileExt, SeriesIDNo)
   }
   RenameCount := RowNumber - 1
   ControlSetText, Edit1, Finished renaming files! Refreshing file list., %WindowTitle%
   GuiControlGet, ClearIt,, Clear
   If ClearIt = 1
   {
      ClearList()
   }
   Else
   {
      GuiControl, +Redraw, MyListView  ; Turn redrawing back on
      LV_ModifyCol()  ; Resize each column to fit
      LV_ModifyCol(2, 60)  ; Expand "Preview" to keep the header visible
      LV_ModifyCol(4, 60)  ; Expand "Extension" to keep the header visible
      LV_ModifyCol(5, 110)  ; Expand "TVDB Series ID No" to keep the header visible
   }
   ControlSetText, Edit1, Finished Successfully!, %WindowTitle%
   Return

;Provide a filename (greek.s01e01.original.title.avi) and this should return the original title (in case a title isn't found)
GetTitle(FileName)
{
   SplitPath , FileName, name, dir, ext, FileName
   IfInString, FileName, .
      StringReplace, FileName, FileName, ., %A_Space%, All
   IfInString, FileName, _
      StringReplace, FileName, FileName, _, %A_Space%, All
   If RegExMatch(FileName, "i)s[0-9][0-9]? ?e[0-9][0-9]?", SeasonAndEpisode)
   {
      StringGetPos, SeasonAndEpisodePos, FileName, %SeasonAndEpisode%
      NumberOfChars := (StrLen(FileName)-(StrLen(SeasonAndEpisode)+SeasonAndEpisodePos))
      StringRight, ShowTitle, FileName, NumberOfChars
   }
   Else If RegExMatch(FileName, "i)[0-9][0-9]?x[0-9][0-9]?", SeasonAndEpisode)
   {
      StringGetPos, SeasonAndEpisodePos, FileName, %SeasonAndEpisode%
      NumberOfChars := (StrLen(FileName)-(StrLen(SeasonAndEpisode)+SeasonAndEpisodePos))
      StringRight, ShowTitle, FileName, NumberOfChars
   }
   Else If RegExMatch(FileName, "[0-9][0-9][0-9][0-9]?", SeasonAndEpisode)
   {
      StringGetPos, SeasonAndEpisodePos, FileName, %SeasonAndEpisode%
      NumberOfChars := (StrLen(FileName)-(StrLen(SeasonAndEpisode)+SeasonAndEpisodePos))
      StringRight, ShowTitle, FileName, NumberOfChars
   }
   Loop
   {
      StringRight, LastChar, ShowTitle, 1
      If (LastChar = "-" or LastChar = " ")
         StringTrimRight, ShowTitle, ShowTitle, 1
      Else
         Break
   }
   Loop
   {
      StringLeft, FirstChar, ShowTitle, 1
      If (FirstChar = "-" or FirstChar = " ")
         StringTrimLeft, ShowTitle, ShowTitle, 1
      Else
         Break
   }
   Return ShowTitle
}

;Provide a filename (s01e01.avi or greek.s01e01.avi) and Directory name (C:\TV\greek) and this should return the show name
GetShowName(FileName, FileDir)
{
   TempName := GetName(FileName)
   If not TempName
      TempName := GetNameFromDir(FileName, FileDir)
   Return TempName
}
;Provide a filename (greek.s01e01.avi) and this should return the show name
GetName(FileName)
{
   IfInString, FileName, .
      StringReplace, FileName, FileName, ., %A_Space%, All
   IfInString, FileName, _
      StringReplace, FileName, FileName, _, %A_Space%, All
   If RegExMatch(FileName, "i)s[0-9][0-9]? ?e[0-9][0-9]?", SeasonAndEpisode)
   {
      StringGetPos, SeasonAndEpisodePos, FileName, %SeasonAndEpisode%
      StringLeft, ShowName, FileName, (SeasonAndEpisodePos - 1)
   }
   Else If RegExMatch(FileName, "i)[0-9][0-9]?x[0-9][0-9]?", SeasonAndEpisode)
   {
      StringGetPos, SeasonAndEpisodePos, FileName, %SeasonAndEpisode%
      StringLeft, ShowName, FileName, (SeasonAndEpisodePos - 1)
   }
   Else If RegExMatch(FileName, "[0-9][0-9][0-9][0-9]?", SeasonAndEpisode)
   {
      StringGetPos, SeasonAndEpisodePos, FileName, %SeasonAndEpisode%
      StringLeft, ShowName, FileName, (SeasonAndEpisodePos - 1)
   }
   Loop
   {
      StringRight, LastChar, ShowName, 1
      If (LastChar = "-" or LastChar = " ")
         StringTrimRight, ShowName, ShowName, 1
      Else
         Break
   }
   Return ShowName
}

;Provide a filename (s01e01.avi) and Directory name (C:\TV\greek) and this should return the show name
GetNameFromDir(FileName, FileDir)
{
   Directory = %FileDir% - %FileName%
   SplitPath , Directory, NewFileName, dir, ext, name
   Return GetName(NewFileName)
}

;Provide a filename (greek.s01e01.avi) and this should return the season number
GetSeasonNumber(FileName)
{
   If RegExMatch(FileName, "i)s\K[0-9][0-9]?.?e[0-9][0-9]?", SeasonAndEpisode)
   {
      StringSplit, OutputArray, SeasonAndEpisode, e E, .
      SeasonNumber = %OutputArray1%
      IfInString, SeasonNumber, 0
      {
         StringGetPos, ZeroLoc, SeasonNumber, 0
         If ZeroLoc = 0
            StringTrimLeft, SeasonNumber, SeasonNumber, 1
      }

   }
   Else If RegExMatch(FileName, "i)[0-9][0-9]?x[0-9][0-9]?", SeasonAndEpisode)
   {
      StringSplit, OutputArray, SeasonAndEpisode, x X
      SeasonNumber = %OutputArray1%
      IfInString, SeasonNumber, 0
      {
         StringGetPos, ZeroLoc, SeasonNumber, 0
         If ZeroLoc = 0
            StringTrimLeft, SeasonNumber, SeasonNumber, 1
      }
   }
   Else If RegExMatch(FileName, "[0-9][0-9][0-9][0-9]?", SeasonAndEpisode)
   {
      StringTrimRight, SeasonNumber, SeasonAndEpisode, 2
      IfInString, SeasonNumber, 0
      {
         StringGetPos, ZeroLoc, SeasonNumber, 0
         If ZeroLoc = 0
            StringTrimLeft, SeasonNumber, SeasonNumber, 1
      }
   }
   Return SeasonNumber
}

;Provide a filename (greek.s01e01.avi) and this should return the episode number
GetEpisodeNumber(FileName)
{
   If RegExMatch(FileName, "i)s\K[0-9][0-9]?.?e[0-9][0-9]?", SeasonAndEpisode)
   {
      StringSplit, OutputArray, SeasonAndEpisode, e E, .
      EpisodeNumber = %OutputArray2%
      IfInString, EpisodeNumber, 0
      {
         StringGetPos, ZeroLoc, EpisodeNumber, 0
         If ZeroLoc = 0
            StringTrimLeft, EpisodeNumber, EpisodeNumber, 1
      }
   }
   Else If RegExMatch(FileName, "i)[0-9][0-9]?.?x[0-9][0-9]?", SeasonAndEpisode)
   {
      StringSplit, OutputArray, SeasonAndEpisode, x X
      EpisodeNumber = %OutputArray2%
      IfInString, EpisodeNumber, 0
      {
         StringGetPos, ZeroLoc, EpisodeNumber, 0
         If ZeroLoc = 0
            StringTrimLeft, EpisodeNumber, EpisodeNumber, 1
      }
   }
   Else If RegExMatch(FileName, "[0-9][0-9][0-9][0-9]?", SeasonAndEpisode)
   {
      StringRight, EpisodeNumber, SeasonAndEpisode, 2
      IfInString, EpisodeNumber, 0
      {
         StringGetPos, ZeroLoc, EpisodeNumber, 0
         If ZeroLoc = 0
            StringTrimLeft, EpisodeNumber, EpisodeNumber, 1
      }
   }
   Return EpisodeNumber
}

;Provide a show name (greek) and it will return the TVDB data for the show name (Greek) and series ID (80301) as a CSV (Greek,80301)
GetTVDBShows(ShowName)
{
   Global SeriesName, SeriesIDNum
   IfExist, Series_ID.xml
      FileDelete, Series_ID.xml
   UrlDownloadToFile, http://www.thetvdb.com/api/GetSeries.php?seriesname="%ShowName%", Series_ID.xml
   XPath_Load(xml, "Series_ID.xml")
   FileDelete, Series_ID.xml
   SeriesNameNodeCount := XPath(xml, "/Data/Series/SeriesName/Count()")
   If SeriesNameNodeCount = 1
   {
      SeriesIDNum := XPath(xml, "/Data/Series/seriesid/text()")
      SeriesName := XPath(xml, "/Data/Series/SeriesName/text()")
   }
   Else If SeriesNameNodeCount > 1
   {
      SeriesIDNum := XPath(xml, "/Data/Series/seriesid/text()")
      SeriesName := XPath(xml, "/Data/Series/SeriesName/text()")
      SeriesOverview := XPath(xml, "/Data/Series/Overview/text()")
      StringSplit, OutputArraySID, SeriesIDNum, `,
      StringSplit, OutputArraySN, SeriesName, `,
      StringSplit, OutputArraySO, SeriesOverview, `,
      Gui, 2: Default
      Gui, 2: +ToolWindow +Owner1
      Gui, 2: Add, ListView, xm r15 w600, Show name|Show description|TVDB series ID no.
      Gui, 2: Add, Text, y+7
      Gui, 2: Add, Button, x+475, Select
      Gui, 2: Add, Button, x+15, Cancel
      Loop, %SeriesNameNodeCount%
      {
         SeriesIDNum := OutputArraySID%A_Index%
         SeriesName := OutputArraySN%A_Index%
         SeriesOverview := OutputArraySO%A_Index%
         IfInString, SeriesOverview, ,`;
            StringReplace, SeriesOverview, SeriesOverview, ,`;, `,, All
         If not SeriesOverview
            SeriesOverview = (No show description provided)
         LV_Add(Row, SeriesName, SeriesOverview, SeriesIDNum)
         LV_ModifyCol()
         LV_ModifyCol(3, 110)
         SeriesIDNum =
         SeriesName =
         SeriesOverview =
      }
      Gui, 2: Show,,Which Show?
      Gui, 1: Default
      WinWaitClose, Which Show?
   }
   If not SeriesName
      SeriesName = %ShowName%
   J = %SeriesName%,%SeriesIDNum%
   ShowName =
   SeriesIDNum =
   SeriesName =
   SeriesOverview =
   Return J
}

   ;Labels required for Gui 2
   2GuiEscape:
   2GuiClose:
   2ButtonCancel:
   {
      Gui, 2: Destroy
      Return
   }
   2ButtonSelect:
   {
      FocusedRowNumber := LV_GetNext(0, "F")
      If not FocusedRowNumber
      {
         MsgBox, 0, Warning!, You must select a show or press cancel!
         Return
      }
      LV_GetText(SeriesName, FocusedRowNumber, 1)
      LV_GetText(SeriesIDNum, FocusedRowNumber, 3)
      FocusedRowNumber =
      Gui, 2: Destroy
      Return
   }

;Provide the "TVDB series ID", "season number" and "episode number" and this will return the TVDB season number, episode number, and episode title as a CSV (3,1,The Day After)
GetTVDBEpisodes(SeriesIDNum, SeasonNum, EpisodeNum, ShowName)
{
   GuiControlGet, CacheInfo,, Cache
   FileName = data/%ShowName%_%SeasonNum%x%EpisodeNum%.xml
   If CacheInfo = 1
   {
      IfNotExist, FileName
         UrlDownloadToFile, http://www.thetvdb.com/api/563E39CDC7F666DF/series/%SeriesIDNum%/default/%SeasonNum%/%EpisodeNum%/en.xml, %FileName%
      If not XPath_Load(xml, FileName)
         Msgbox, 48, [XPath]  , Load of %FileName% Failed!
   }
   Else
   {
      IfExist, Episode_Info.xml
         FileDelete, Episode_Info.xml
      UrlDownloadToFile, http://www.thetvdb.com/api/563E39CDC7F666DF/series/%SeriesIDNum%/default/%SeasonNum%/%EpisodeNum%/en.xml, Episode_Info.xml
      If not XPath_Load(xml, "Episode_Info.xml")
         Msgbox, 48, [XPath]  , Load of "Episode_Info.xml" Failed!
      FileDelete, Episode_Info.xml
   }
   SeasonNumber := XPath(xml, "/Data/Episode/SeasonNumber/text()")
   EpisodeNumber := XPath(xml, "/Data/Episode/EpisodeNumber/text()")
   EpisodeTitle := XPath(xml, "/Data/Episode/EpisodeName/text()")
   If not EpisodeTitle
   {
      IfExist, %FileName%
         FileDelete, %FileName%
   }
   If not SeasonNumber
      SeasonNumber = %SeasonNum%
   If not EpisodeNumber
      EpisodeNumber = %EpisodeNum%
   K = %SeasonNumber%,%EpisodeNumber%,%EpisodeTitle%
   SeasonNumber =
   EpisodeNumber =
   EpisodeTitle =
   Return K
}

;Pads a variable with a preceeding zero
PadZero(VarToPad)
{
   VarToPadLen := StrLen(VarToPad)
   If VarToPadLen = 1
      VarToPad = 0%VarToPad%
   VarToPadLen =
   Return VarToPad
}

/*
>>>>CHANGELOG<<<<

1.0 (10-5-2009)
   - Original script
1.1 (10-6-2009)
   - Fixed a bug with adding a single file where the file would not be renamed
   -- Forgot to define the TargetFile's TargetFolder when updating the GUI
1.2 (10-13-2009)
   - Fixed another bug with adding a single file where the file would not be renamed
   - Fixed a bug with parsing the series overview where the non-comma delimiter (,) would be displayed
   -- Titans XPath replaces commas with "," (no quotes)
1.30 (11-8-2009)
   - Added a new method of selecting a show name when multiple results are returned
   -- Secondary ListView gui is displayed allowing the user to select the correct show
   - Script now compares the current filename against the previous filename (filenames converted to UPPERCASE)
   -- Drasitically reduces the number of requests against the TVDB and speeds everything up when renaming multiple shows all with the same name
   - Added a check and replace system for invalid filename characters
   -- StringReplace these chars \ / : * ? "" < > | with descriptive replacements
   - Fixed a bug in the GetEpisodeNumber() function
   -- A single digit season number would sometimes cause too few of the episode numbers to be returned when SeasonAndEpisode contained (e|x)
   - Tweaked GetSeasonNumber() and GetEpisodeNumber() to more reliably return correct data
   -- StringGetPos and String(Left|Right) were swapped for StringSplit to more predictably split SeasonAndEpisode regardless of (e|x) char location
   - Added a check to make sure files have a new filename in the preview column before renaming
   - Added a static window title which may be needed for various features in the future as well as making things look nicer :P
1.40 (11-15-2009)
   - Added status bar
   - Fixed a bug where a file would not have a preceeding zero added if no info was found on TheTVDB by adding PadZero() function
   -- Preceeding zero was only added in GetTVDBEpisodes() which means that if SeriesIDNo was blank (i.e. no info pulled from TheTVDB) the Season and Episode number would not get padded
1.41 (12-10-2009)
   - Fixed a serious bug where no results would be returned for ShowName inside the GetTVDBShows function would return the first result infinitely
   -- Had to clear the SeriesName var at the end of the function so that on the next loop iteration the correct var contents would exist
1.42 (12-11-2009)
   - Fixed a minor bug where the second time the GetTVDBInfo button was pressed, the first item in the list view would not actually be rescanned
   -- Had to clear the UpperPrevSN and PrevShowName vars so that the second time the button was pressed it would compare the correct names

>>>>Paradox Changelog<<<<

1.42.1 (2-5-2010)
   - Added new checkbox and supporting code that allows you to save the xmls downloaded in data/%ShowName%_%SeasonNum%x%EpisodeNum%.xml to make future renames quicker.
   -- Added check that determines if you are connected to the internet and thetvdb.com is reachable
   - Added better handling for previous showname
   -- Clean up some code that caused shows to use the previous renamed file settings wrongly
   - Renamed GetShowName(FileName) to GetName(FileName) and added new GetShowName(FileName, FileDir) to implement the following feature without requiring big changes to existing scripts.
   -- Added GetNameFromDir(FileName, Directory) to handle using the directory name as the showname, in case you are renaming files named 01x01 - title.avi the directory must, of course, be named as the show name.
   - Added debug message box if the episode info xml can't be read for some reason.
   -- Fixed Bug where first file would be properly renamed "Castle [2009] - 01x01 - Title" and the rest would be improperly renamed Castle - 01x02 - Title"
   - I am planning to add more features including using the API properly to download All the Episode information for a show and cache it locally/update on a regular basis.
   -- Also Planning to add a feature that will recognize when you are missing episodes from a season and either create a .txt file with the show name, season, episode, and title in the directory, or, keep track of it in a log file of some sort.
1.42.2 (2-5-2010)
   - Added support for choosing if you want to use spaces, periods or underscores as separators
   -- Added A checkbox that allows you to clear the list after renaming, so you don't have to click the button :)
   - Moved some things on the interface around a bit to accommodate previous features.
   -- Fixed an error where the list of files in the directory were being displayed after renaming instead of the previous items, renamed.
   - Added an option that allows you to click on rename and have it do the TVDB lookup and rename all in one (Be careful with this option)
   -- Fix up a few other small bugs
1.42.3 (2-5-2010)
   - Remove Some debug code I forgot to remove before.
   -- Save original title (The part between the 01x01 and the extension), if any to be added back later if no official title is found.
   - Implement better way of refreshing the display after a rename.
1.42.4 (2-5-2010)
   - Fix Typo that would keep files with no . in them at all from being renamed properly. (Exists in original 1.42 script as well)
*/


Paradox
  • Members
  • 24 posts
  • Last active: Mar 05 2013 04:15 PM
  • Joined: 05 Feb 2010
1.42.5

; SceneRenamer by strictlyfocused02
; Modified By Paradox iamparadox at netscape.net
; AutoHotkey Version: 1.0.48+
;
; Script Function:
;   Extracts season and episode info from the filename
;   and uses that to retreive info from TheTVDB.com to rename
;   the file to a user-specified format

;   Special thanks to TheTVDB.com
;   This project would not have been possible without their top-notch API

#Include xpath.ahk

#NoEnv
SendMode, Input
SetWorkingDir, %A_ScriptDir%

WindowTitle = SceneRenamer v1.42.5 Modified By Paradox

Gui, Add, Button, Default gButtonAddFolder, &Add folder
Gui, Add, Button, x+20 gButtonAddFile, &Add file
Gui, Add, Button, x+20 gButtonClear, &Clear list
Gui, Add, Text, x+150 w50, Status:
Gui, Add, Edit, +ReadOnly x+0 w400, Waiting for user to add file(s)...

Gui, Add, ListView, xm r26 w800 -ReadOnly vMyListView, Name|Preview|Directory|Extension|TVDB Series ID No

Gui, Add, DropDownList, w250 AltSubmit vNameScheme, (Show Title) - (SS)x(EE) - (Episode Title)|(Show Title) - S(SS)E(EE) - (Episode Title)|(SS)x(EE) - Episode Title||S(SS)E(EE) - (Episode Title)
Gui, Add, DropDownList, x+10 w180 AltSubmit vSeparator, Use spaces as separators|Use.periods.as.separators||Use_underscores_as_separators
Gui, Add, Button, x+150 gButtonGetTVDBInfo, &Get TVDB Info
Gui, Add, Button, x+10 gButtonRename, &Rename files

Gui, Add, Checkbox, xm Checked vZero, Pad with zero?
Gui, Add, Checkbox, x+10 Checked vCache, Cache Episode Info?
Gui, Add, Checkbox, x+10 vRename, Allow Direct Rename?
Gui, Add, Checkbox, x+10 Checked vClear, Clear List after Rename?

Menu, MyContextMenu, Add, Open, ContextOpenFile
Menu, MyContextMenu, Add, Properties, ContextProperties
Menu, MyContextMenu, Add, Remove item, ContextRemoveItem

Gui, Show,, %WindowTitle%
Return

GuiClose:
   ExitApp

GuiContextMenu:
   If A_GuiControl <> MyListView
       Return
   Menu, MyContextMenu, Show, %A_GuiX%, %A_GuiY%
   Return

ContextOpenFile:
ContextProperties:
   FocusedRowNumber := LV_GetNext(0, "F")
   If not FocusedRowNumber
      return
   LV_GetText(FileName, FocusedRowNumber, 1)
   LV_GetText(FileDir, FocusedRowNumber, 3)
   IfInString A_ThisMenuItem, Open
      Run %FileDir%\%FileName%,, UseErrorLevel
   Else
      Run Properties "%FileDir%\%FileName%",, UseErrorLevel
   If ErrorLevel
      MsgBox Could not perform requested action on "%FileDir%\%FileName%".
   return

ContextRemoveItem:
   RowNumber = 0
   Loop
   {
      RowNumber := LV_GetNext(RowNumber - 1)
      If not RowNumber
           Break
      LV_Delete(RowNumber)
   }
   Return

ButtonAddFolder:
   Gui +OwnDialogs
   FileSelectFolder, TargetFolder,, 3, Select a folder:
   If not TargetFolder  ; The user pressed cancel
       Return
   StringRight, LastChar, TargetFolder, 1
   If LastChar = \
      StringTrimRight, TargetFolder, TargetFolder, 1
   GuiControl, -Redraw, MyListView ; Improves performance by disabling redrawing
   Loop %TargetFolder%\*.*
   {
      FileName := A_LoopFileFullPath
      SplitPath, FileName,,, FileExt  ; Get the file extension
      If FileExt in avi,mkv,mp4
         LV_Add(Row, A_LoopFileName, "", A_LoopFileDir, FileExt)
   }
   GuiControl, +Redraw, MyListView  ; Turn redrawing back on
   LV_ModifyCol()  ; Resize each column to fit
   LV_ModifyCol(2, 60)  ; Expand "Preview" to keep the header visible
   LV_ModifyCol(4, 60)  ; Expand "Extension" to keep the header visible
   LV_ModifyCol(5, 110)  ; Expand "TVDB Series ID No" to keep the header visible
   ControlSetText, Edit1, Added folder %TargetFolder%, %WindowTitle%
   Return

ButtonAddFile:
   Gui +OwnDialogs
   FileSelectFile, TargetFile
   If not TargetFile
      Return
   SplitPath, TargetFile,,, FileExt  ; Get the file extension
   If FileExt in avi,mkv,mp4
   {
      SplitPath, TargetFile, FileName, TargetFolder
      LV_Add(Row, FileName, "", TargetFolder, FileExt)
      LV_ModifyCol()  ; Resize each column to fit
      LV_ModifyCol(2, 60)  ; Expand "Preview" to keep the header visible
      LV_ModifyCol(4, 60)  ; Expand "Extension" to keep the header visible
      LV_ModifyCol(5, 110)  ; Expand "TVDB Series ID No" to keep the header visible
      ControlSetText, Edit1, Added file %TargetFile%..., %WindowTitle%
   }
   Return

ButtonClear:
   ClearList()
   Return

ClearList()
{
   TargetFolder =
   TargetFile =
   LV_Delete()
   ControlSetText, Edit1, Cleared Listview, %WindowTitle%
   Return
}

InternetCheckConnection(Url="",FIFC=1) {
   Return DllCall("Wininet.dll\InternetCheckConnectionA", Str,Url, Int,FIFC, Int,0)
}

ButtonGetTVDBInfo:
   GetTVDBInfo()
   Return

GetTVDBInfo()
{
   LV_GetText(LVFileName, 1, 1)
   If not LVFileName
   {
      Gui +OwnDialogs
      MsgBox, 0,Fatal Error!, You must select a file or folder before connecting to TheTVDB.com!
      Return
   }
   LV_GetText(LVFileDir, 1, 3)  ; Get the file directory
   LV_GetText(LVFileExt, 1, 4)  ; Get the file extension

   URL := "http://www.thetvdb.com"

   If not InternetCheckConnection(URL)
   {
      Msgbox, 48, [%URL%]  , Connection Failed!
      Return
   }

   RowNumber = 1
   ShowInfo := GetTVDBShows(GetShowName(LVFileName, LVFileDir))
   StringSplit, ShowArray, ShowInfo, `,
   ShowName = %ShowArray1%
   SeriesIDNo = %ShowArray2%
   Loop
   {
      Gui +OwnDialogs
      If A_Index > 1
      {
         LV_GetText(LVPrevFN, RowNumber - 1, 1)  ; Get the preceeding rows filename
         LV_GetText(LVPrevFD, RowNumber - 1, 3)  ; Get the preceeding rows file directory
         PrevShowName := GetShowName(LVPrevFN, LVPrevFD)
         StringUpper, UpperPrevSN, PrevShowName

         NewShowName := GetShowName(LVFileName, LVFileDir)
         StringUpper, UpperCurrSN, NewShowName
         If UpperCurrSN <> %UpperPrevSN%
         {
            ShowInfo := GetTVDBShows(NewShowName)
            StringSplit, ShowArray, ShowInfo, `,
            ShowName = %ShowArray1%
            SeriesIDNo = %ShowArray2%
         }
      }
      UpperPrevSN =
      SeasonNumber := GetSeasonNumber(LVFileName)
      EpisodeNumber := GetEpisodeNumber(LVFileName)
      OriginalTitle := GetTitle(LVFileName)
      ControlSetText, Edit1, Processing "%ShowName%" Season "%SeasonNumber%" Episode "%EpisodeNumber%", %WindowTitle%
      If SeriesIDNo
      {
         IfInString, ShowName, %A_Space%
            StringReplace, SafeShowName, ShowName, %A_Space%, _, All
         Else
            SafeShowName = %ShowName%
         EpisodeInfo := GetTVDBEpisodes(SeriesIDNo, SeasonNumber, EpisodeNumber, SafeShowName)
         StringSplit, OutputArray, EpisodeInfo, `,
         SeasonNumber = %OutputArray1%
         EpisodeNumber = %OutputArray2%
         EpisodeTitle = %OutputArray3%
         If EpisodeTitle
         {
            StringReplace, EpisodeTitle, EpisodeTitle, \, %A_Space%~%A_Space%, All
            StringReplace, EpisodeTitle, EpisodeTitle, /, %A_Space%~%A_Space%, All
            StringReplace, EpisodeTitle, EpisodeTitle, :, %A_Space%~%A_Space%, All
            StringReplace, EpisodeTitle, EpisodeTitle, *, %A_Space%~%A_Space%, All
            StringReplace, EpisodeTitle, EpisodeTitle, ?,, All
            StringReplace, EpisodeTitle, EpisodeTitle, ", ', All
            StringReplace, EpisodeTitle, EpisodeTitle, <, %A_Space%less than%A_Space%, All
            StringReplace, EpisodeTitle, EpisodeTitle, >, %A_Space%greater than%A_Space%, All
            StringReplace, EpisodeTitle, EpisodeTitle, |, %A_Space%~%A_Space%, All
            StringReplace, EpisodeTitle, EpisodeTitle, &`#44;, `,, All
            StringReplace, EpisodeTitle, EpisodeTitle, &, &, All
         }
         If OriginalTitle
         {
            StringReplace, OriginalTitle, OriginalTitle, \, %A_Space%~%A_Space%, All
            StringReplace, OriginalTitle, OriginalTitle, /, %A_Space%~%A_Space%, All
            StringReplace, OriginalTitle, OriginalTitle, :, %A_Space%~%A_Space%, All
            StringReplace, OriginalTitle, OriginalTitle, *, %A_Space%~%A_Space%, All
            StringReplace, OriginalTitle, OriginalTitle, ?,, All
            StringReplace, OriginalTitle, OriginalTitle, ", ', All
            StringReplace, OriginalTitle, OriginalTitle, <, %A_Space%less than%A_Space%, All
            StringReplace, OriginalTitle, OriginalTitle, >, %A_Space%greater than%A_Space%, All
            StringReplace, OriginalTitle, OriginalTitle, |, %A_Space%~%A_Space%, All
            StringReplace, OriginalTitle, OriginalTitle, &`#44;, `,, All
            StringReplace, OriginalTitle, OriginalTitle, &, &, All
         }
      }
      GuiControlGet, PadZero,, Zero
      If PadZero = 1
      {
         SeasonNumber := PadZero(SeasonNumber)
         EpisodeNumber := PadZero(EpisodeNumber)
      }
      GuiControlGet, NamingScheme,, NameScheme
      If SeasonNumber && EpisodeNumber
      {
         If NamingScheme = 1
         {
            If EpisodeTitle
               NewFileName = %ShowName% - %SeasonNumber%x%EpisodeNumber% - %EpisodeTitle%
            Else If OriginalTitle
               NewFileName = %ShowName% - %SeasonNumber%x%EpisodeNumber% - %OriginalTitle%
            Else
               NewFileName = %ShowName% - %SeasonNumber%x%EpisodeNumber%
         }
         Else if NamingScheme = 2
         {
            If EpisodeTitle
               NewFileName = %ShowName% - S%SeasonNumber%E%EpisodeNumber% - %EpisodeTitle%
            Else If OriginalTitle
               NewFileName = %ShowName% - S%SeasonNumber%E%EpisodeNumber% - %OriginalTitle%
            Else
               NewFileName = %ShowName% - S%SeasonNumber%E%EpisodeNumber%
         }
         Else If NamingScheme = 3
         {
            If EpisodeTitle
               NewFileName = %SeasonNumber%x%EpisodeNumber% - %EpisodeTitle%
            Else If OriginalTitle
               NewFileName = %SeasonNumber%x%EpisodeNumber% - %OriginalTitle%
            Else
               NewFileName = %SeasonNumber%x%EpisodeNumber%
         }
         Else If NamingScheme = 4
         {
            If EpisodeTitle
               NewFileName = S%SeasonNumber%E%EpisodeNumber% - %EpisodeTitle%
            Else If OriginalTitle
               NewFileName = S%SeasonNumber%E%EpisodeNumber% - %OriginalTitle%
            Else
               NewFileName = S%SeasonNumber%E%EpisodeNumber%
         }
      }
      Else
      {
         StringReplace, LVFN, LVFileName, \, %A_Space%~%A_Space%, All
         StringReplace, LVFN, LVFN, /, %A_Space%~%A_Space%, All
         StringReplace, LVFN, LVFN, :, %A_Space%~%A_Space%, All
         StringReplace, LVFN, LVFN, *, %A_Space%~%A_Space%, All
         StringReplace, LVFN, LVFN, ?,, All
         StringReplace, LVFN, LVFN, ", ', All
         StringReplace, LVFN, LVFN, <, %A_Space%less than%A_Space%, All
         StringReplace, LVFN, LVFN, >, %A_Space%greater than%A_Space%, All
         StringReplace, LVFN, LVFN, |, %A_Space%~%A_Space%, All
         StringReplace, LVFN, LVFN, &`#44;, `,, All
         StringReplace, LVFN, LVFN, &, &, All
         StringTrimRight, LVFN, LVFN, 4
         Loop
         {
            StringRight, LastChar, LVFN, 1
            If (LastChar = "-" or LastChar = " ")
               StringTrimRight, LVFN, LVFN, 1
            Else
               Break
         }
         NewFileName = %LVFN%
      }
      GuiControlGet, Sep,, Separator
      If Sep = 2
      {
         StringReplace, NewFileName, NewFileName, %A_Space%, ., All
      }
      Else If Sep = 3
      {
         StringReplace, NewFileName, NewFileName, %A_Space%, _, All
      }
      NewFileName = %NewFileName%.%LVFileExt%
      LV_Modify(RowNumber, Col1, LVFileName, NewFileName, LVFileDir, LVFileExt, SeriesIDNo)
      LV_ModifyCol()
      LV_ModifyCol(4, 60)
      LV_ModifyCol(5, 110)  ; Expand "TVDB Series ID No" to keep the header visible
      LVFileName =
      LVPrevFN =
      ShowArray1 =
      OutputArray1 =
      OutputArray2 =
      OutputArray3 =
      SeasonNumber =
      EpisodeNumber =
      EpisodeTitle =
      OriginalTitle =
      RowNumber := RowNumber + 1
      LV_GetText(LVFileName, RowNumber, 1)  ; Get the filename
      If not LVFileName  ; Break the loop at the end of the list
         Break
      LV_GetText(LVFileDir, RowNumber, 3)  ; Get the file directory
      LV_GetText(LVFileExt, RowNumber, 4)  ; Get the file extension
   }
   ControlSetText, Edit1, Finished querying TheTVDB.com. Ready to rename..., %WindowTitle%
   Return
}

ButtonRename:
   LV_GetText(LVNewFileName, 1, 2)
   If not LVNewFileName
   {
      GuiControlGet, DirectRename,, Rename
      If DirectRename = 1
      {
         GetTVDBInfo()
      }
      Else
      {
         Gui +OwnDialogs
         MsgBox, 0,Fatal Error!, You must scan your files against TheTVDB.com before you rename them!
         Return
      }
   }
   Loop
   {
      RowNumber = %A_Index%
      LV_GetText(LVFileName, RowNumber, 1)  ; Get the original filename
      LV_GetText(LVNewFileName, RowNumber, 2)  ; Get the new filename
      LV_GetText(LVFileDir, RowNumber, 3)  ; Get the file dir
      LV_GetText(LVFileExt, RowNumber, 4)  ; Get the file extension
      If not LVNewFileName  ; Break the loop at the end of the list
         Break
      ControlSetText, Edit1, Renaming "%LVFileName%" to "%LVNewFileName%", %WindowTitle%
      FileMove, %LVFileDir%\%LVFileName%, %LVFileDir%\%LVNewFileName%  ; Finally, rename it
      LV_Modify(RowNumber, Col1, LVNewFileName, "", LVFileDir, LVFileExt, SeriesIDNo)
   }
   RenameCount := RowNumber - 1
   ControlSetText, Edit1, Finished renaming files! Refreshing file list., %WindowTitle%
   GuiControlGet, ClearIt,, Clear
   If ClearIt = 1
   {
      ClearList()
   }
   Else
   {
      GuiControl, +Redraw, MyListView  ; Turn redrawing back on
      LV_ModifyCol()  ; Resize each column to fit
      LV_ModifyCol(2, 60)  ; Expand "Preview" to keep the header visible
      LV_ModifyCol(4, 60)  ; Expand "Extension" to keep the header visible
      LV_ModifyCol(5, 110)  ; Expand "TVDB Series ID No" to keep the header visible
   }
   ControlSetText, Edit1, Finished Successfully!, %WindowTitle%
   Return

;Provide a filename (greek.s01e01.original.title.avi) and this should return the original title (in case a title isn't found)
GetTitle(FileName)
{
   SplitPath , FileName, name, dir, ext, FileName
   IfInString, FileName, .
      StringReplace, FileName, FileName, ., %A_Space%, All
   IfInString, FileName, _
      StringReplace, FileName, FileName, _, %A_Space%, All
   If RegExMatch(FileName, "i)s[0-9][0-9]? ?e[0-9][0-9]?", SeasonAndEpisode)
   {
      StringGetPos, SeasonAndEpisodePos, FileName, %SeasonAndEpisode%
      NumberOfChars := (StrLen(FileName)-(StrLen(SeasonAndEpisode)+SeasonAndEpisodePos))
      StringRight, ShowTitle, FileName, NumberOfChars
   }
   Else If RegExMatch(FileName, "i)[0-9][0-9]?x[0-9][0-9]?", SeasonAndEpisode)
   {
      StringGetPos, SeasonAndEpisodePos, FileName, %SeasonAndEpisode%
      NumberOfChars := (StrLen(FileName)-(StrLen(SeasonAndEpisode)+SeasonAndEpisodePos))
      StringRight, ShowTitle, FileName, NumberOfChars
   }
   Else If RegExMatch(FileName, "[0-9][0-9][0-9][0-9]?", SeasonAndEpisode)
   {
      StringGetPos, SeasonAndEpisodePos, FileName, %SeasonAndEpisode%
      NumberOfChars := (StrLen(FileName)-(StrLen(SeasonAndEpisode)+SeasonAndEpisodePos))
      StringRight, ShowTitle, FileName, NumberOfChars
   }
   Loop
   {
      StringRight, LastChar, ShowTitle, 1
      If (LastChar = "-" or LastChar = " ")
         StringTrimRight, ShowTitle, ShowTitle, 1
      Else
         Break
   }
   Loop
   {
      StringLeft, FirstChar, ShowTitle, 1
      If (FirstChar = "-" or FirstChar = " ")
         StringTrimLeft, ShowTitle, ShowTitle, 1
      Else
         Break
   }
   Return ShowTitle
}

;Provide a filename (s01e01.avi or greek.s01e01.avi) and Directory name (C:\TV\greek) and this should return the show name
GetShowName(FileName, FileDir)
{
   TempName := GetName(FileName)
   If not TempName
      TempName := GetNameFromDir(FileName, FileDir)
   Return TempName
}
;Provide a filename (greek.s01e01.avi) and this should return the show name
GetName(FileName)
{
   SplitPath , FileName, name, dir, ext, FileName
   IfInString, FileName, .
      StringReplace, FileName, FileName, ., %A_Space%, All
   IfInString, FileName, _
      StringReplace, FileName, FileName, _, %A_Space%, All
   If RegExMatch(FileName, "i)s[0-9][0-9]? ?e[0-9][0-9]?", SeasonAndEpisode)
   {
      StringGetPos, SeasonAndEpisodePos, FileName, %SeasonAndEpisode%
      StringLeft, ShowName, FileName, (SeasonAndEpisodePos - 1)
   }
   Else If RegExMatch(FileName, "i)[0-9][0-9]?x[0-9][0-9]?", SeasonAndEpisode)
   {
      StringGetPos, SeasonAndEpisodePos, FileName, %SeasonAndEpisode%
      StringLeft, ShowName, FileName, (SeasonAndEpisodePos - 1)
   }
   Else If RegExMatch(FileName, "[0-9][0-9][0-9][0-9]?", SeasonAndEpisode)
   {
      StringGetPos, SeasonAndEpisodePos, FileName, %SeasonAndEpisode%
      StringLeft, ShowName, FileName, (SeasonAndEpisodePos - 1)
   }
   Loop
   {
      StringRight, LastChar, ShowName, 1
      If (LastChar = "-" or LastChar = " ")
         StringTrimRight, ShowName, ShowName, 1
      Else
         Break
   }
   If SeasonAndEpisodePos > -1
      Return ShowName
   Else
   {
      Return FileName
   }
}

;Provide a filename (s01e01.avi) and Directory name (C:\TV\greek) and this should return the show name
GetNameFromDir(FileName, FileDir)
{
   Directory = %FileDir% - %FileName%
   SplitPath , Directory, NewFileName, dir, ext, name
   Return GetName(NewFileName)
}

;Provide a filename (greek.s01e01.avi) and this should return the season number
GetSeasonNumber(FileName)
{
   If RegExMatch(FileName, "i)s\K[0-9][0-9]?.?e[0-9][0-9]?", SeasonAndEpisode)
   {
      StringSplit, OutputArray, SeasonAndEpisode, e E, .
      SeasonNumber = %OutputArray1%
      IfInString, SeasonNumber, 0
      {
         StringGetPos, ZeroLoc, SeasonNumber, 0
         If ZeroLoc = 0
            StringTrimLeft, SeasonNumber, SeasonNumber, 1
      }

   }
   Else If RegExMatch(FileName, "i)[0-9][0-9]?x[0-9][0-9]?", SeasonAndEpisode)
   {
      StringSplit, OutputArray, SeasonAndEpisode, x X
      SeasonNumber = %OutputArray1%
      IfInString, SeasonNumber, 0
      {
         StringGetPos, ZeroLoc, SeasonNumber, 0
         If ZeroLoc = 0
            StringTrimLeft, SeasonNumber, SeasonNumber, 1
      }
   }
   Else If RegExMatch(FileName, "[0-9][0-9][0-9][0-9]?", SeasonAndEpisode)
   {
      StringTrimRight, SeasonNumber, SeasonAndEpisode, 2
      IfInString, SeasonNumber, 0
      {
         StringGetPos, ZeroLoc, SeasonNumber, 0
         If ZeroLoc = 0
            StringTrimLeft, SeasonNumber, SeasonNumber, 1
      }
   }
   Return SeasonNumber
}

;Provide a filename (greek.s01e01.avi) and this should return the episode number
GetEpisodeNumber(FileName)
{
   If RegExMatch(FileName, "i)s\K[0-9][0-9]?.?e[0-9][0-9]?", SeasonAndEpisode)
   {
      StringSplit, OutputArray, SeasonAndEpisode, e E, .
      EpisodeNumber = %OutputArray2%
      IfInString, EpisodeNumber, 0
      {
         StringGetPos, ZeroLoc, EpisodeNumber, 0
         If ZeroLoc = 0
            StringTrimLeft, EpisodeNumber, EpisodeNumber, 1
      }
   }
   Else If RegExMatch(FileName, "i)[0-9][0-9]?.?x[0-9][0-9]?", SeasonAndEpisode)
   {
      StringSplit, OutputArray, SeasonAndEpisode, x X
      EpisodeNumber = %OutputArray2%
      IfInString, EpisodeNumber, 0
      {
         StringGetPos, ZeroLoc, EpisodeNumber, 0
         If ZeroLoc = 0
            StringTrimLeft, EpisodeNumber, EpisodeNumber, 1
      }
   }
   Else If RegExMatch(FileName, "[0-9][0-9][0-9][0-9]?", SeasonAndEpisode)
   {
      StringRight, EpisodeNumber, SeasonAndEpisode, 2
      IfInString, EpisodeNumber, 0
      {
         StringGetPos, ZeroLoc, EpisodeNumber, 0
         If ZeroLoc = 0
            StringTrimLeft, EpisodeNumber, EpisodeNumber, 1
      }
   }
   Return EpisodeNumber
}

;Provide a show name (greek) and it will return the TVDB data for the show name (Greek) and series ID (80301) as a CSV (Greek,80301)
GetTVDBShows(ShowName)
{
   Global SeriesName, SeriesIDNum
   IfExist, Series_ID.xml
      FileDelete, Series_ID.xml
   UrlDownloadToFile, http://www.thetvdb.com/api/GetSeries.php?seriesname="%ShowName%", Series_ID.xml
   XPath_Load(xml, "Series_ID.xml")
   FileDelete, Series_ID.xml
   SeriesNameNodeCount := XPath(xml, "/Data/Series/SeriesName/Count()")
   If SeriesNameNodeCount = 1
   {
      SeriesIDNum := XPath(xml, "/Data/Series/seriesid/text()")
      SeriesName := XPath(xml, "/Data/Series/SeriesName/text()")
   }
   Else If SeriesNameNodeCount > 1
   {
      SeriesIDNum := XPath(xml, "/Data/Series/seriesid/text()")
      SeriesName := XPath(xml, "/Data/Series/SeriesName/text()")
      SeriesOverview := XPath(xml, "/Data/Series/Overview/text()")
      StringSplit, OutputArraySID, SeriesIDNum, `,
      StringSplit, OutputArraySN, SeriesName, `,
      StringSplit, OutputArraySO, SeriesOverview, `,
      Gui, 2: Default
      Gui, 2: +ToolWindow +Owner1
      Gui, 2: Add, ListView, xm r15 w600, Show name|Show description|TVDB series ID no.
      Gui, 2: Add, Text, y+7
      Gui, 2: Add, Button, x+475, Select
      Gui, 2: Add, Button, x+15, Cancel
      Loop, %SeriesNameNodeCount%
      {
         SeriesIDNum := OutputArraySID%A_Index%
         SeriesName := OutputArraySN%A_Index%
         SeriesOverview := OutputArraySO%A_Index%
         IfInString, SeriesOverview, ,`;
            StringReplace, SeriesOverview, SeriesOverview, ,`;, `,, All
         If not SeriesOverview
            SeriesOverview = (No show description provided)
         LV_Add(Row, SeriesName, SeriesOverview, SeriesIDNum)
         LV_ModifyCol()
         LV_ModifyCol(3, 110)
         SeriesIDNum =
         SeriesName =
         SeriesOverview =
      }
      Gui, 2: Show,,Which Show?
      Gui, 1: Default
      WinWaitClose, Which Show?
   }
   If not SeriesName
      SeriesName = %ShowName%
   J = %SeriesName%,%SeriesIDNum%
   ShowName =
   SeriesIDNum =
   SeriesName =
   SeriesOverview =
   Return J
}

   ;Labels required for Gui 2
   2GuiEscape:
   2GuiClose:
   2ButtonCancel:
   {
      Gui, 2: Destroy
      Return
   }
   2ButtonSelect:
   {
      FocusedRowNumber := LV_GetNext(0, "F")
      If not FocusedRowNumber
      {
         MsgBox, 0, Warning!, You must select a show or press cancel!
         Return
      }
      LV_GetText(SeriesName, FocusedRowNumber, 1)
      LV_GetText(SeriesIDNum, FocusedRowNumber, 3)
      FocusedRowNumber =
      Gui, 2: Destroy
      Return
   }

;Provide the "TVDB series ID", "season number" and "episode number" and this will return the TVDB season number, episode number, and episode title as a CSV (3,1,The Day After)
GetTVDBEpisodes(SeriesIDNum, SeasonNum, EpisodeNum, ShowName)
{
   GuiControlGet, CacheInfo,, Cache
   FileName = data/%ShowName%_%SeasonNum%x%EpisodeNum%.xml
   If CacheInfo = 1
   {
      IfNotExist, FileName
         UrlDownloadToFile, http://www.thetvdb.com/api/563E39CDC7F666DF/series/%SeriesIDNum%/default/%SeasonNum%/%EpisodeNum%/en.xml, %FileName%
      If not XPath_Load(xml, FileName)
         Msgbox, 48, [XPath]  , Load of %FileName% Failed!
   }
   Else
   {
      IfExist, Episode_Info.xml
         FileDelete, Episode_Info.xml
      UrlDownloadToFile, http://www.thetvdb.com/api/563E39CDC7F666DF/series/%SeriesIDNum%/default/%SeasonNum%/%EpisodeNum%/en.xml, Episode_Info.xml
      If not XPath_Load(xml, "Episode_Info.xml")
         Msgbox, 48, [XPath]  , Load of "Episode_Info.xml" Failed!
      FileDelete, Episode_Info.xml
   }
   SeasonNumber := XPath(xml, "/Data/Episode/SeasonNumber/text()")
   EpisodeNumber := XPath(xml, "/Data/Episode/EpisodeNumber/text()")
   EpisodeTitle := XPath(xml, "/Data/Episode/EpisodeName/text()")
   If not EpisodeTitle
   {
      IfExist, %FileName%
         FileDelete, %FileName%
   }
   If not SeasonNumber
      SeasonNumber = %SeasonNum%
   If not EpisodeNumber
      EpisodeNumber = %EpisodeNum%
   K = %SeasonNumber%,%EpisodeNumber%,%EpisodeTitle%
   SeasonNumber =
   EpisodeNumber =
   EpisodeTitle =
   Return K
}

;Pads a variable with a preceeding zero
PadZero(VarToPad)
{
   VarToPadLen := StrLen(VarToPad)
   If VarToPadLen = 1
      VarToPad = 0%VarToPad%
   VarToPadLen =
   Return VarToPad
}

/*
>>>>CHANGELOG<<<<

1.0 (10-5-2009)
   - Original script
1.1 (10-6-2009)
   - Fixed a bug with adding a single file where the file would not be renamed
   -- Forgot to define the TargetFile's TargetFolder when updating the GUI
1.2 (10-13-2009)
   - Fixed another bug with adding a single file where the file would not be renamed
   - Fixed a bug with parsing the series overview where the non-comma delimiter (,) would be displayed
   -- Titans XPath replaces commas with "," (no quotes)
1.30 (11-8-2009)
   - Added a new method of selecting a show name when multiple results are returned
   -- Secondary ListView gui is displayed allowing the user to select the correct show
   - Script now compares the current filename against the previous filename (filenames converted to UPPERCASE)
   -- Drasitically reduces the number of requests against the TVDB and speeds everything up when renaming multiple shows all with the same name
   - Added a check and replace system for invalid filename characters
   -- StringReplace these chars \ / : * ? "" < > | with descriptive replacements
   - Fixed a bug in the GetEpisodeNumber() function
   -- A single digit season number would sometimes cause too few of the episode numbers to be returned when SeasonAndEpisode contained (e|x)
   - Tweaked GetSeasonNumber() and GetEpisodeNumber() to more reliably return correct data
   -- StringGetPos and String(Left|Right) were swapped for StringSplit to more predictably split SeasonAndEpisode regardless of (e|x) char location
   - Added a check to make sure files have a new filename in the preview column before renaming
   - Added a static window title which may be needed for various features in the future as well as making things look nicer :P
1.40 (11-15-2009)
   - Added status bar
   - Fixed a bug where a file would not have a preceeding zero added if no info was found on TheTVDB by adding PadZero() function
   -- Preceeding zero was only added in GetTVDBEpisodes() which means that if SeriesIDNo was blank (i.e. no info pulled from TheTVDB) the Season and Episode number would not get padded
1.41 (12-10-2009)
   - Fixed a serious bug where no results would be returned for ShowName inside the GetTVDBShows function would return the first result infinitely
   -- Had to clear the SeriesName var at the end of the function so that on the next loop iteration the correct var contents would exist
1.42 (12-11-2009)
   - Fixed a minor bug where the second time the GetTVDBInfo button was pressed, the first item in the list view would not actually be rescanned
   -- Had to clear the UpperPrevSN and PrevShowName vars so that the second time the button was pressed it would compare the correct names

>>>>Paradox Changelog<<<<

1.42.1 (2-5-2010)
   - Added new checkbox and supporting code that allows you to save the xmls downloaded in data/%ShowName%_%SeasonNum%x%EpisodeNum%.xml to make future renames quicker.
   -- Added check that determines if you are connected to the internet and thetvdb.com is reachable
   - Added better handling for previous showname
   -- Clean up some code that caused shows to use the previous renamed file settings wrongly
   - Renamed GetShowName(FileName) to GetName(FileName) and added new GetShowName(FileName, FileDir) to implement the following feature without requiring big changes to existing scripts.
   -- Added GetNameFromDir(FileName, Directory) to handle using the directory name as the showname, in case you are renaming files named 01x01 - title.avi the directory must, of course, be named as the show name.
   - Added debug message box if the episode info xml can't be read for some reason.
   -- Fixed Bug where first file would be properly renamed "Castle [2009] - 01x01 - Title" and the rest would be improperly renamed Castle - 01x02 - Title"
   - I am planning to add more features including using the API properly to download All the Episode information for a show and cache it locally/update on a regular basis.
   -- Also Planning to add a feature that will recognize when you are missing episodes from a season and either create a .txt file with the show name, season, episode, and title in the directory, or, keep track of it in a log file of some sort.
1.42.2 (2-5-2010)
   - Added support for choosing if you want to use spaces, periods or underscores as separators
   -- Added A checkbox that allows you to clear the list after renaming, so you don't have to click the button :)
   - Moved some things on the interface around a bit to accommodate previous features.
   -- Fixed an error where the list of files in the directory were being displayed after renaming instead of the previous items, renamed.
   - Added an option that allows you to click on rename and have it do the TVDB lookup and rename all in one (Be careful with this option)
   -- Fix up a few other small bugs
1.42.3 (2-5-2010)
   - Remove Some debug code I forgot to remove before.
   -- Save original title (The part between the 01x01 and the extension), if any to be added back later if no official title is found.
   - Implement better way of refreshing the display after a rename.
1.42.4 (2-5-2010)
   - Fix Typo that would keep files with no . in them at all from being renamed properly. (Exists in original 1.42 script as well)
1.42.5 (2-6-2010)
   - Fix renaming files with no Season and Episode Number (use original filename)
*/


Paradox
  • Members
  • 24 posts
  • Last active: Mar 05 2013 04:15 PM
  • Joined: 05 Feb 2010
I've already done quite a bit of work on this, and, up to this point, most of my changes could be folded back into the original project without making it much different than it was intended to be (most of my changes up to now have been pretty much bug fixes)

My next version will completely go against that, and will change the App so much that it will basically be a different application, so, with the next version I will be creating my own topic here, entering my own API key, changing the name, and Announcing it as my own App based off scene renamer, with credits to strictlyfocused, of course...

I hope someone else out there will find my finished work to be useful to them, but, I know I will be happy, because I will finally have the TV Episode renamer I have looked long and hard for.

strictlyfocused, is, of course, still welcome to include any and all of my changes in his version, if he likes.

Thanks for the start.

Paradox
  • Members
  • 24 posts
  • Last active: Mar 05 2013 04:15 PM
  • Joined: 05 Feb 2010
And, it seems no one cares about this....

Delusion
  • Members
  • 272 posts
  • Last active: Jul 13 2014 09:04 PM
  • Joined: 16 Jul 2008

And, it seems no one cares about this....


i do :D
looking forward to see your own version!
QuickSubs | Popcorn Movie Catalog
All my scripts are just in AutoHotkey v1.0.48.05