Sign in to follow this  
Followers 0
CountryBoy

IMDB Webpage Episode Renamer

6 posts in this topic

An Example Script for Opening and Extracting Web page information.

Eliminates the time consuming task of Copy - Paste of a Web page, and File Re Name.

The script opens I.M.D.B - Internet Movie Data Base Search, Gets Title of TV Series, Season, Episode Number, and

Returns the Title Name and Episode Name for Rename of Selected Episode Files.

; IMDB EPISODE RENAMER 

; FireFox Automation Example Script, free for use : [ CopyRight © 2011 James Moore ] Please give credit for use of, or any parts of.

; ************************************* IMDB EPISODE RENAMER : Internet Movie Data Base Renamer *************************************************
#cs
Searchs IMDB for TV Series Title Name, and gets Epsisode Name to RENAME Selected TV Series Episodes
Opens Search Webpage, User Selects the Title Name, and Season, or Full Episode List, and Folder - Files to Rename
Scans Webpages Title Name for Season - Episode Number to obtain Episode Name for the Selected Files to Rename
RENAME FORMAT : [ Title Name * Season x Episode Number - Episode Name ]    Example : ( Baywatch 03x08 - Princess Of Tides.avi )
-----------------------------------------------------------------------------------------------------------------------------------------------

NOTE: This Program Requires FireFox Browser with MozRepl Addon installed.

MozRepl Addon available from :                                  DOWNLOAD : [ https://github.com/bard/mozrepl/wiki ]
OR Mozilla FireFox Website:
MozLab Version 0.1.8.2007072315 Works with Firefox 1.5 - 3.0a7  DOWNLOAD : [ https://addons.mozilla.org/en-us/firefox/addon/mozlab/ ]
Version 1.1 beta2 1/25/2011 Works with: Firefox 3.0 - 6.*       DOWNLOAD : [ https://addons.mozilla.org/en-US/firefox/addon/mozrepl/versions/ ]

UDF for FireFox automation by Author(s) : Thorsten Willert
FF.au3 Include                                                  DOWNLOAD : [ http://www.thorsten-willert.de/Themen/FFau3/FF.au3/FF.au3?a ]
FFex.au3 Include                                                DOWNLOAD : [ http://www.thorsten-willert.de/Themen/FFau3/FF.au3/FFEx.au3?a ]
For more info see:                                                       : [ http://www.autoitscript.com/forum/topic/95595-ffau3-v0600b/ ]

AUTOIT : To Compile this Script                                 DOWNLOAD : [ http://www.autoitscript.com/site/autoit/downloads/ ]

Another Usefull Tool for File Renaming is Renamer by den4b      DOWNLOAD : [ http://www.den4b.com/?x=downloads ]

-----------------------------------------------------------------------------------------------------------------------------------------------
CopyRight © 2011 James Moore
A Quick done Example Provided Free for Use, Please give Author credit for use of, or any parts of Script.
I love Autoit, An easy and Quick Scripting Language, and I also Write programs in : Pascal, Assembly, C++, Html, some java, and Basic
For more information or questions Contact louisiana.countryboy at Google gmail
#ce
; ***********************************************************************************************************************************************

#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Compression=4
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****

#Include <FF.au3>
#include <FFex.au3>
#Include <Misc.au3>

; ------------------------------------------------------  Set Window Options -----------------------------------------------------
Opt("TrayOnEventMode",0)         ; 0=disable, 1=enable
Opt("WinTitleMatchMode", 2)      ; 1=start, 2=subStr, 3=exact, 4=advanced, -1 to -4=Nocase
Opt("WinDetectHiddenText", 1)    ; 0=don't detect, 1=do detect
Opt("WinTextMatchMode", 2)       ; 1=complete, 2=quick
Opt("WinSearchChildren", 1)      ; 0=no, 1=search 
Opt("MouseCoordMode",1)

Local Const $RenameList = @ScriptDir & "\IMDB-Rename.txt"
Local Const $RenameListTMP = @ScriptDir & "\IMDB-Rename-OLD.txt"

$SeriesName = ""                    ; The Name of the Series of Episodes to Rename, Used as 1st part of filename
$SeasonStr = ""                     ; The Season of the Series Episode List for files to rename
$WebpageSourceCode = ""             ; Html Source Code of IMDB Webpage, used to get NAME of Season - Episode to rename    
$RenameFileFolder = ""              ; Folder path of files selected to rename
$SeasonInList = ""                  ; Global for GetFileListData() to predict Season number if matches found in file list.
$MaxLen = 0                         ; Maximum length of Filenames in Rename List used for formating list
$DoContinue = 6                     ; MsgBox Yes = 6, continue or No 7, Quit Program

; --------------------------------------------------- Window Constants ---------------------------------------------------------
Local Const $ttX = ((@DesktopWidth / 3) * 2)                      ; Tool Tip X Position = Two-Thirds of Screen Width
Local Const $ttY = 4                                              ; Tool Tip Y Position

; -------------------------------------------------- Check if Page Load Error -------------------------------------------------
; Firefox can't find the server at (or) Problem loading Page   <title>Problem loading page</title>

Func CheckLoadError()
     ToolTip("", $ttX, $ttY)
     ToolTip(" Check Page Load Error ", $ttX, $ttY)
     Sleep(200)
     _FFLoadWait()
     If ((WinExists ( "Problem loading page" )) Or (WinExists ( "find the server at" )) Or (WinExists ( "Server not found" ))) Then
         _FFAction("Reload","LOAD_FLAGS_NONE")             ; Reload the Page
         _FFLoadWait()
         Sleep(2000)                                       ; Wait 2 seconds
         ToolTip("", $ttX, $ttY)
         Return 1
     EndIf   
     Sleep(200)
     ToolTip("", $ttX, $ttY)
     Return 0    
 EndFunc

; ------------------------------------------------ WINDOW WAIT SECONDS -----------------------------------------------------
; Wait Seconds Untill Opening or webpage Window exists

Func WinWaitSeconds($WaitSec)   
     If Not WinExists ("[CLASS:MozillaWindowClass]") Then                                            ; USER CLOSED FIREFOX BROWSER SO QUIT
         ToolTip("", $ttX, $ttY)
         Exit(0)
     EndIf  
     For $i = 0 to $WaitSec -1 Step 1
         ToolTip(" Wait On Window: " & ($WaitSec - $i) & " Seconds ", $ttX, $ttY)
         Sleep(1000)
     Next
     ToolTip("", $ttX, $ttY)
 EndFunc
 
; ------------------------------------------------ WINDOW WAIT MINUTES -----------------------------------------------------
; Wait Minutes Untill Opening or webpage Window exists

Func WinWaitMinutes($MsgStr, $WaitMin)  
     For $i = 0 to $WaitMin - 1 Step 1
         ToolTip($MsgStr & "  " & ($WaitMin - $i) & " Minutes ",(@DesktopWidth / 2), $ttY)
         If Not WinExists ("[CLASS:MozillaWindowClass]") Then                                        ; USER CLOSED FIREFOX BROWSER SO QUIT
             ToolTip("", (@DesktopWidth / 2), $ttY)
             Exit(0)
         EndIf  
         Sleep(60000)     ; Wait 1 Minute
     Next
     ToolTip("", (@DesktopWidth / 2), $ttY)
 EndFunc

; ---------------------------------------------------- Func Do Quit Close Firefox and Exit -----------------------------------------------------
Func DoQuit()
     _FFQuit()
     Exit(0)
EndFunc

; ----------------------------------------------------------- Ask User if want to Quit ---------------------------------------------------------
Func Ask2Quit()
         $Quit = MsgBox (4, "QUIT PROGRAM", "Do you want to Quit Program ?")
         If ($Quit <> 6) Then Return
         DoQuit()
 EndFunc
 
 ; ------------------------------------------------------- Return True if Esc Key Pressed -------------------------------------------------------
 Func EscKeyPressed()
     If _IsPressed("1B") Then
         Return True
     Else
         Return False        
     EndIf   
 EndFunc

; ------------------------------------------- Get String in a String or in Text Stream -------------------------------------------
; Returns STRING: Searchs for ( SearchStr ) as starting Position to Search for ( Str 2 Find Start )
; ( Search Str Past End ) is String Past String2Find and is the Count of Chars to get. ; Webpage Search: Example: $Str2Search = _FFReadText(7)

Func GetStrInStr($Str2Search, $SearchStr, $Str2FindStart, $StrPastStr2FindEnd)                     
     $ItemPos = StringInStr($Str2Search,$SearchStr)
     If $ItemPos > 0 Then                                                                            ; Didn't find Search String Return ""
         $StringStart = StringInStr($Str2Search,$Str2FindStart,2,1,$ItemPos)
         If $StringStart > 0 Then                                                                    ; Didn't find Str2FindStart Return ""
              If ($StrPastStr2FindEnd = "") and (StringLen($Str2Search) >= $StringStart) Then        ; Get whole string if no char past end
                 $StringEnd = StringLen($Str2Search)+1
             Else
                 $StringEnd = (StringInStr($Str2Search,$StrPastStr2FindEnd,2,1,$StringStart))
             EndIf
              If ($StringEnd > 0) and ($StringEnd > $StringStart) Then                                ; No "", At Least one Char    
                 $Str2Return = StringMid ( $Str2Search, $StringStart ,($StringEnd - $StringStart))    
                 $Str2Return = StringStripWS ( $Str2Return, 2 )
                 $Str2Return = StringReplace ( $Str2Return, '"',"")                                   ; Remove any Quotes "" or ''
                 $Str2Return = StringReplace ( $Str2Return, "'","")
                 Return $Str2Return
             EndIf
         EndIf
     EndIf  
  Return ""
EndFunc

; **************************************************************************************************************************************
; Searchs IMDB Webpage Source Code and Returns ( Episode Name ) of Selected Season and Episode Number

Func GetImdbEpisode( $ImdbSeason, $ImdbEpisode)
     ToolTip("", $ttX, $ttY)
     ToolTip(" Geting Episode Name ", $ttX, $ttY)
     $EpisodeName = StringReplace(GetStrInStr( $WebpageSourceCode, "Season " & $ImdbSeason & ", Episode " & $ImdbEpisode & ":", ">", "<"),">","")
                                                                                                  ; MsgBox(64, "TEXT Episode 2 IS",  $EpisodeName)
     $EpisodeName = StringRegExpReplace($EpisodeName, "[\\\-\_\.\,\(\)\!\{\}\+\=\?\#\~\<\>\'\|\`\/\%\^\*\@\;\:]", "")
     $EpisodeName = StringReplace ($EpisodeName,'"',"")
     $EpisodeName = StringReplace($EpisodeName,"&","And")
     $EpisodeName = StringStripWS ( $EpisodeName, 1 )
     $EpisodeName = StringStripWS ( $EpisodeName, 2 )
     $EpisodeName = StringStripWS ( $EpisodeName, 4 )
     Return $EpisodeName
     ToolTip("", $ttX, $ttY)
EndFunc

; --------------------------------------------------- Get Episode String Starting Position -------------------------------------------------------
; Searches FileName List String to ( skip Leading Numbers ), and Predict Search Starting Position of Season - Episode Divider - Episode Number
                 ; Mode 1: Season Match, and Episode divider: x or e found
                 ; Mode 2: Season Match, and any Episode divider Found
                 ; Mode 3: Episode divider: x or e found, and Preceding Char OldTmpS is an Integer, but not Season Match
                 ; Mode 4: Unknown Episode Divider Found, and Preceding Char OldTmpS is an Integer, but not Season Match
                 ; Mode 5: Season Match found only, and no divider found

Func GetEpisodeStringStartPosition($sInput,$Season2Get,$Mode)
    $TmpS = ""
    $OldTmpS = ""
    $OlderTmpS = ""
    $EpDivStrPos =  1                                                                       ; Return Default Start at Char 1 Position
    $SeasonTmp = ""

    $SLen = StringLen($sInput)
    For $i = 1 to $SLen
         $SeasonTmp =  ""
         $TmpS = StringMid($sInput,$i,1)
         If (StringIsInt($OlderTmpS)) Then  $SeasonTmp =  $OlderTmpS
         If (StringIsInt($OldTmpS)) Then  $SeasonTmp =  $SeasonTmp & $OldTmpS    
         If $SeasonTmp < 10 then $SeasonTmp = StringReplace($SeasonTmp, "0","",1,0)         ; Remove leading 0
         If ($Mode = 5) and ($SeasonTmp = $Season2Get)  Then ExitLoop                       ; Found Season, Search sting to end skip last char
         If Not StringIsInt($TmpS) then                                                     ; may have found episode divider
             If ($i < $SLen) Then                                                           ; look ahead 1 char
                 If StringIsInt($OldTmpS) and StringIsInt(StringMid($sInput,$i+1,1)) Then
                     Select
                        Case $Mode = "1"
                             If ($SeasonTmp = $Season2Get) and (($TmpS = "x") or ($TmpS = "e")) Then ExitLoop
                         Case $Mode = "2"
                             If ($SeasonTmp = $Season2Get) Then ExitLoop
                         Case $Mode = "3"
                             If (($TmpS = "x") or ($TmpS = "e")) And (StringIsInt($OldTmpS)) Then ExitLoop
                         Case $Mode = "4"
                             If (StringIsInt($OldTmpS)) Then ExitLoop
                     EndSelect      
                 Endif   
             EndIf
         Endif   
         $OlderTmpS = $OldTmpS
         $OldTmpS = $TmpS                                                                  ; look behind 1 space or last char
     Next

     If $i = $SLen +1 Then                                                                 ; Reached end of string loop count i + increment 1
         $EpDivStrPos = 1                                                                  ; at end of string and didn't find it set start to 1
     Else
         If StringIsInt($OlderTmpS) Then                                                   ; If 2nd char before divider is Integer
             $EpDivStrPos = $i -2                                                          ; start search 2 spaces back                                 
         Else
             $EpDivStrPos = $i -1                                                          ; only 1 integer before episode divider  
         Endif  
     EndIf
     Return $EpDivStrPos
EndFunc 

; ------------------------------------------------------------ GET EPISODE NUMBER --------------------------------------------------------
; Searchs String of Selected Season - Episode List and Returns the Episode Number, Calls GetEpisodeStringStartPosition() to skip leading digit
; Season-Episode Divider Formats : s01e09, 01x09, 01e09, 0109, 1x09, 01x9, 1x9, 19
; Also Returns : Global $SeasonInList for GetFileListData() to predict Season of Files in List to Rename if IMDB Full Episode List Choosen

Func GetEpisodeNumber( $sInput, $Season2Get)
    $TmpS = ""
    $S1 = ""
    $S2 = ""
    $E1 = ""
    $E2 = ""
    $EpDiv = ""
    $IntCount = 0
    $NonIntCount = 0
    $EpDivGroupPosition =  0
    $SeasonInList = ""                                                           ; Global to Predict FileList season $SeasonInList = ""
    $sOutput = ""
    
     For $j = 1 to 5                                                             ; For Search Depth Mode 1 to 5
         $StartPos = GetEpisodeStringStartPosition($sInput,$Season2Get,$j)       ; Check all 5 posible string search start positions
         If $StartPos > 1 Then ExitLoop                                          ; Found String search Starting Position
     Next
     
    $SLen = StringLen($sInput)

    For $i = $StartPos to $SLen
         $TmpS = StringMid($sInput,$i,1)
         If StringIsInt($TmpS) then                                     ; Found an Integer in the String
             $IntCount = $IntCount +1                                   ; Keep count of Integers found in string             
             If ($i+1 < $SLen) and ($S1 = "") Then                      ; Check if found Group of Integers, not a single number before group
                 If not (StringIsInt(StringMid($sInput,$i+1,1)) or StringIsInt(StringMid($sInput,$i+2,1))) Then $IntCount = 0
             EndIf   
             If ($IntCount = 1) and ($S1 = "") Then                     ; Found 1st Integer of Group in String
                 $S1 = $TmpS
                 $NonIntCount = 0                                       ; Zero or Start the Non Integer count in Group
             EndIf
             If ($IntCount = 2) and ($S2 = "") Then $S2 =  $TmpS        ; Get 2nd Integer in Group
             If ($IntCount = 3) and ($E1 = "") Then $E1 =  $TmpS        ; Get 3rd Integer in Group
             If ($IntCount = 4) and ($E2 = "") Then $E2 =  $TmpS        ; Get 4th Integer in Group
         Else
             If ($S1 <> "") and $NonIntCount > 1 Then ExitLoop          ; Group End: no more integers, found episode divider, and none integer
             If ($S1 <> "") Then $NonIntCount = $NonIntCount +1         ; if group of integers found then keep count of any non-integers
             If ($NonIntCount > 0) and ($EpDiv = "") Then
                 $EpDiv = $TmpS                                         ; Get the Episode divider char found in group of integers
                 $EpDivGroupPosition = $IntCount+1                      ; Get Episode divider position in group of integers
             EndIf   
         Endif
     Next
    
    If ($IntCount = 3) and ($EpDivGroupPosition <> 3) Then             ; Only 3 DIGITS IN STRING Swap Season and Extention       
         $E2 =  $E1                                                    ; but, don't swap if season has 2 digits & Episode has 1 : ( 12x3 )
         $E1 = $S2
         $S2 = ""
     EndIf   
      If ($IntCount = 2) Then                                          ; ONLY 2 DIGITS IN STRING must be a single digit of season and Episode
         $E2 =  ""
         $E1 = $S2
         $S2 = ""
     EndIf   
         
     If $Season2Get < 10 then $Season2Get = StringReplace($Season2Get, "0","",1,0)        ; Remove Leading 0 if < 10
     
     $SeasonTmp =  $S1 & $S2
     If $SeasonTmp < 10 then $SeasonTmp = StringReplace($SeasonTmp, "0","",1,0)           ; Remove Leading 0 if < 10
     $SeasonInList = $SeasonTmp                                                           ; Get Global $SeasonInList for GetFileListData()
     
     If ($Season2Get = $SeasonTmp) Then                                                   ; FOUND Episode Number for Season Selected
         $sOutput = $E1 & $E2
         If $sOutput < 10 then $sOutput = StringReplace($sOutput, "0","",1,0)             ; Remove leading 0 if < 10
     EndIf
     Return $sOutput
EndFunc ; GetEpisodeNumber()

; ------------------------------------------------------- Create Rename list of Files ----------------------------------------------------------
; Create Rename List, Saves IMDB-Rename.txt as IMDB-Rename-OLD and Re-Creats a New Modified IMDB-Rename.txt
; Calls GetEpisodeNumber() & GetImdbEpisode() To get Episode Name for Selected Season, Formats New Line String AND Saves to Rename List

Func CreateRenameList()
     ToolTip("", $ttX, $ttY)
     ToolTip("Creating Episode Rename List ", $ttX, $ttY)       
         
If FileExists ($RenameList) then                                                          ; Check if IMDB-Rename.txt exists
     FileMove ( $RenameList, $RenameListTMP , 1 )                                         ; SAVE IMDB-Rename.txt AS IMDB-Rename-Old.txt
     If Not FileExists ($RenameList) then                                                 ; Check if IMDB-Rename.txt was Renamed
         If FileExists ($RenameListTMP) then                                              ; And New File Name EXISTS
         $File = FileOpen($RenameListTMP, 0)                                              ; Open the Renamed Origional
         If $File = -1 Then Exit                                                          ; if file opened for reading ERROR EXIT
         While 1                                                                          ; Read in lines of text until the EOF is reached
             $line2Add = FileReadLine($File)                                              ; Get a line of text
             If @error = -1 Then ExitLoop
             If (StringInStr($line2Add,"Check - Edit",0)= 0) and (StringInStr($line2Add,"Folder=",0)= 0) Then
                 $GetEpNum = GetEpisodeNumber($line2Add, $SeasonStr)                                    ; MsgBox(0, "GetEpNum ",  $GetEpNum)
                 $EpName = GetImdbEpisode($SeasonStr, $GetEpNum)                                        ; MsgBox(0, "Episode Name ",  $EpName)
                     
                 If $EpName <> "" Then          
                     $Season = $SeasonStr                                                               ; Format String for File List add 0         
                     If ($Season < 10) And (StringInStr($Season,"0")=0) Then $Season = "0" & $Season 

                     $EpNum = $GetEpNum                                                                 ; FILE FORMAT $EpNum ADD leading 0
                     If ($EpNum < 10) AND  (StringInStr($EpNum, "0") = 0) Then $EpNum = "0" & $EpNum    ; MsgBox(0, "THE Episode Number 2 ADD ", $GetEpNum)
                     
                     $StrEnd = StringRight($line2Add, 5 )                                               ; Get last four char at end of string
                     $StrExt = StringReplace(GetStrInStr( $StrEnd, ".", ".", ""),".","")                ; Get the String filename extension
                     
                     $Newline2Add = $line2Add                                                           ; Justify - Format Filename string for list
                     $Newline2Add = StringFormat("%-"& $MaxLen & "s", $Newline2Add)                     ; Pad end of string with spaces
                     $Newline2Add = $Newline2Add & ">   " & $SeriesName & " " & $Season & "x" &  $EpNum & " - " & $EpName & "." & $StrExt
                                                                                            ; MsgBox(0, "New Line 2 ADD ",  $Newline2Add)
                     FileWriteLine($RenameList, $Newline2Add)                               ; MsgBox(0, "WRITE THE STRING Line 2 ADD ", $line2Add) 
                 Else 
                     FileWriteLine($RenameList, $line2Add)                                  ; MsgBox(0, "Write Unchanged line: ", $line2Add)
                 EndIf
             Else
                 FileWriteLine($RenameList, $line2Add)                                      ; MsgBox(0, "Write Unchanged line: ", $line2Add)
             EndIf                                                                          ; END OF : If (StringInStr($line2Add
         Wend
             FileClose($file)
         EndIf                                                                              ; END OF $GetEpNum <> "" 
     Else
          MsgBox(0, "ERROR : Saving File", $RenameList)
     EndIf                                                                                  ; END OF : If Not FileExists ($RenameList)
Else   
     MsgBox(0, "File not Found", $RenameList)
EndIf                                                                                      ; END OF : If FileExists ($RenameList) then 
     ToolTip("", $ttX, $ttY)
EndFunc

; -------------------------------------------------- GET  FileListData : Open List Read in names ------------------------------------------
; Get format Length of longest Line in FileRename List, Get Path to $RenameFileFolder, and Predict Season from FileName of the Rename list
; Calls GetEpisodeNumber to Get Global $SeasonInList to Predict Season of FileNames in Rename List if Full Episode List was Choosen

Func GetFileListData()
     $GotFileListData = False
     ToolTip("", $ttX, $ttY)
     ToolTip(" Checking Rename List ", $ttX, $ttY)
     $OlderSTmp = ""
     $OldSTmp = ""
     $STmp = ""
     $TmpLen = 0
 If FileExists ($RenameList) then
     $File = FileOpen($RenameList, 0)
     If $File = -1 Then Exit                                                                         ; If file OPEN ERROR - EXIT
     While 1                                                                                         ; Read in lines until EOF is reached
         $GotFileListData = False
         $line2DL = FileReadLine($File)
         If @error = -1 Then ExitLoop
         If (StringInStr($line2DL,"Check - Edit",0)= 0) Then 
             If (StringInStr($line2DL,"Folder=",0)<> 0) Then
                 $RenameFileFolder = StringReplace (GetStrInStr($line2DL, "Folder=", "=", ""),"=","")     
                 ; MsgBox(0, "Rename File Folder",  $RenameFileFolder)
             Else                                                                                             ; List of filenames only
                 GetEpisodeNumber($line2DL, "")                                                               ; Get at least 3 with same season
                 If StringIsInt($SeasonInList) Then $STmp = $SeasonInList                                     ; to predict season of list
                 If ($SeasonStr = "") and ($STmp <> "") and ($STmp = $OldSTmp) and ($STmp = $OlderSTmp) Then 
                     $SeasonStr = $STmp
                 Endif               
                 If StringLen($line2DL) >  $TmpLen Then $TmpLen = StringLen($line2DL)                    ; Get length of longest filename in list
             EndIf
         EndIf
         $OlderSTmp = $OldSTmp
         $OldSTmp = $STmp
     Wend
     FileClose($file)
 Else    
     MsgBox(0, "File not Found : List of IMDB Episodes", $RenameList)
 EndIf
     $MaxLen = $TmpLen  + 3                                                                            ; Return Maximum String Length 
     ToolTip("", $ttX, $ttY)
     If ($RenameFileFolder <> "") Then $GotFileListData = True                                         ; Return True if list exists
     Return $GotFileListData
EndFunc

; -------------------------------------------- Get List of Files to Rename and Create Rename List -----------------------------------------------
Func GetFileList() 
 ToolTip("", $ttX, $ttY)
 ToolTip(" Select Files to Rename ", $ttX, $ttY)    

$message = "Select Files:  Hold Ctrl or Shift : Mouse or Arrow Keys for multiple files."          ; Multiple filter group
; File Type Filter
$F1 =  "Videos (*.avi;*.wmv;*.divx;*mpg;*.mkv;*flv;*.ogg;*.ogm;*.ogv;*.f4v;*.mov;*.mp4;*.mpe;*.m4v;*.mpv;*.m1v;*.dat;*vob;"
$F2 = "*asf;*.qt;*.3gp;*.3g2;*.m4v;*.rm;*.rmvb;*.m2ts;*.mts;*.tod;*.vro;*.dv;*.amv;*.ts;*.tp;*.m2t;*.dvr-ms;*.m)|All Files(*.*)"
$var = FileOpenDialog($message, "", $F1 & $F2, 1 + 4 )

If @error Then
     MsgBox(4096,"Exit Program","    No File(s) chosen ...    ")
     DoQuit()
Else
     $var = StringReplace($var,"|","||",1)
     $var = StringReplace($var, "|", @CRLF)                                                      ; MsgBox(4096,"","You chose " & $var)
    
     $File = FileOpen($RenameList, 2)                                                            ; Open the Rename list
     If $File = -1 Then Exit                                                                     ; if file opened for reading ERROR EXIT
     FileWriteLine($RenameList, "Check - Edit File Names - Save ... Close NotePad [x] to Continue" & @CRLF & @CRLF)
     FileWriteLine($RenameList, "Folder=" & $var) 
     FileClose($file)
EndIf
     ToolTip("", $ttX, $ttY)
EndFunc
 
; -------------------------------------------- Use NotePad to CHECK - EDIT - SAVE FILE RENAME LIST --------------------------------------------
; Uses Windows NotePad to View and Edit Rename List before Renaming Files

Func EditRenameList()
     ToolTip("", $ttX, $ttY)
     ToolTip(" Check - Edit Rename List ", $ttX, $ttY)
     $SaveNow = 7
     RunWait(@ComSpec & " /c " & $RenameList, FileGetShortName(@ScriptDir,1),@SW_HIDE )  
     While ($SaveNow = 7)
         $SaveNow = MsgBox (3, "RENAME FILES", "[ Yes ] = RENAME   [ No ] = View - Edit   [ Cancel ] = Quit")
             Select
                Case $SaveNow = 6                                                          ; Check if user clicked on the "Yes" button
                     Return True
                 Case $SaveNow = 7                                                         ; Check if user clicked on the "No" button
                     RunWait(@ComSpec & " /c " & $RenameList, FileGetShortName(@ScriptDir,1),@SW_HIDE )  
                 Case $SaveNow = 2                                                         ; Check if user clicked on the "CANCEL" button
                     Return false
             EndSelect      
         Wend
     ToolTip("", $ttX, $ttY)                                                                       
  EndFunc
 
; ------------------------------------------------------ Get Season of Series Title Name --------------------------------------------------
; Gets Season from Webpage link URL, or from Getfilelistdata's scan of filelist to get Predicted Season, or Ask's user if not available

Func GetSeason()
     ToolTip("", $ttX, $ttY)
     ToolTip(" SEASON of Episode List ", $ttX, $ttY)
     $TmpStr = ""
     If $SeasonStr = "" Then
         $SrcLink = _FF_GetCurrentURL()                                                                       ; MsgBox(0, "SrcLink", $SrcLink)
         If StringInStr( $SrcLink,"episodes#") > 0 then                       ; example: http://www.imdb.com/title/tt0073972/episodes#season-2
             $TmpStr = StringReplace(GetStrInStr( $SrcLink, "episodes#season", "-", ""),"-","")
         Endif   
         If StringIsInt($TmpStr) Then
             $SeasonStr = $TmpStr
             Else
                 While not StringIsInt($SeasonStr)
                     If not StringIsInt($TmpStr) then $TmpStr = "1"
                     $SeasonStr = InputBox ( "IMDB Episode List SEASON", "Enter Season for IMDB Episode List", $TmpStr,"",375,150) 
                     If @error Then DoQuit()
                 Wend
         EndIf
     EndIf  
     ToolTip("", $ttX, $ttY)
EndFunc

; ---------------------------------------------------------- Get Series Name ---------------------------------------------------------------
; Reads Webpage SourceCode to get SERIES NAME for Formated Name in File Rename List, if unable to get then ASK USER

Func GetSeriesName()
     ToolTip("", $ttX, $ttY)
     ToolTip(" Get Season Name ", $ttX, $ttY)
     $sTitle = _FFCmd(".title")                                                   ; MsgBox(0, "Series NAME",  $sTitle) 
     $Series = StringLeft($sTitle, StringInStr($sTitle, '"',0,2 )) 
     $Series = StringReplace($Series,'"',"")
     $Series = StringReplace($Series,"&","And")
     $Series = StringRegExpReplace($Series, "[\\\-\_\.\,\(\)\!\{\}\+\=\?\#\~\<\>\'\|\`\/\%\^\*\@\;\:]", "")
     If StringInStr($Series,":") > 0 Then
        $Series = GetStrInStr( $Series, $Series, $Series, ":")                    ; Get short Version of Series Name
     Endif
     If $Series = "" Then
         $Series = InputBox ( "Get Series NAME", "Enter Series NAME for IMDB Episode List", $Series,"",375,150) 
         If @error or ($Series = "") Then DoQuit()
     EndIf      
     $SeriesName =  $Series                                                       ; MsgBox(0, "Series NAME fixed",  $SeriesName)
     ToolTip("", $ttX, $ttY)
 EndFunc    
 
 ; ------------------------------------------------------------ RENAME FILES -------------------------------------------------------------------- 
 ; Open Rename List, ask user if want to rename, and Rename the Selected Files, Report Count of Errors and count of Files Renamed
 
Func RenameFiles()
     $FileCount = 0
     $ErrorCount = 0
     ToolTip("", $ttX, $ttY)
     ToolTip(" Rename Files ", $ttX, $ttY)      
     $SaveNow = MsgBox (1, "Confirm Rename Files", "Do you want to Rename Files ?")
     If  $SaveNow <> 1 Then DoQuit()

If FileExists ($RenameList) then                                                      ; Check if IMDB-Rename.txt exists
     $File = FileOpen($RenameList, 0)                                                 ; Open Rename list
     If $File = -1 Then Exit                                                          ; if file opened for reading ERROR EXIT
     While 1                                                                          ; Read in lines of text until the EOF is reached
         $line2Ren = FileReadLine($File)                                              ; Get a line
         If @error = -1 Then ExitLoop
         If ($line2Ren <> "") and (StringInStr($line2Ren,"Check - Edit",0)= 0) and (StringInStr($line2Ren,"Folder=",0)= 0) Then
             $EpFileName = StringStripWS(StringStripWS(StringReplace(StringLeft($line2Ren, StringInStr($line2Ren,">")),">",""),1),2)
             $EpFileName = $RenameFileFolder & "\" & $EpFileName                      ;  MsgBox(0, "Episode File to Rename", $EpFileName)
             $NewFileName = StringStripWS(StringStripWS(StringReplace(GetStrInStr( $line2Ren, ">", ">", ""),">",""),1),2)
             $NewFileName = $RenameFileFolder & "\" & $NewFileName                    ; MsgBox(0, "New File Name to Rename File", $NewFileName)
             If FileExists($EpFileName) Then                                          ; MsgBox(0, "File Exists", $EpFileName)
                 FileMove ( $EpFileName, $NewFileName , 0 )  
                 $FileCount = $FileCount + 1                                          ; Increment Files Done
                 If Not FileExists($NewFileName) Then $ErrorCount = $ErrorCount + 1   ; Increment Error Count
             Else
                 MsgBox(0, "ERROR: File Not Found", $EpFileName)                 
             EndIf 
         Endif
     Wend
             FileClose($file)
             If $ErrorCount > 0 Then  MsgBox(0, "FILE RENAME : ERROR", "( " & $ErrorCount & " )  Files were not Renamed")
             If $FileCount > 0 Then  MsgBox(0, "FILE RENAME : SUCESS", "( " & $FileCount & " )  Files were Renamed")
Else 
         MsgBox(0, "File not Found", $RenameList)
EndIf  
         ToolTip("", $ttX, $ttY)
EndFunc

; ----------------------------------------------------- Open IMDB SEARCH WEBPAGE --------------------------------------------------------------
; Open IMDB Webpage Search, Get Title Name, Get Season to Rename, or Full Episode List, If Error Ask user for Search Link, Esc Key = Quit
; Searchbar: /html/body/div[1]/div[2]/layer/div[1]/div[2]/form/div/input ; id="navbar-query"  name="q" ; BUTTON Go class="nb_primary" type="submit"

Func ImdbSearch()
     $ImdbLink = "http://www.imdb.com/search/"
     
     ToolTip("", $ttX, $ttY)
     ToolTip(" Opening IMDB Search ", $ttX, $ttY)
     _FFOpenURL($ImdbLink)                                                                          ; Open IMDB Search Webpage
     CheckLoadError()
     $SrcLink = _FF_GetCurrentURL()  
     
     If (StringInStr( $SrcLink,$ImdbLink)= 0) Then                                                 ; Error Loading search ask user
         $SrcLink = InputBox( "ERROR LOADING IMDB SEARCH", "Enter Link : IMDB Title Name Search", $ImdbLink,"",375,150) 
         If @error or ($SrcLink = "") Then DoQuit()
        
         If (StringInStr( $SrcLink,"imdb.com")<> 0) Then                                           ; Open user Provided Link
             ToolTip("", $ttX, $ttY)
             ToolTip(" Opening IMDB Website ", $ttX, $ttY)
             _FFOpenURL($SrcLink)
             CheckLoadError()
         EndIf           
     EndIf
     
     ToolTip("", $ttX, $ttY)                                                                       ; Show Help Information
     ToolTip(" Search Series Title Name ", $ttX, $ttY)
     MsgBox (0, 'IMDB EPISODE RENAMER SEARCH', "Search for TV Series Title [ NAME ]  and  Select [ SEASON ] ... Hold Esc Key to Quit" ,5 )
     ToolTip("", $ttX, $ttY) 
      
     MouseMove ( (@DesktopWidth / 2)-120, (@DesktopHeight / 5) )                                   ; move mouse near Search Bar at top
     While 1 
         $SrcLink = _FF_GetCurrentURL()                                                            ; Get Webpage link Address
         If (StringInStr( $SrcLink,"imdb.com/find?s=all") <> 0) Then                              
             ToolTip(" Select a Title from List ")                                                 ; List : Page of titles to select
         Else    
             ToolTip(" Search - Series Title Name & Click [ Go ]")                                 ; Blink help at mouse pointer                  
         EndIf
         Sleep(500)
         ToolTip("")
         If (StringInStr( $SrcLink,"/title/") <> 0) Then ExitLoop                                  ; Title Selected Go get season    
         Sleep(250)
         If Not WinExists("[CLASS:MozillaWindowClass]") Then DoQuit()                              ; Firefox window closed
         If EscKeyPressed() Then Ask2Quit()                                                        ; If user pressed Esc Ask if Quit
     WEnd
        
     MouseMove ( (@DesktopWidth / 4), @DesktopHeight - (@DesktopHeight / 5) )                     ; Move mouse near Seasons at bottom
     While 1
         $SrcLink = _FF_GetCurrentURL()                                                            ; Get Webpage link Address
         ToolTip(" Select Season or Full Episode List")
         Sleep(500)
         ToolTip("")
         If (StringInStr( $SrcLink,"episodes") <> 0) Then ExitLoop                                 ; Season or Full Episode list selected
         Sleep(250)
         If Not WinExists("[CLASS:MozillaWindowClass]") Then DoQuit()                              ; Firefox window closed
         If EscKeyPressed() Then Ask2Quit()                                                        ; If user pressed Esc Ask if Quit
     WEnd
EndFunc 

 ; *********************************************************** MAIN BODY OF PROGRAM **********************************************************

ToolTip(" Starting FireFox ", $ttX, $ttY)
_FFStart()       
$Socket =  _FFConnect()

If _FFIsConnected() Then                                                                           ; If MozRepl AddOn and firefox connected
     ToolTip(" Maximize ", $ttX, $ttY)                                                             ; Maximize Window
     _FFAction("Maximize")

While ($DoContinue = 6)                                                                            ; User Selected Continue in Msgbox
    GetFileList() 
    ImdbSearch()                                                                                  ; Open search get title & season
     GetFileList()                                                                                 ; Get User Selected list of files to rename
     $WebpageSourceCode = _FFReadHTML()                                                            ; Read Webpage Html Source Code
         
     If GetFileListData() Then                        ; GetFileListData -- Check file exists, Get format info & Predict season from filelist 
         GetSeason()                                  ; Check if season needed, use GetFileListData Predicted Season, or Ask User
         GetSeriesName()                              ; Get Series Name from Webpage to format File Rename list, or ask User
         CreateRenameList()                           ; Scan WebpageSourceCode & File List: for Episode Name, and Create Rename List
         If EditRenameList() Then RenameFiles()       ; User Verify or Edits List, and Asks if want to Rename
         ToolTip("", $ttX, $ttY)
     Else   ; --------------------------------------------- File Not Found ERROR ----------------------------------------------------
             MsgBox(0, "File Not Found", "List of Files to Rename : Imdb - Rename.txt")
            
     EndIf ; ---------------------------------------------- END of GetFileListData --------------------------------------------------
        
    $DoContinue = MsgBox (4, "IMDB EPISODE RENAMER", "Do you want to Search & Rename another Series ?") 
Wend            
Else
     MsgBox(0,"Error: Unable to Connect", "FireFox with MozRepl AddOn Required !")
EndIf     ; ------------------------------------------------ End If _FFIsConnected () -----------------------------------------------
 
ToolTip(" Quiting FireFox ", $ttX, $ttY)
_FFQuit ()
ToolTip("", $ttX, $ttY)

ToolTip(" Shuting Done ", $ttX, $ttY)
Sleep(2000)
ToolTip("", $ttX, $ttY)

EXIT(0)

Share this post


Link to post
Share on other sites



#2 ·  Posted (edited)

Note: Script Correction,

Please use the Corrected Version as Script was Quickly Done, and posted.

Country Boy.

Removed the first GetFileList() in Main Body of Script, as this was for quick testing only,

because More file type extensions for FileOpenDialog() were added.

The Temporary Testing error will cause the Function to be called twice, before and after Web page is opened.

While ($DoContinue = 6)                                                                            ; User Selected Continue in Msgbox
    GetFileList()   ; REMOVEED THIS LINE, for TESTING PURPOSE ONLY
    ImdbSearch()                                                                                  ; Open search get title & season
     GetFileList()

Note: Replaced The Runwait() call in Function EditRenameList()

Windows Note Pad may not be able to find file if Script or

Compiled exe is placed in a folder with a space in the folder name.

Replaced The Runwait() Call with a ShellExecuteWait() Call.

; Line Replaced :
                    RunWait(@ComSpec & " /c " & $RenameList, FileGetShortName(@ScriptDir,1),@SW_HIDE )
; New Line added :
                    ShellExecuteWait ( "notepad.exe", $RenameList, @ScriptDir, "open", @SW_SHOWNORMAL )

Also did a Minor Clean up of GetFileListData() Function Return.

NEW CORRECTED MODIFIED VERSION OF SCRIPT:

; IMDB EPISODE RENAMER 

; FireFox Automation Example Script, free for use : [ CopyRight © 2011 James Moore ] Please give credit for use of, or any parts of.

; ************************************* IMDB EPISODE RENAMER : Internet Movie Data Base Renamer *************************************************
#cs
Searchs IMDB for TV Series Title Name, and gets Epsisode Name to RENAME Selected TV Series Episodes
Opens Search Webpage, User Selects the Title Name, and Season, or Full Episode List, and Folder - Files to Rename
Scans Webpages Title Name for Season - Episode Number to obtain Episode Name for the Selected Files to Rename
RENAME FORMAT : [ Title Name * Season x Episode Number - Episode Name ]    Example : ( Baywatch 03x08 - Princess Of Tides.avi )
-----------------------------------------------------------------------------------------------------------------------------------------------

NOTE: This Program Requires FireFox Browser with MozRepl Addon installed.

MozRepl Addon available from :                                  DOWNLOAD : [ https://github.com/bard/mozrepl/wiki ]
OR Mozilla FireFox Website:
MozLab Version 0.1.8.2007072315 Works with Firefox 1.5 - 3.0a7  DOWNLOAD : [ https://addons.mozilla.org/en-us/firefox/addon/mozlab/ ]
Version 1.1 beta2 1/25/2011 Works with: Firefox 3.0 - 6.*       DOWNLOAD : [ https://addons.mozilla.org/en-US/firefox/addon/mozrepl/versions/ ]

UDF for FireFox automation by Author(s) : Thorsten Willert
FF.au3 Include                                                  DOWNLOAD : [ http://www.thorsten-willert.de/Themen/FFau3/FF.au3/FF.au3?a ]
FFex.au3 Include                                                DOWNLOAD : [ http://www.thorsten-willert.de/Themen/FFau3/FF.au3/FFEx.au3?a ]
For more info see:                                                       : [ http://www.autoitscript.com/forum/topic/95595-ffau3-v0600b/ ]

AUTOIT : To Compile this Script                                 DOWNLOAD : [ http://www.autoitscript.com/site/autoit/downloads/ ]

Another Usefull Tool for File Renaming is Renamer by den4b      DOWNLOAD : [ http://www.den4b.com/?x=downloads ]

-----------------------------------------------------------------------------------------------------------------------------------------------
CopyRight © 2011 James Moore
A Quick done Example Provided Free for Use, Please give Author credit for use of, or any parts of Script.
I love Autoit, An easy and Quick Scripting Language, and I also Write programs in : Pascal, Assembly, C++, Html, some java, and Basic
For more information or questions Contact louisiana.countryboy at Google gmail
#ce
; ***********************************************************************************************************************************************

#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Compression=4
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****

#Include <FF.au3>
#include <FFex.au3>
#Include <Misc.au3>

; ------------------------------------------------------  Set Window Options -----------------------------------------------------
Opt("TrayOnEventMode",0)         ; 0=disable, 1=enable
Opt("WinTitleMatchMode", 2)      ; 1=start, 2=subStr, 3=exact, 4=advanced, -1 to -4=Nocase
Opt("WinDetectHiddenText", 1)    ; 0=don't detect, 1=do detect
Opt("WinTextMatchMode", 2)       ; 1=complete, 2=quick
Opt("WinSearchChildren", 1)      ; 0=no, 1=search 
Opt("MouseCoordMode",1)

Local Const $RenameList = @ScriptDir & "\IMDB-Rename.txt"
Local Const $RenameListTMP = @ScriptDir & "\IMDB-Rename-OLD.txt"

$SeriesName = ""                    ; The Name of the Series of Episodes to Rename, Used as 1st part of filename
$SeasonStr = ""                     ; The Season of the Series Episode List for files to rename
$WebpageSourceCode = ""             ; Html Source Code of IMDB Webpage, used to get NAME of Season - Episode to rename    
$RenameFileFolder = ""              ; Folder path of files selected to rename
$SeasonInList = ""                  ; Global for GetFileListData() to predict Season number if matches found in file list.
$MaxLen = 0                         ; Maximum length of Filenames in Rename List used for formating list
$DoContinue = 6                     ; MsgBox Yes = 6, continue or No 7, Quit Program

; --------------------------------------------------- Window Constants ---------------------------------------------------------
Local Const $ttX = ((@DesktopWidth / 3) * 2)                      ; Tool Tip X Position = Two-Thirds of Screen Width
Local Const $ttY = 4                                              ; Tool Tip Y Position

; -------------------------------------------------- Check if Page Load Error -------------------------------------------------
; Firefox can't find the server at (or) Problem loading Page   <title>Problem loading page</title>

Func CheckLoadError()
     ToolTip("", $ttX, $ttY)
     ToolTip(" Check Page Load Error ", $ttX, $ttY)
     Sleep(200)
     _FFLoadWait()
     If ((WinExists ( "Problem loading page" )) Or (WinExists ( "find the server at" )) Or (WinExists ( "Server not found" ))) Then
         _FFAction("Reload","LOAD_FLAGS_NONE")             ; Reload the Page
         _FFLoadWait()
         Sleep(2000)                                       ; Wait 2 seconds
         ToolTip("", $ttX, $ttY)
         Return 1
     EndIf   
     Sleep(200)
     ToolTip("", $ttX, $ttY)
     Return 0    
 EndFunc

; ------------------------------------------------ WINDOW WAIT SECONDS -----------------------------------------------------
; Wait Seconds Untill Opening or webpage Window exists

Func WinWaitSeconds($WaitSec)   
     If Not WinExists ("[CLASS:MozillaWindowClass]") Then                                            ; USER CLOSED FIREFOX BROWSER SO QUIT
         ToolTip("", $ttX, $ttY)
         Exit(0)
     EndIf  
     For $i = 0 to $WaitSec -1 Step 1
         ToolTip(" Wait On Window: " & ($WaitSec - $i) & " Seconds ", $ttX, $ttY)
         Sleep(1000)
     Next
     ToolTip("", $ttX, $ttY)
 EndFunc
 
; ------------------------------------------------ WINDOW WAIT MINUTES -----------------------------------------------------
; Wait Minutes Untill Opening or webpage Window exists

Func WinWaitMinutes($MsgStr, $WaitMin)  
     For $i = 0 to $WaitMin - 1 Step 1
         ToolTip($MsgStr & "  " & ($WaitMin - $i) & " Minutes ",(@DesktopWidth / 2), $ttY)
         If Not WinExists ("[CLASS:MozillaWindowClass]") Then                                        ; USER CLOSED FIREFOX BROWSER SO QUIT
             ToolTip("", (@DesktopWidth / 2), $ttY)
             Exit(0)
         EndIf  
         Sleep(60000)     ; Wait 1 Minute
     Next
     ToolTip("", (@DesktopWidth / 2), $ttY)
 EndFunc

; ---------------------------------------------------- Func Do Quit Close Firefox and Exit -----------------------------------------------------
Func DoQuit()
     _FFQuit()
     Exit(0)
EndFunc

; ----------------------------------------------------------- Ask User if want to Quit ---------------------------------------------------------
Func Ask2Quit()
         $Quit = MsgBox (4, "QUIT PROGRAM", "Do you want to Quit Program ?")
         If ($Quit <> 6) Then Return
         DoQuit()
 EndFunc
 
 ; ------------------------------------------------------- Return True if Esc Key Pressed -------------------------------------------------------
 Func EscKeyPressed()
     If _IsPressed("1B") Then
         Return True
     Else
         Return False        
     EndIf   
 EndFunc

; ------------------------------------------- Get String in a String or in Text Stream -------------------------------------------
; Returns STRING: Searchs for ( SearchStr ) as starting Position to Search for ( Str 2 Find Start )
; ( Search Str Past End ) is String Past String2Find and is the Count of Chars to get. ; Webpage Search: Example: $Str2Search = _FFReadText(7)

Func GetStrInStr($Str2Search, $SearchStr, $Str2FindStart, $StrPastStr2FindEnd)                     
     $ItemPos = StringInStr($Str2Search,$SearchStr)
     If $ItemPos > 0 Then                                                                            ; Didn't find Search String Return ""
         $StringStart = StringInStr($Str2Search,$Str2FindStart,2,1,$ItemPos)
         If $StringStart > 0 Then                                                                    ; Didn't find Str2FindStart Return ""
              If ($StrPastStr2FindEnd = "") and (StringLen($Str2Search) >= $StringStart) Then        ; Get whole string if no char past end
                 $StringEnd = StringLen($Str2Search)+1
             Else
                 $StringEnd = (StringInStr($Str2Search,$StrPastStr2FindEnd,2,1,$StringStart))
             EndIf
              If ($StringEnd > 0) and ($StringEnd > $StringStart) Then                                ; No "", At Least one Char    
                 $Str2Return = StringMid ( $Str2Search, $StringStart ,($StringEnd - $StringStart))    
                 $Str2Return = StringStripWS ( $Str2Return, 2 )
                 $Str2Return = StringReplace ( $Str2Return, '"',"")                                   ; Remove any Quotes "" or ''
                 $Str2Return = StringReplace ( $Str2Return, "'","")
                 Return $Str2Return
             EndIf
         EndIf
     EndIf  
  Return ""
EndFunc

; **************************************************************************************************************************************
; Searchs IMDB Webpage Source Code and Returns ( Episode Name ) of Selected Season and Episode Number

Func GetImdbEpisode( $ImdbSeason, $ImdbEpisode)
     ToolTip("", $ttX, $ttY)
     ToolTip(" Geting Episode Name ", $ttX, $ttY)
     $EpisodeName = StringReplace(GetStrInStr( $WebpageSourceCode, "Season " & $ImdbSeason & ", Episode " & $ImdbEpisode & ":", ">", "<"),">","")
                                                                                                  ; MsgBox(64, "TEXT Episode 2 IS",  $EpisodeName)
     $EpisodeName = StringRegExpReplace($EpisodeName, "[\\\-\_\.\,\(\)\!\{\}\+\=\?\#\~\<\>\'\|\`\/\%\^\*\@\;\:]", "")
     $EpisodeName = StringReplace ($EpisodeName,'"',"")
     $EpisodeName = StringReplace($EpisodeName,"&","And")
     $EpisodeName = StringStripWS ( $EpisodeName, 1 )
     $EpisodeName = StringStripWS ( $EpisodeName, 2 )
     $EpisodeName = StringStripWS ( $EpisodeName, 4 )
     Return $EpisodeName
     ToolTip("", $ttX, $ttY)
EndFunc

; --------------------------------------------------- Get Episode String Starting Position -------------------------------------------------------
; Searches FileName List String to ( skip Leading Numbers ), and Predict Search Starting Position of Season - Episode Divider - Episode Number
                 ; Mode 1: Season Match, and Episode divider: x or e found
                 ; Mode 2: Season Match, and any Episode divider Found
                 ; Mode 3: Episode divider: x or e found, and Preceding Char OldTmpS is an Integer, but not Season Match
                 ; Mode 4: Unknown Episode Divider Found, and Preceding Char OldTmpS is an Integer, but not Season Match
                 ; Mode 5: Season Match found only, and no divider found

Func GetEpisodeStringStartPosition($sInput,$Season2Get,$Mode)
    $TmpS = ""
    $OldTmpS = ""
    $OlderTmpS = ""
    $EpDivStrPos =  1                                                                       ; Return Default Start at Char 1 Position
    $SeasonTmp = ""

    $SLen = StringLen($sInput)
    For $i = 1 to $SLen
         $SeasonTmp =  ""
         $TmpS = StringMid($sInput,$i,1)
         If (StringIsInt($OlderTmpS)) Then  $SeasonTmp =  $OlderTmpS
         If (StringIsInt($OldTmpS)) Then  $SeasonTmp =  $SeasonTmp & $OldTmpS    
         If $SeasonTmp < 10 then $SeasonTmp = StringReplace($SeasonTmp, "0","",1,0)         ; Remove leading 0
         If ($Mode = 5) and ($SeasonTmp = $Season2Get)  Then ExitLoop                       ; Found Season, Search sting to end skip last char
         If Not StringIsInt($TmpS) then                                                     ; may have found episode divider
             If ($i < $SLen) Then                                                           ; look ahead 1 char
                 If StringIsInt($OldTmpS) and StringIsInt(StringMid($sInput,$i+1,1)) Then
                     Select
                        Case $Mode = "1"
                             If ($SeasonTmp = $Season2Get) and (($TmpS = "x") or ($TmpS = "e")) Then ExitLoop
                         Case $Mode = "2"
                             If ($SeasonTmp = $Season2Get) Then ExitLoop
                         Case $Mode = "3"
                             If (($TmpS = "x") or ($TmpS = "e")) And (StringIsInt($OldTmpS)) Then ExitLoop
                         Case $Mode = "4"
                             If (StringIsInt($OldTmpS)) Then ExitLoop
                     EndSelect      
                 Endif   
             EndIf
         Endif   
         $OlderTmpS = $OldTmpS
         $OldTmpS = $TmpS                                                                  ; look behind 1 space or last char
     Next

     If $i = $SLen +1 Then                                                                 ; Reached end of string loop count i + increment 1
         $EpDivStrPos = 1                                                                  ; at end of string and didn't find it set start to 1
     Else
         If StringIsInt($OlderTmpS) Then                                                   ; If 2nd char before divider is Integer
             $EpDivStrPos = $i -2                                                          ; start search 2 spaces back                                 
         Else
             $EpDivStrPos = $i -1                                                          ; only 1 integer before episode divider  
         Endif  
     EndIf
     Return $EpDivStrPos
EndFunc 

; ------------------------------------------------------------ GET EPISODE NUMBER --------------------------------------------------------
; Searchs String of Selected Season - Episode List and Returns the Episode Number, Calls GetEpisodeStringStartPosition() to skip leading digit
; Season-Episode Divider Formats : s01e09, 01x09, 01e09, 0109, 1x09, 01x9, 1x9, 19
; Also Returns : Global $SeasonInList for GetFileListData() to predict Season of Files in List to Rename if IMDB Full Episode List Choosen

Func GetEpisodeNumber( $sInput, $Season2Get)
    $TmpS = ""
    $S1 = ""
    $S2 = ""
    $E1 = ""
    $E2 = ""
    $EpDiv = ""
    $IntCount = 0
    $NonIntCount = 0
    $EpDivGroupPosition =  0
    $SeasonInList = ""                                                           ; Global to Predict FileList season $SeasonInList = ""
    $sOutput = ""
    
     For $j = 1 to 5                                                             ; For Search Depth Mode 1 to 5
         $StartPos = GetEpisodeStringStartPosition($sInput,$Season2Get,$j)       ; Check all 5 posible string search start positions
         If $StartPos > 1 Then ExitLoop                                          ; Found String search Starting Position
     Next
     
    $SLen = StringLen($sInput)

    For $i = $StartPos to $SLen
         $TmpS = StringMid($sInput,$i,1)
         If StringIsInt($TmpS) then                                     ; Found an Integer in the String
             $IntCount = $IntCount +1                                   ; Keep count of Integers found in string             
             If ($i+1 < $SLen) and ($S1 = "") Then                      ; Check if found Group of Integers, not a single number before group
                 If not (StringIsInt(StringMid($sInput,$i+1,1)) or StringIsInt(StringMid($sInput,$i+2,1))) Then $IntCount = 0
             EndIf   
             If ($IntCount = 1) and ($S1 = "") Then                     ; Found 1st Integer of Group in String
                 $S1 = $TmpS
                 $NonIntCount = 0                                       ; Zero or Start the Non Integer count in Group
             EndIf
             If ($IntCount = 2) and ($S2 = "") Then $S2 =  $TmpS        ; Get 2nd Integer in Group
             If ($IntCount = 3) and ($E1 = "") Then $E1 =  $TmpS        ; Get 3rd Integer in Group
             If ($IntCount = 4) and ($E2 = "") Then $E2 =  $TmpS        ; Get 4th Integer in Group
         Else
             If ($S1 <> "") and $NonIntCount > 1 Then ExitLoop          ; Group End: no more integers, found episode divider, and none integer
             If ($S1 <> "") Then $NonIntCount = $NonIntCount +1         ; if group of integers found then keep count of any non-integers
             If ($NonIntCount > 0) and ($EpDiv = "") Then
                 $EpDiv = $TmpS                                         ; Get the Episode divider char found in group of integers
                 $EpDivGroupPosition = $IntCount+1                      ; Get Episode divider position in group of integers
             EndIf   
         Endif
     Next
    
    If ($IntCount = 3) and ($EpDivGroupPosition <> 3) Then             ; Only 3 DIGITS IN STRING Swap Season and Extention       
         $E2 =  $E1                                                    ; but, don't swap if season has 2 digits & Episode has 1 : ( 12x3 )
         $E1 = $S2
         $S2 = ""
     EndIf   
      If ($IntCount = 2) Then                                          ; ONLY 2 DIGITS IN STRING must be a single digit of season and Episode
         $E2 =  ""
         $E1 = $S2
         $S2 = ""
     EndIf   
         
     If $Season2Get < 10 then $Season2Get = StringReplace($Season2Get, "0","",1,0)        ; Remove Leading 0 if < 10
     
     $SeasonTmp =  $S1 & $S2
     If $SeasonTmp < 10 then $SeasonTmp = StringReplace($SeasonTmp, "0","",1,0)           ; Remove Leading 0 if < 10
     $SeasonInList = $SeasonTmp                                                           ; Get Global $SeasonInList for GetFileListData()
     
     If ($Season2Get = $SeasonTmp) Then                                                   ; FOUND Episode Number for Season Selected
         $sOutput = $E1 & $E2
         If $sOutput < 10 then $sOutput = StringReplace($sOutput, "0","",1,0)             ; Remove leading 0 if < 10
     EndIf
     Return $sOutput
EndFunc ; GetEpisodeNumber()

; ------------------------------------------------------- Create Rename list of Files ----------------------------------------------------------
; Create Rename List, Saves IMDB-Rename.txt as IMDB-Rename-OLD and Re-Creats a New Modified IMDB-Rename.txt
; Calls GetEpisodeNumber() & GetImdbEpisode() To get Episode Name for Selected Season, Formats New Line String AND Saves to Rename List

Func CreateRenameList()
     ToolTip("", $ttX, $ttY)
     ToolTip("Creating Episode Rename List ", $ttX, $ttY)       
         
If FileExists ($RenameList) then                                                          ; Check if IMDB-Rename.txt exists
     FileMove ( $RenameList, $RenameListTMP , 1 )                                         ; SAVE IMDB-Rename.txt AS IMDB-Rename-Old.txt
     If Not FileExists ($RenameList) then                                                 ; Check if IMDB-Rename.txt was Renamed
         If FileExists ($RenameListTMP) then                                              ; And New File Name EXISTS
         $File = FileOpen($RenameListTMP, 0)                                              ; Open the Renamed Origional
         If $File = -1 Then Exit                                                          ; if file opened for reading ERROR EXIT
         While 1                                                                          ; Read in lines of text until the EOF is reached
             $line2Add = FileReadLine($File)                                              ; Get a line of text
             If @error = -1 Then ExitLoop
             If (StringInStr($line2Add,"Check - Edit",0)= 0) and (StringInStr($line2Add,"Folder=",0)= 0) Then
                 $GetEpNum = GetEpisodeNumber($line2Add, $SeasonStr)                                    ; MsgBox(0, "GetEpNum ",  $GetEpNum)
                 $EpName = GetImdbEpisode($SeasonStr, $GetEpNum)                                        ; MsgBox(0, "Episode Name ",  $EpName)
                     
                 If $EpName <> "" Then          
                     $Season = $SeasonStr                                                               ; Format String for File List add 0         
                     If ($Season < 10) And (StringInStr($Season,"0")=0) Then $Season = "0" & $Season 

                     $EpNum = $GetEpNum                                                                 ; FILE FORMAT $EpNum ADD leading 0
                     If ($EpNum < 10) AND  (StringInStr($EpNum, "0") = 0) Then $EpNum = "0" & $EpNum    ; MsgBox(0, "THE Episode Number 2 ADD ", $GetEpNum)
                     
                     $StrEnd = StringRight($line2Add, 5 )                                               ; Get last four char at end of string
                     $StrExt = StringReplace(GetStrInStr( $StrEnd, ".", ".", ""),".","")                ; Get the String filename extension
                     
                     $Newline2Add = $line2Add                                                           ; Justify - Format Filename string for list
                     $Newline2Add = StringFormat("%-"& $MaxLen & "s", $Newline2Add)                     ; Pad end of string with spaces
                     $Newline2Add = $Newline2Add & ">   " & $SeriesName & " " & $Season & "x" &  $EpNum & " - " & $EpName & "." & $StrExt
                                                                                            ; MsgBox(0, "New Line 2 ADD ",  $Newline2Add)
                     FileWriteLine($RenameList, $Newline2Add)                               ; MsgBox(0, "WRITE THE STRING Line 2 ADD ", $line2Add) 
                 Else 
                     FileWriteLine($RenameList, $line2Add)                                  ; MsgBox(0, "Write Unchanged line: ", $line2Add)
                 EndIf
             Else
                 FileWriteLine($RenameList, $line2Add)                                      ; MsgBox(0, "Write Unchanged line: ", $line2Add)
             EndIf                                                                          ; END OF : If (StringInStr($line2Add
         Wend
             FileClose($file)
         EndIf                                                                              ; END OF $GetEpNum <> "" 
     Else
          MsgBox(0, "ERROR : Saving File", $RenameList)
     EndIf                                                                                  ; END OF : If Not FileExists ($RenameList)
Else   
     MsgBox(0, "File not Found", $RenameList)
EndIf                                                                                      ; END OF : If FileExists ($RenameList) then 
     ToolTip("", $ttX, $ttY)
EndFunc

; -------------------------------------------------- GET  FileListData : Open List Read in names ------------------------------------------
; Get format Length of longest Line in FileRename List, Get Path to $RenameFileFolder, and Predict Season from FileName of the Rename list
; Calls GetEpisodeNumber to Get Global $SeasonInList to Predict Season of FileNames in Rename List if Full Episode List was Choosen

Func GetFileListData()
     $RenameFileFolder = ""
     $GotFileListData = False
     ToolTip("", $ttX, $ttY)
     ToolTip(" Checking Rename List ", $ttX, $ttY)
     $OlderSTmp = ""
     $OldSTmp = ""
     $STmp = ""
     $TmpLen = 0
 If FileExists ($RenameList) then
     $File = FileOpen($RenameList, 0)
     If $File = -1 Then Exit                                                                         ; If file OPEN ERROR - EXIT
     While 1                                                                                         ; Read in lines until EOF is reached
         $line2DL = FileReadLine($File)
         If @error = -1 Then ExitLoop
         If (StringInStr($line2DL,"Check - Edit",0)= 0) Then 
             If (StringInStr($line2DL,"Folder=",0)<> 0) Then
                 $RenameFileFolder = StringReplace (GetStrInStr($line2DL, "Folder=", "=", ""),"=","")    
                 $GotFileListData = True                                                             ; MsgBox(0,"Rename File Folder",$RenameFileFolder)
             Else                                                                                             ; List of filenames only
                 GetEpisodeNumber($line2DL, "")                                                               ; Get at least 3 with same season
                 If StringIsInt($SeasonInList) Then $STmp = $SeasonInList                                     ; to predict season of list
                 If ($SeasonStr = "") and ($STmp <> "") and ($STmp = $OldSTmp) and ($STmp = $OlderSTmp) Then 
                     $SeasonStr = $STmp
                 Endif               
                 If StringLen($line2DL) >  $TmpLen Then $TmpLen = StringLen($line2DL)                ; Get length of longest filename in list
             EndIf
         EndIf
         $OlderSTmp = $OldSTmp
         $OldSTmp = $STmp
     Wend
     FileClose($file)
 Else    
     MsgBox(0, "File not Found : List of IMDB Episodes", $RenameList)
 EndIf
     $MaxLen = $TmpLen  + 3                                                                            ; Return Maximum String Length 
     ToolTip("", $ttX, $ttY)
     Return $GotFileListData
EndFunc

; -------------------------------------------- Get List of Files to Rename and Create Rename List -----------------------------------------------
Func GetFileList() 
 ToolTip("", $ttX, $ttY)
 ToolTip(" Select Files to Rename ", $ttX, $ttY)    

$message = "Select Files:  Hold Ctrl or Shift : Mouse or Arrow Keys for multiple files."          ; Multiple filter group
; File Type Filter
$F1 =  "Videos (*.avi;*.wmv;*.divx;*mpg;*.mkv;*flv;*.ogg;*.ogm;*.ogv;*.f4v;*.mov;*.mp4;*.mpe;*.m4v;*.mpv;*.m1v;*.dat;*vob;"
$F2 = "*asf;*.qt;*.3gp;*.3g2;*.m4v;*.rm;*.rmvb;*.m2ts;*.mts;*.tod;*.vro;*.dv;*.amv;*.ts;*.tp;*.m2t;*.dvr-ms;*.m)|All Files(*.*)"
$var = FileOpenDialog($message, "", $F1 & $F2, 1 + 4 )

If @error Then
     MsgBox(4096,"Exit Program","    No File(s) chosen ...    ")
     DoQuit()
Else
     $var = StringReplace($var,"|","||",1)
     $var = StringReplace($var, "|", @CRLF)                                                      ; MsgBox(4096,"","You chose " & $var)
    
     $File = FileOpen($RenameList, 2)                                                            ; Open the Rename list
     If $File = -1 Then Exit                                                                     ; if file opened for reading ERROR EXIT
     FileWriteLine($RenameList, "Check - Edit File Names - Save ... Close NotePad [x] to Continue" & @CRLF & @CRLF)
     FileWriteLine($RenameList, "Folder=" & $var) 
     FileClose($file)
EndIf
     ToolTip("", $ttX, $ttY)
EndFunc
 
; -------------------------------------------- Use NotePad to CHECK - EDIT - SAVE FILE RENAME LIST --------------------------------------------
; Uses Windows NotePad to View and Edit Rename List before Renaming Files

Func EditRenameList()
     ToolTip("", $ttX, $ttY)
     ToolTip(" Check - Edit Rename List ", $ttX, $ttY)
     $SaveNow = 7
     ShellExecuteWait ( "notepad.exe", $RenameList, @ScriptDir, "open", @SW_SHOWNORMAL )
     While ($SaveNow = 7)
         $SaveNow = MsgBox (3, "RENAME FILES", "[ Yes ] = RENAME   [ No ] = View - Edit   [ Cancel ] = Quit")
             Select
                Case $SaveNow = 6                                                          ; Check if user clicked on the "Yes" button
                     Return True
                 Case $SaveNow = 7                                                         ; Check if user clicked on the "No" button
                     ShellExecuteWait ( "notepad.exe", $RenameList, @ScriptDir, "open", @SW_SHOWNORMAL )
                 Case $SaveNow = 2                                                         ; Check if user clicked on the "CANCEL" button
                     Return false
             EndSelect      
         Wend
     ToolTip("", $ttX, $ttY)                                                                       
  EndFunc
 
; ------------------------------------------------------ Get Season of Series Title Name --------------------------------------------------
; Gets Season from Webpage link URL, or from Getfilelistdata's scan of filelist to get Predicted Season, or Ask's user if not available

Func GetSeason()
     ToolTip("", $ttX, $ttY)
     ToolTip(" SEASON of Episode List ", $ttX, $ttY)
     $TmpStr = ""
     If $SeasonStr = "" Then
         $SrcLink = _FF_GetCurrentURL()                                                                       ; MsgBox(0, "SrcLink", $SrcLink)
         If StringInStr( $SrcLink,"episodes#") > 0 then                       ; example: http://www.imdb.com/title/tt0073972/episodes#season-2
             $TmpStr = StringReplace(GetStrInStr( $SrcLink, "episodes#season", "-", ""),"-","")
         Endif   
         If StringIsInt($TmpStr) Then
             $SeasonStr = $TmpStr
             Else
                 While not StringIsInt($SeasonStr)
                     If not StringIsInt($TmpStr) then $TmpStr = "1"
                     $SeasonStr = InputBox ( "IMDB Episode List SEASON", "Enter Season for IMDB Episode List", $TmpStr,"",375,150) 
                     If @error Then DoQuit()
                 Wend
         EndIf
     EndIf  
     ToolTip("", $ttX, $ttY)
EndFunc

; ---------------------------------------------------------- Get Series Name ---------------------------------------------------------------
; Reads Webpage SourceCode to get SERIES NAME for Formated Name in File Rename List, if unable to get then ASK USER

Func GetSeriesName()
     ToolTip("", $ttX, $ttY)
     ToolTip(" Get Season Name ", $ttX, $ttY)
     $sTitle = _FFCmd(".title")                                                   ; MsgBox(0, "Series NAME",  $sTitle) 
     $Series = StringLeft($sTitle, StringInStr($sTitle, '"',0,2 )) 
     $Series = StringReplace($Series,'"',"")
     $Series = StringReplace($Series,"&","And")
     $Series = StringRegExpReplace($Series, "[\\\-\_\.\,\(\)\!\{\}\+\=\?\#\~\<\>\'\|\`\/\%\^\*\@\;\:]", "")
     If StringInStr($Series,":") > 0 Then
        $Series = GetStrInStr( $Series, $Series, $Series, ":")                    ; Get short Version of Series Name
     Endif
     If $Series = "" Then
         $Series = InputBox ( "Get Series NAME", "Enter Series NAME for IMDB Episode List", $Series,"",375,150) 
         If @error or ($Series = "") Then DoQuit()
     EndIf      
     $SeriesName =  $Series                                                       ; MsgBox(0, "Series NAME fixed",  $SeriesName)
     ToolTip("", $ttX, $ttY)
 EndFunc    
 
 ; ------------------------------------------------------------ RENAME FILES -------------------------------------------------------------------- 
 ; Open Rename List, ask user if want to rename, and Rename the Selected Files, Report Count of Errors and count of Files Renamed
 
Func RenameFiles()
     $FileCount = 0
     $ErrorCount = 0
     ToolTip("", $ttX, $ttY)
     ToolTip(" Rename Files ", $ttX, $ttY)      
     $SaveNow = MsgBox (1, "Confirm Rename Files", "Do you want to Rename Files ?")
     If  $SaveNow <> 1 Then DoQuit()

If FileExists ($RenameList) then                                                      ; Check if IMDB-Rename.txt exists
     $File = FileOpen($RenameList, 0)                                                 ; Open Rename list
     If $File = -1 Then Exit                                                          ; if file opened for reading ERROR EXIT
     While 1                                                                          ; Read in lines of text until the EOF is reached
         $line2Ren = FileReadLine($File)                                              ; Get a line
         If @error = -1 Then ExitLoop
         If ($line2Ren <> "") and (StringInStr($line2Ren,"Check - Edit",0)= 0) and (StringInStr($line2Ren,"Folder=",0)= 0) Then
             $EpFileName = StringStripWS(StringStripWS(StringReplace(StringLeft($line2Ren, StringInStr($line2Ren,">")),">",""),1),2)
             $EpFileName = $RenameFileFolder & "\" & $EpFileName                      ;  MsgBox(0, "Episode File to Rename", $EpFileName)
             $NewFileName = StringStripWS(StringStripWS(StringReplace(GetStrInStr( $line2Ren, ">", ">", ""),">",""),1),2)
             $NewFileName = $RenameFileFolder & "\" & $NewFileName                    ; MsgBox(0, "New File Name to Rename File", $NewFileName)
             If FileExists($EpFileName) Then                                          ; MsgBox(0, "File Exists", $EpFileName)
                 FileMove ( $EpFileName, $NewFileName , 0 )  
                 $FileCount = $FileCount + 1                                          ; Increment Files Done
                 If Not FileExists($NewFileName) Then $ErrorCount = $ErrorCount + 1   ; Increment Error Count
             Else
                 MsgBox(0, "ERROR: File Not Found", $EpFileName)                 
             EndIf 
         Endif
     Wend
             FileClose($file)
             If $ErrorCount > 0 Then  MsgBox(0, "FILE RENAME : ERROR", "( " & $ErrorCount & " )  Files were not Renamed")
             If $FileCount > 0 Then  MsgBox(0, "FILE RENAME : SUCESS", "( " & $FileCount & " )  Files were Renamed")
Else 
         MsgBox(0, "File not Found", $RenameList)
EndIf  
         ToolTip("", $ttX, $ttY)
EndFunc

; ----------------------------------------------------- Open IMDB SEARCH WEBPAGE --------------------------------------------------------------
; Open IMDB Webpage Search, Get Title Name, Get Season to Rename, or Full Episode List, If Error Ask user for Search Link, Esc Key = Quit
; Searchbar: /html/body/div[1]/div[2]/layer/div[1]/div[2]/form/div/input ; id="navbar-query"  name="q" ; BUTTON Go class="nb_primary" type="submit"

Func ImdbSearch()
     $ImdbLink = "http://www.imdb.com/search/"
     
     ToolTip("", $ttX, $ttY)
     ToolTip(" Opening IMDB Search ", $ttX, $ttY)
     _FFOpenURL($ImdbLink)                                                                          ; Open IMDB Search Webpage
     CheckLoadError()
     $SrcLink = _FF_GetCurrentURL()  
     
     If (StringInStr( $SrcLink,$ImdbLink)= 0) Then                                                 ; Error Loading search ask user
         $SrcLink = InputBox( "ERROR LOADING IMDB SEARCH", "Enter Link : IMDB Title Name Search", $ImdbLink,"",375,150) 
         If @error or ($SrcLink = "") Then DoQuit()
        
         If (StringInStr( $SrcLink,"imdb.com")<> 0) Then                                           ; Open user Provided Link
             ToolTip("", $ttX, $ttY)
             ToolTip(" Opening IMDB Website ", $ttX, $ttY)
             _FFOpenURL($SrcLink)
             CheckLoadError()
         EndIf           
     EndIf
     
     ToolTip("", $ttX, $ttY)                                                                       ; Show Help Information
     ToolTip(" Search Series Title Name ", $ttX, $ttY)
     MsgBox (0, 'IMDB EPISODE RENAMER SEARCH', "Search for TV Series Title [ NAME ]  and  Select [ SEASON ] ... Hold Esc Key to Quit" ,5 )
     ToolTip("", $ttX, $ttY) 
      
     MouseMove ( (@DesktopWidth / 2)-120, (@DesktopHeight / 5) )                                   ; move mouse near Search Bar at top
     While 1 
         $SrcLink = _FF_GetCurrentURL()                                                            ; Get Webpage link Address
         If (StringInStr( $SrcLink,"imdb.com/find?s=all") <> 0) Then                              
             ToolTip(" Select a Title from List ")                                                 ; List : Page of titles to select
         Else    
             ToolTip(" Search - Series Title Name & Click [ Go ]")                                 ; Blink help at mouse pointer                  
         EndIf
         Sleep(500)
         ToolTip("")
         If (StringInStr( $SrcLink,"/title/") <> 0) Then ExitLoop                                  ; Title Selected Go get season    
         Sleep(250)
         If Not WinExists("[CLASS:MozillaWindowClass]") Then DoQuit()                              ; Firefox window closed
         If EscKeyPressed() Then Ask2Quit()                                                        ; If user pressed Esc Ask if Quit
     WEnd
        
     MouseMove ( (@DesktopWidth / 4), @DesktopHeight - (@DesktopHeight / 5) )                     ; Move mouse near Seasons at bottom
     While 1
         $SrcLink = _FF_GetCurrentURL()                                                            ; Get Webpage link Address
         ToolTip(" Select Season or Full Episode List")
         Sleep(500)
         ToolTip("")
         If (StringInStr( $SrcLink,"episodes") <> 0) Then ExitLoop                                 ; Season or Full Episode list selected
         Sleep(250)
         If Not WinExists("[CLASS:MozillaWindowClass]") Then DoQuit()                              ; Firefox window closed
         If EscKeyPressed() Then Ask2Quit()                                                        ; If user pressed Esc Ask if Quit
     WEnd
EndFunc 

 ; *********************************************************** MAIN BODY OF PROGRAM **********************************************************

ToolTip(" Starting FireFox ", $ttX, $ttY)
_FFStart()       
$Socket =  _FFConnect()

If _FFIsConnected() Then                                                                           ; If MozRepl AddOn and firefox connected
     ToolTip(" Maximize ", $ttX, $ttY)                                                             ; Maximize Window
     _FFAction("Maximize")

While ($DoContinue = 6)                                                                            ; User Selected Continue in Msgbox
     ImdbSearch()                                                                                  ; Open search get title & season
     GetFileList()                                                                                 ; Get User Selected list of files to rename
     $WebpageSourceCode = _FFReadHTML()                                                            ; Read Webpage Html Source Code
         
     If GetFileListData() Then                        ; GetFileListData -- Check file exists, Get format info & Predict season from filelist 
         GetSeason()                                  ; Check if season needed, use GetFileListData Predicted Season, or Ask User
         GetSeriesName()                              ; Get Series Name from Webpage to format File Rename list, or ask User
         CreateRenameList()                           ; Scan WebpageSourceCode & File List: for Episode Name, and Create Rename List
         If EditRenameList() Then RenameFiles()       ; User Verify or Edits List, and Asks if want to Rename
         ToolTip("", $ttX, $ttY)
     Else   ; --------------------------------------------- File Not Found ERROR ----------------------------------------------------
             MsgBox(0, "File Not Found", "List of Files to Rename : Imdb - Rename.txt")
            
     EndIf ; ---------------------------------------------- END of GetFileListData --------------------------------------------------
        
    $DoContinue = MsgBox (4, "IMDB EPISODE RENAMER", "Do you want to Search & Rename another Series ?") 
Wend            
Else
     MsgBox(0,"Error: Unable to Connect", "FireFox with MozRepl AddOn Required !")
EndIf     ; ------------------------------------------------ End If _FFIsConnected () -----------------------------------------------
 
ToolTip(" Quiting FireFox ", $ttX, $ttY)
_FFQuit ()
ToolTip("", $ttX, $ttY)

ToolTip(" Shuting Done ", $ttX, $ttY)
Sleep(2000)
ToolTip("", $ttX, $ttY)

EXIT(0)
Edited by CountryBoy

Share this post


Link to post
Share on other sites

Hi CountryBoy,

Looks like you have been busy. :huh2:

I have looked at IMDB system previously with their use of text files for their database. I considered it too much work for my need. It looks like you have done it from the Firefox browser instead. I have not tried it yet and not sure if I have the need to use it. It does look like a good effort and would save time with a lot of use.

I would suggest that you use quotes to handle paths with possible white space. The below will use the default program that is associated to the file type.

ShellExecuteWait ( '"' & $RenameList & '"' )

Thanks for sharing ;)

Share this post


Link to post
Share on other sites

I wonder ! could you explain a practical way in which this could be used ? I'm not sure what it is you see.

[i realise this is an oldish thread, but ...]

A practical use is because people who upload TV shows to UseNet or torrent sites can't be bothered putting the episode title in the filenames.

I have written something similar which uses a downloaded html file from tv.com. I'd post it, but tv.com have a habit of changing the format all too often, which means a recode of the passing routine.

Share this post


Link to post
Share on other sites

#6 ·  Posted (edited)

Here is an Updated Script as I.M.D.B. has changed their Web Page.

The following script will work with the New Web Page.

countryboy

; IMDB EPISODE RENAMER

; FireFox Automation Example Script, free for use : [ CopyRight © 2011 James Moore ] Please give credit for use of, or any parts of.

; ************************************* IMDB EPISODE RENAMER : Internet Movie Data Base Renamer *************************************************
#cs
Searchs IMDB for TV Series Title Name, and gets Epsisode Name to RENAME Selected TV Series Episodes
Opens Search Webpage, User Selects the Title Name, and Season, or Full Episode List, and Folder - Files to Rename
Scans Webpages Title Name for Season - Episode Number to obtain Episode Name for the Selected Files to Rename
RENAME FORMAT : [ Title Name * Season x Episode Number - Episode Name ] Example : ( Baywatch 03x08 - Princess Of Tides.avi )
-----------------------------------------------------------------------------------------------------------------------------------------------

NOTE: This Program Requires FireFox Browser with MozRepl Addon installed.

MozRepl Addon available from :                               DOWNLOAD : [ https://github.com/bard/mozrepl/wiki ]
OR Mozilla FireFox Website:
MozLab Version 0.1.8.2007072315 Works with Firefox 1.5 - 3.0a7 DOWNLOAD : [ https://addons.mozilla.org/en-us/firefox/addon/mozlab/ ]
Version 1.1 beta2 1/25/2011 Works with: Firefox 3.0 - 6.*    DOWNLOAD : [ https://addons.mozilla.org/en-US/firefox/addon/mozrepl/versions/ ]

UDF for FireFox automation by Author(s) : Thorsten Willert
FF.au3 Include                                               DOWNLOAD : [ http://www.thorsten-willert.de/Themen/FFau3/FF.au3/FF.au3?a ]
FFex.au3 Include                                             DOWNLOAD : [ http://www.thorsten-willert.de/Themen/FFau3/FF.au3/FFEx.au3?a ]
For more info see:                                                   : [ http://www.autoitscript.com/forum/topic/95595-ffau3-v0600b/ ]

AUTOIT : To Compile this Script                              DOWNLOAD : [ http://www.autoitscript.com/site/autoit/downloads/ ]

Another Usefull Tool for File Renaming is Renamer by den4b   DOWNLOAD : [ http://www.den4b.com/?x=downloads ]

-----------------------------------------------------------------------------------------------------------------------------------------------
CopyRight © 2011 James Moore
A Quick done Example Provided Free for Use, Please give Author credit for use of, or any parts of Script.
I love Autoit, An easy and Quick Scripting Language, and I also Write programs in : Pascal, Assembly, C++, Html, some java, and Basic
For more information or questions Contact louisiana.countryboy at Google gmail
#ce
; ***********************************************************************************************************************************************

#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Compression=4
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****

#Include <FF.au3>
#include <FFex.au3>
#Include <Misc.au3>

; ------------------------------------------------------ Set Window Options -----------------------------------------------------
Opt("TrayOnEventMode",0)         ; 0=disable, 1=enable
Opt("WinTitleMatchMode", 2)  ; 1=start, 2=subStr, 3=exact, 4=advanced, -1 to -4=Nocase
Opt("WinDetectHiddenText", 1) ; 0=don't detect, 1=do detect
Opt("WinTextMatchMode", 2)   ; 1=complete, 2=quick
Opt("WinSearchChildren", 1)  ; 0=no, 1=search
Opt("MouseCoordMode",1)

Local Const $RenameList = @ScriptDir & "\IMDB-Rename.txt"
Local Const $RenameListTMP = @ScriptDir & "\IMDB-Rename-OLD.txt"
Local Const $DebugTxt = @ScriptDir & "\IMDB-Rename-Debug.txt"
$DebugStr = ""
$DoDebug = True                  ; Check for Errors Create Debug.txt for checking String Scaning action

$SeriesName = ""                 ; The Name of the Series of Episodes to Rename, Used as 1st part of filename
$SeasonStr = ""                  ; The Season of the Series Episode List for files to rename
$WebpageSourceCode = ""          ; Html Source Code of IMDB Webpage, used to get NAME of Season - Episode to rename
$RenameFileFolder = ""           ; Folder path of files selected to rename
$SeasonInList = ""               ; Global for GetFileListData() to predict Season number if matches found in file list.
$MaxLen = 0                      ; Maximum length of Filenames in Rename List used for formating list
$DoContinue = 6                  ; MsgBox Yes = 6, continue or No 7, Quit Program

; --------------------------------------------------- Window Constants ---------------------------------------------------------
Local Const $ttX = ((@DesktopWidth / 2))                         ; Tool Tip X Position = center of Screen Width
Local Const $ttY = 4                                             ; Tool Tip Y Position

; -------------------------------------------------- Check if Page Load Error -------------------------------------------------
; Firefox can't find the server at (or) Problem loading Page <title>Problem loading page</title>

Func CheckLoadError()
ToolTip("", $ttX, $ttY)
ToolTip(" Check Page Load Error ", $ttX, $ttY)
Sleep(200)
_FFLoadWait()
     If ((WinExists ( "Problem loading page" )) Or (WinExists ( "find the server at" )) Or (WinExists ( "Server not found" ))) Then
     _FFAction("Reload","LOAD_FLAGS_NONE")           ; Reload the Page
_FFLoadWait()
Sleep(2000)                                  ; Wait 2 seconds
ToolTip("", $ttX, $ttY)
Return 1
EndIf
Sleep(200)
ToolTip("", $ttX, $ttY)
Return 0
EndFunc

; ------------------------------------------------ WINDOW WAIT SECONDS -----------------------------------------------------
; Wait Seconds Untill Opening or webpage Window exists

Func WinWaitSeconds($WaitSec)
If Not WinExists ("[CLASS:MozillaWindowClass]") Then                                         ; USER CLOSED FIREFOX BROWSER SO QUIT
ToolTip("", $ttX, $ttY)
     Exit(0)
EndIf
     For $i = 0 to $WaitSec -1 Step 1
     ToolTip(" Wait On Window: " & ($WaitSec - $i) & " Seconds ", $ttX, $ttY)
Sleep(1000)
Next
ToolTip("", $ttX, $ttY)
EndFunc

; ------------------------------------------------ WINDOW WAIT MINUTES -----------------------------------------------------
; Wait Minutes Untill Opening or webpage Window exists

Func WinWaitMinutes($MsgStr, $WaitMin)
     For $i = 0 to $WaitMin - 1 Step 1
ToolTip($MsgStr & " " & ($WaitMin - $i) & " Minutes ",(@DesktopWidth / 2), $ttY)
         If Not WinExists ("[CLASS:MozillaWindowClass]") Then                                    ; USER CLOSED FIREFOX BROWSER SO QUIT
     ToolTip("", (@DesktopWidth / 2), $ttY)
         Exit(0)
     EndIf
Sleep(60000)     ; Wait 1 Minute
Next
ToolTip("", (@DesktopWidth / 2), $ttY)
EndFunc

; ---------------------------------------------------- Func Do Quit Close Firefox and Exit -----------------------------------------------------
Func DoQuit()
     _FFQuit()
ToolTip("", $ttX, $ttY)
Exit(0)
EndFunc

; ----------------------------------------------------------- Ask User if want to Quit ---------------------------------------------------------
Func Ask2Quit()
         $Quit = MsgBox (4, "QUIT PROGRAM", "Do you want to Quit Program ?")
If ($Quit <> 6) Then Return
DoQuit()
EndFunc

; ------------------------------------------------------- Return True if Esc Key Pressed -------------------------------------------------------
Func EscKeyPressed()
     If _IsPressed("1B") Then
         Return True
Else
         Return False
EndIf
EndFunc

; -------------------------------------------------- DELETE COOKIES HISTORY CACHE ---------------------------------------------
Func DeleteCookies()
     ToolTip(" Deleting: Cookies, Cache, History ", $ttX, $ttY)
     ;Cookies _FF_CookiesRemoveAll()
     _FFCmd("Components.classes['@mozilla.org/cookiemanager;1'].getService(Components.interfaces.nsICookieManager).removeAll();")
;History _FF_EmptyHistory()
_FFCmd("Components.classes['@mozilla.org/browser/nav-history-service;1'].getService(Components.interfaces.nsIBrowserHistory).removeAllPages();")
     ;Cache _FF_EmptyCache()
     _FFCmd("Ci=Components.interfaces;Components.classes['@mozilla.org/network/cache-service;1'].getService(Ci.nsICacheService).evictEntries(Ci.nsICache.STORE_ANYWHERE);")
Sleep(1000)
ToolTip("", $ttX, $ttY)
Return
EndFunc

; ------------------------------------------- Get String in a String or in Text Stream -------------------------------------------
; Returns STRING: Searchs for ( SearchStr ) as starting Position to Search for ( Str 2 Find Start )
; ( Search Str Past End ) is String Past String2Find and is the Count of Chars to get. ; Webpage Search: Example: $Str2Search = _FFReadText(7)

Func GetStrInStr($Str2Search, $SearchStr, $Str2FindStart, $StrPastStr2FindEnd)
     $ItemPos = StringInStr($Str2Search,$SearchStr)
     If $ItemPos > 0 Then                                                                        ; Didn't find Search String Return ""
     $StringStart = StringInStr($Str2Search,$Str2FindStart,2,1,$ItemPos)
         If $StringStart > 0 Then                                                                ; Didn't find Str2FindStart Return ""
If ($StrPastStr2FindEnd = "") and (StringLen($Str2Search) >= $StringStart) Then  ; Get whole string if no char past end
$StringEnd = StringLen($Str2Search)+1
Else
     $StringEnd = (StringInStr($Str2Search,$StrPastStr2FindEnd,2,1,$StringStart))
EndIf
If ($StringEnd > 0) and ($StringEnd > $StringStart) Then                             ; No "", At Least one Char
                 $Str2Return = StringMid ( $Str2Search, $StringStart ,($StringEnd - $StringStart))
         $Str2Return = StringStripWS ( $Str2Return, 2 )
         $Str2Return = StringReplace ( $Str2Return, '"',"")                              ; Remove any Quotes "" or ''
                 $Str2Return = StringReplace ( $Str2Return, "'","")
         Return $Str2Return
             EndIf
         EndIf
     EndIf
Return ""
EndFunc

; **************************************************************************************************************************************
; Searchs IMDB Webpage Source Code and Returns ( Episode Name ) of Selected Season and Episode Number

Func GetImdbEpisode( $ImdbSeason, $ImdbEpisode)
ToolTip("", $ttX, $ttY)
ToolTip(" Geting Episode Name ", $ttX, $ttY)

; OLD VERSION IMDB: $EpisodeName = StringReplace(GetStrInStr( $WebpageSourceCode, "Season " & $ImdbSeason & ", Episode " & $ImdbEpisode & ":", ">", "<"),">","")

$EpisodeName = StringReplace(GetStrInStr( $WebpageSourceCode, "episode-" & $ImdbEpisode, "title=","itemprop="),"title=","")

; MsgBox(64, "GetImdbEpisode", "Episode Number : " & $ImdbEpisode & " Episode Name : " & $EpisodeName)

$EpisodeName = StringRegExpReplace($EpisodeName, "[\\\-\_\.\,\(\)\!\{\}\+\=\?\#\~\<\>\'\|\`\/\%\^\*\@\;\:]", "")
$EpisodeName = StringReplace ($EpisodeName,'"',"")
$EpisodeName = StringReplace($EpisodeName,'&amp',"And")
$EpisodeName = StringStripWS ( $EpisodeName, 1 )
$EpisodeName = StringStripWS ( $EpisodeName, 2 )
$EpisodeName = StringStripWS ( $EpisodeName, 4 )
Return $EpisodeName
ToolTip("", $ttX, $ttY)
EndFunc

Func Display($sInput, $sOutput)
; Format the output.
Local $sMsg = StringFormat("Input:\t%s\n\nOutput:\t%s", $sInput, $sOutput)
MsgBox(0, "Results", $sMsg)
EndFunc ; Display()

; --------------------------------------------------- Get Episode String Starting Position -------------------------------------------------------
; Searches FileName List String to ( skip Leading Numbers ), and Predict Search Starting Position of Season - Episode Divider - Episode Number
; Mode 1: Season Match, and Episode divider: x or e found
; Mode 2: Season Match, and any Episode divider Found
; Mode 3: Episode divider: x or e found, and Preceding Char OldTmpS is an Integer, but not Season Match
; Mode 4: Unknown Episode Divider Found, and Preceding Char OldTmpS is an Integer, but not Season Match
; Mode 5: Season Match found only, and no divider found

Func GetEpisodeStringStartPosition($sInput,$Season2Get,$Mode)
$TmpS = ""
$OldTmpS = ""
$OlderTmpS = ""
$EpDivStrPos = 1                                                                     ; Return Default Start at Char 1 Position
$SeasonTmp = ""

$SLen = StringLen($sInput)
For $i = 1 to $SLen
$SeasonTmp = ""
$TmpS = StringMid($sInput,$i,1)
If (StringIsInt($OlderTmpS)) Then $SeasonTmp = $OlderTmpS
If (StringIsInt($OldTmpS)) Then $SeasonTmp = $SeasonTmp & $OldTmpS
If $SeasonTmp < 10 then $SeasonTmp = StringReplace($SeasonTmp, "0","",1,0)       ; Remove leading 0
If ($Mode = 5) and ($SeasonTmp = $Season2Get) Then ExitLoop                  ; Found Season, Search sting to end skip last char
If Not StringIsInt($TmpS) then                                                   ; may have found episode divider
If ($i < $SLen) Then                                                         ; look ahead 1 char
If StringIsInt($OldTmpS) and StringIsInt(StringMid($sInput,$i+1,1)) Then
Select
Case $Mode = "1"
If ($SeasonTmp = $Season2Get) and (($TmpS = "x") or ($TmpS = "e")) Then ExitLoop
Case $Mode = "2"
If ($SeasonTmp = $Season2Get) Then ExitLoop
                     Case $Mode = "3"
If (($TmpS = "x") or ($TmpS = "e")) And (StringIsInt($OldTmpS)) Then ExitLoop
Case $Mode = "4"
If (StringIsInt($OldTmpS)) Then ExitLoop
                 EndSelect
     Endif
EndIf
Endif
$OlderTmpS = $OldTmpS
         $OldTmpS = $TmpS                                                                ; look behind 1 space or last char
Next

     If $i >= $SLen Then                                                                 ; Reached end of string loop count i + increment 1
     $EpDivStrPos = 1                                                                ; at end of string and didn't find it set start to 1
Else
         If StringIsInt($OlderTmpS) Then                                                 ; If 2nd char before divider is Integer
     $EpDivStrPos = $i -2                                                        ; start search 2 spaces back
Else
         $EpDivStrPos = $i -1                                        ; only 1 integer before episode divider
Endif
     EndIf

;$sOutput = "GetEpisodeStringStartPosition() : Episode Divider String Position is: " & $EpDivStrPos & " Divider is " & $TmpS & "     Loop Counter ( i ) is: " & $i & " Slen " & $SLen
; Display($sInput, $sOutput)

Return $EpDivStrPos
EndFunc

; ------------------------------------------------------------ GET EPISODE NUMBER --------------------------------------------------------
; Searchs String of Selected Season - Episode List and Returns the Episode Number, Calls GetEpisodeStringStartPosition() to skip leading digit
; Season-Episode Divider Formats : s01e09, 01x09, 01e09, 0109, 1x09, 01x9, 1x9, 19
; Also Returns : Global $SeasonInList for GetFileListData() to predict Season of Files in List to Rename if IMDB Full Episode List Choosen

Func GetEpisodeNumber( $sInput, $Season2Get)
$TmpS = ""
$OldTmpS = ""
$S1 = ""
$S2 = ""
$E1 = ""
$E2 = ""
$EpDiv = ""
$IntCount = 0
$NonIntCount = 0
$EpDivGroupPosition = 0
$SeasonInList = ""                                                       ; Global to Predict FileList season $SeasonInList = ""
$sOutput = ""

$DebugStr = "String Search Position : "
For $j = 1 to 5                                                          ; For Search Depth Mode 1 to 5
     $StartPos = GetEpisodeStringStartPosition($sInput,$Season2Get,$j)   ; Check all 5 posible string search start positions
$DebugStr = $DebugStr & " Mode " & $j & " StartPos = " & $StartPos & ", "
     If $StartPos > 1 Then ExitLoop                                      ; Found String search Starting Position
Next
$DebugStr = $DebugStr & " Position Selected = " & $StartPos

$SLen = StringLen($sInput)

For $i = $StartPos to $SLen
$TmpS = StringMid($sInput,$i,1)
If StringIsInt($TmpS) then                                   ; Found an Integer in the String
$IntCount = $IntCount +1                                 ; Keep count of Integers found in string
If ($IntCount = 1) and ($S1 = "") Then                   ; Found 1st Integer of Group in String
     $S1 = $TmpS
$NonIntCount = 0                                     ; Zero or Start the Non Integer count in Group
EndIf
If ($IntCount = 2) and ($S2 = "") Then $S2 = $TmpS   ; Get 2nd Integer in Group
If ($IntCount = 3) and ($E1 = "") Then $E1 = $TmpS   ; Get 3rd Integer in Group
If ($IntCount = 4) and ($E2 = "") Then $E2 = $TmpS   ; Get 4th Integer in Group
     Else
     If ($S1 <> "") and $NonIntCount > 1 Then ExitLoop       ; Group End: no more integers, found episode divider, and none integer
If ($S1 <> "") and (StringIsInt($OldTmpS)) Then $NonIntCount = $NonIntCount +1       ; if group of integers found then keep count of any non-integers
If ($NonIntCount > 0) and ($EpDiv = "") Then
     $EpDiv = $TmpS                                      ; Get the Episode divider char found in group of integers
$EpDivGroupPosition = $IntCount + 1              ; Get Episode divider position in group of integers
EndIf
If ($EpDiv <> "") and ($NonIntCount > 0) and not (StringIsInt($OldTmpS)) Then $EpDiv = $EpDiv & $TmpS ; Episode Divider more than 1 Char
Endif
$OldTmpS = $TmpS
Next

If ($IntCount = 3) and ($EpDivGroupPosition <> 3) Then           ; Only 3 DIGITS IN STRING Swap Season and Extention
$E2 = $E1                                                ; but, don't swap if season has 2 digits & Episode has 1 : ( 12x3 )
$E1 = $S2
$S2 = ""
EndIf
If ($IntCount = 2) Then                                      ; ONLY 2 DIGITS IN STRING must be a single digit of season and Episode
$E2 = ""
$E1 = $S2
$S2 = ""
EndIf

If $Season2Get < 10 then $Season2Get = StringReplace($Season2Get, "0","",1,0)    ; Remove Leading 0 if < 10

$SeasonTmp = $S1 & $S2
If $SeasonTmp < 10 then $SeasonTmp = StringReplace($SeasonTmp, "0","",1,0)       ; Remove Leading 0 if < 10
$SeasonInList = $SeasonTmp                                                       ; Get Global $SeasonInList for GetFileListData()

If ($Season2Get = $SeasonTmp) Then                                               ; FOUND Episode Number for Season Selected
     $sOutput = $E1 & $E2
     If $sOutput < 10 then $sOutput = StringReplace($sOutput, "0","",1,0)            ; Remove leading 0 if < 10
EndIf

;$TOutput = "GetEpisodeNumber() Season 2 Get: " & $Season2Get & " Season TMP: " & $S1 & $S2 & " ( Episode Divider is: " & $EpDiv & " ) 1st EpisodeDigit = " & $E1 & " 2nd EpisodeDigit = " & $E2 & "     EpDivGroupPosition= " & $EpDivGroupPosition
;Display($sInput, $TOutput)
;Display($sInput, $sOutput)
$DebugStr = $DebugStr & @CRLF & "Season to Get = " & $Season2Get & " Season TMP = " & $S1 & $S2 & " EpDiv = " & $EpDiv & " 1st Digit = " & $E1 & " 2nd Digit = " & $E2 & " EpDivGroupPosition= " & $EpDivGroupPosition & " IntCount = " & $IntCount & " NonIntCount " & $NonIntCount

ToolTip("", $ttX, $ttY)
Return $sOutput
EndFunc ; GetEpisodeNumber()

; ------------------------------------------------------- Create Rename list of Files ----------------------------------------------------------
; Create Rename List, Saves IMDB-Rename.txt as IMDB-Rename-OLD and Re-Creats a New Modified IMDB-Rename.txt
; Calls GetEpisodeNumber() & GetImdbEpisode() To get Episode Name for Selected Season, Formats New Line String AND Saves to Rename List

Func CreateRenameList()
ToolTip("", $ttX, $ttY)
ToolTip("Creating Rename List ", $ttX, $ttY)

If FileExists ($RenameList) then                                                         ; Check if IMDB-Rename.txt exists
     FileMove ( $RenameList, $RenameListTMP , 1 )                                        ; SAVE IMDB-Rename.txt AS IMDB-Rename-Old.txt
     If Not FileExists ($RenameList) then                                                ; Check if IMDB-Rename.txt was Renamed
         If FileExists ($RenameListTMP) then                                             ; And New File Name EXISTS
         $File = FileOpen($RenameListTMP, 0)                                             ; Open the Renamed Origional
         If $File = -1 Then Exit                                                         ; if file opened for reading ERROR EXIT
         While 1                                                                         ; Read in lines of text until the EOF is reached
             $line2Add = FileReadLine($File)                                             ; Get a line of text
             If @error = -1 Then ExitLoop
If (StringInStr($line2Add,"Check - Edit",0) > 0) or (StringInStr($line2Add,"Folder=",0) > 0) or ($line2Add = "") Then
FileWriteLine($RenameList, $line2Add)                                ; MsgBox(0, "Write Unchanged line: ", $line2Add)
Else
$EpName = ""
$GetEpNum = ""
$DebugStr = ""
                 $GetEpNum = GetEpisodeNumber($line2Add, $SeasonStr)                                 ; MsgBox(0, "GetEpNum ", $GetEpNum)
                 If $GetEpNum <> "" Then $EpName = GetImdbEpisode($SeasonStr, $GetEpNum)
; MsgBox(0, "Episode Name ", "GetEpNum " & $GetEpNum & " Episode Name : " & $EpName)
ToolTip(" Episode " & $GetEpNum & " " & $EpName, $ttX, $ttY)
Sleep(150)
If $DoDebug Then                                                                     ; Write Debug info to Debug file
     FileWriteLine ( $DebugTxt, @CRLF & "Episode " & $GetEpNum & " " & $EpName )
     FileWriteLine ( $DebugTxt, $line2Add )
     FileWriteLine ( $DebugTxt, $DebugStr )
EndIf

If $EpName <> "" Then
     $Season = $SeasonStr                                                            ; Format String for File List add 0
     If ($Season < 10) And (StringInStr($Season,"0")=0) Then $Season = "0" & $Season

                     $EpNum = $GetEpNum                                                              ; FILE FORMAT $EpNum ADD leading 0
     If ($EpNum < 10) AND (StringInStr($EpNum, "0") = 0) Then $EpNum = "0" & $EpNum ; MsgBox(0, "THE Episode Number 2 ADD ", $GetEpNum)
If $EpNum = 0 then $EpNum = "00"

$StrEnd = StringRight($line2Add, 5 )                                             ; Get last four char at end of string
             $StrExt = StringReplace(GetStrInStr( $StrEnd, ".", ".", ""),".","")         ; Get the String filename extension

$Newline2Add = $line2Add                                                         ; Justify - Format Filename string for list
                     $Newline2Add = StringFormat("%-"& $MaxLen & "s", $Newline2Add)                  ; Pad end of string with spaces
                     $Newline2Add = $Newline2Add & "> " & $SeriesName & " " & $Season & "x" & $EpNum & " - " & $EpName & "." & $StrExt
                                                                                 ; MsgBox(0, "New Line 2 ADD ", $Newline2Add)
             FileWriteLine($RenameList, $Newline2Add)                            ; MsgBox(0, "WRITE THE STRING Line 2 ADD ", $line2Add)
         Else
             FileWriteLine($RenameList, $line2Add)                               ; MsgBox(0, "Write Unchanged line: ", $line2Add)
             EndIf
         EndIf                                                                   ; END OF : If (StringInStr($line2Add
     Wend
             FileClose($file)
EndIf                                                                            ; END OF $GetEpNum <> ""
     Else
     MsgBox(0, "ERROR : Saving File", $RenameList)
     EndIf                                                                               ; END OF : If Not FileExists ($RenameList)
Else
     MsgBox(0, "File not Found", $RenameList)
EndIf                                                                                    ; END OF : If FileExists ($RenameList) then
     ToolTip("", $ttX, $ttY)
EndFunc

; -------------------------------------------------- GET FileListData : Open List Read in names ------------------------------------------
; Get format Length of longest Line in FileRename List, Get Path to $RenameFileFolder, and Predict Season from FileName of the Rename list
; Calls GetEpisodeNumber to Get Global $SeasonInList to Predict Season of FileNames in Rename List if Full Episode List was Choosen

Func GetFileListData()
$RenameFileFolder = ""
     $GotFileListData = False
ToolTip("", $ttX, $ttY)
ToolTip(" Checking Rename List ", $ttX, $ttY)
$TmpLen = 0
$S1 = ""
$S2 = ""
$S1Count = 0
$S2Count = 0
$STmp = ""

If FileExists ($RenameList) then
If $DoDebug Then                                                                             ; Write Debug info to Debug file
     If FileExists($DebugTxt) Then FileDelete($DebugTxt)
     FileWriteLine ( $DebugTxt, "Series Name = " & $SeriesName )
     FileWriteLine ( $DebugTxt, "IMDB Season Selected : SeasonStr = " & $SeasonStr )
     FileWriteLine ( $DebugTxt, "IMDB Webpage URL = " & _FF_GetCurrentURL() )
EndIf

$File = FileOpen($RenameList, 0)
If $File = -1 Then Exit                                                                      ; If file OPEN ERROR - EXIT
     While 1                                                                                         ; Read in lines until EOF is reached
         $line2DL = FileReadLine($File)
         If @error = -1 Then ExitLoop
If (StringInStr($line2DL,"Check - Edit",0)= 0) Then
     If (StringInStr($line2DL,"Folder=",0)<> 0) Then
     $RenameFileFolder = StringReplace (GetStrInStr($line2DL, "Folder=", "=", ""),"=","")
                 $GotFileListData = True                                                         ; MsgBox(0,"Rename File Folder",$RenameFileFolder)
     Else                                                                                            ; List of filenames only
GetEpisodeNumber($line2DL, "")                                                           ; Get Season from file names
If StringIsInt($SeasonInList) Then
If ($S1 = "") Then $S1 = $SeasonInList                                               ; Found 1st Season in List
If ($S1 = $SeasonInList) Then $S1Count = $S1Count + 1                                ; Keep count of 1st Season found
                 If ($S2 = "") and ($S2 <> $S1) Then $S2 = $SeasonInList                                 ; Found a different Season
If ($S2 = $SeasonInList) Then $S2Count = $S2Count + 1                                ; Keep count of 2nd Season found
ToolTip(" Season of File List : " & $S1, $ttX, $ttY)
Sleep(20)
ToolTip(" Season of File List : " & $S2, $ttX, $ttY)
Sleep(20)
EndIf
If StringLen($line2DL) > $TmpLen Then $TmpLen = StringLen($line2DL)          ; Get length of longest filename in list
             EndIf
         EndIf
     Wend
FileClose($file)
Else
     MsgBox(0, "File not Found : List of IMDB Episodes", $RenameList)
EndIf
$MaxLen = $TmpLen + 3                                                                ; Return Maximum String Length

If $S1Count > 0 Then $STmp = $S1                                                             ; Season = 1st Season found in List
If ($S2Count > 0) and ($S2Count > $S1Count) Then $STmp = $S2                                 ; if 2nd Find found more times then use it

If $SeasonStr = "" Then                                                                  ; Season not selected from IMDB Webpage
If $STmp <> "" Then $SeasonStr = $STmp                                                   ; Use Season from Scan of File List
         While not StringIsInt($SeasonStr)                                                       ; ASK USER : Not in List, or Webpage Selection
             $SeasonStr = InputBox ( "IMDB Episode List SEASON", "Enter Season for IMDB Episode List", "1","",375,150)
             If @error Then DoQuit()
Wend
EndIf

If $DoDebug Then                                                                             ; Write Debug info to Debug file
     FileWriteLine ( $DebugTxt, "Files Folder = " & $RenameFileFolder )
     FileWriteLine ( $DebugTxt, "Season of File List = " & $STmp & @CRLF )
     FileWriteLine ( $DebugTxt, "Maximum Length to Format Files Names = " & $MaxLen )
     EndIf

ToolTip("", $ttX, $ttY)
     Return $GotFileListData
EndFunc

; -------------------------------------------- Get List of Files to Rename and Create Rename List -----------------------------------------------
Func GetFileList()
ToolTip("", $ttX, $ttY)
ToolTip(" Select Files - Season " & $SeasonStr & " of " & $SeriesName , $ttX, $ttY)

$message = "Select Files: Hold Ctrl or Shift : Mouse or Arrow Keys for multiple files."      ; Multiple filter group
; File Type Filter
$F1 = "Videos (*.avi;*.wmv;*.divx;*mpg;*.mkv;*flv;*.ogg;*.ogm;*.ogv;*.f4v;*.mov;*.mp4;*.mpe;*.m4v;*.mpv;*.m1v;*.dat;*vob;"
$F2 = "*asf;*.qt;*.3gp;*.3g2;*.m4v;*.rm;*.rmvb;*.m2ts;*.mts;*.tod;*.vro;*.dv;*.amv;*.ts;*.tp;*.m2t;*.dvr-ms;*.m)|All Files(*.*)"
$var = FileOpenDialog($message, "", $F1 & $F2, 1 + 4 )

If @error Then
MsgBox(4096,"Exit Program"," No File(s) chosen ... ")
     DoQuit()
Else
If StringInStr($var,"|") = 0 Then $var = StringReplace($var,"\","|",-1)                  ; Only 1 File Selected Replace Last \ with |
$var = StringReplace($var,"|","||",1)                                                    ; Replace 1st | With || for 2 carriage returns
     $var = StringReplace($var, "|", @CRLF)                                                  ; Relace all others with carriage return
; MsgBox(4096,"","You chose " & $var)

$File = FileOpen($RenameList, 2)                                                         ; Open the Rename list
If $File = -1 Then Exit                                                                  ; if file opened for reading ERROR EXIT
FileWriteLine($RenameList, "Check - Edit File Names - Save ... Close NotePad [x] to Continue" & @CRLF & @CRLF)
FileWriteLine($RenameList, "Folder=" & $var)
FileClose($file)
EndIf
     ToolTip("", $ttX, $ttY)
EndFunc

; ------------------------------------------------------ Get Season of Series Title Name --------------------------------------------------
; Gets Season from Webpage link URL

Func GetSeason()
ToolTip("", $ttX, $ttY)
ToolTip(" SEASON of Episode List ", $ttX, $ttY)
$TmpStr = ""
$SeasonStr = ""
$SrcLink = _FF_GetCurrentURL()                                                                   ; MsgBox(0, "SrcLink", $SrcLink)
If StringInStr( $SrcLink,"episodes#") > 0 then                   ; example: http://www.imdb.com/title/tt0073972/episodes#season-2
     $TmpStr = StringReplace(GetStrInStr( $SrcLink, "episodes#season", "-", ""),"-","")
Endif
If StringIsInt($TmpStr) Then
$SeasonStr = $TmpStr
     EndIf
ToolTip("", $ttX, $ttY)
ToolTip(" SEASON : " & $SeasonStr, $ttX, $ttY)
sleep(250)
ToolTip("", $ttX, $ttY)
EndFunc

; ---------------------------------------------------------- Get Series Name ---------------------------------------------------------------
; Reads Webpage SourceCode to get SERIES NAME for Formated Name in File Rename List, if unable to get then ASK USER

Func GetSeriesName()
ToolTip("", $ttX, $ttY)
ToolTip(" Get Season Name ", $ttX, $ttY)
$sTitle = _FFCmd(".title")
; MsgBox(0, "Series TITLE", $sTitle)
$Series = StringLeft($sTitle, StringInStr($sTitle, '('))
     $Series = StringReplace($Series,'(',"")

$Series = StringStripWS ( $Series, 1 )
$Series = StringStripWS ( $Series, 2 )
$Series = StringStripWS ( $Series, 4 )

$Series = StringReplace($Series,"&","And")
; MsgBox(0, "Series NAME 1", $Series)

$Series = StringRegExpReplace($Series, "[\\\-\_\.\,\(\)\!\{\}\+\=\?\#\~\<\>\'\|\`\/\%\^\*\@\;\:]", "")
If StringInStr($Series,":") > 0 Then
$Series = GetStrInStr( $Series, $Series, $Series, ":")               ; Get short Version of Series Name
Endif
If $Series = "" Then
$Series = InputBox ( "Get Series NAME", "Enter Series NAME for IMDB Episode List", $Series,"",375,150)
     If @error or ($Series = "") Then DoQuit()
EndIf

$Series = StringStripWS ( $Series, 1 )
$Series = StringStripWS ( $Series, 2 )
$Series = StringStripWS ( $Series, 4 )

$SeriesName = $Series
; MsgBox(0, "Series NAME fixed", $SeriesName)
ToolTip("", $ttX, $ttY)
ToolTip($SeriesName & " Season " & $SeasonStr, $ttX, $ttY)
Sleep(250)
ToolTip("", $ttX, $ttY)
EndFunc

; ------------------------------------------------------------ RENAME FILES --------------------------------------------------------------------
; Uses Windows NotePad to View and Edit Rename List before Renaming Files
; Open Rename List, ask user if want to rename, and Rename the Selected Files, Report Count of Errors and count of Files Renamed

Func RenameFiles()
$FileCount = 0
$ErrorCount = 0
ToolTip("", $ttX, $ttY)
ToolTip(" Check - Edit Rename List ", $ttX, $ttY)
MsgBox (0, 'Check - Edit Rename List', "Check, or Edit list - Save, and Close Notepad [x] to Continue" ,6)
ShellExecuteWait ( "notepad.exe", $RenameList, @ScriptDir, "open", @SW_SHOWNORMAL )
$SaveNow = MsgBox (1, "Confirm Rename Files", "Do you want to Rename Files ?")
If $SaveNow <> 1 Then Return                                                 ; Exit if Rename canceled

If FileExists ($RenameList) then                                                     ; Check if IMDB-Rename.txt exists
     $File = FileOpen($RenameList, 0)                                                ; Open Rename list
     If $File = -1 Then Exit                                                         ; if file opened for reading ERROR EXIT
     While 1                                                                         ; Read in lines of text until the EOF is reached
         $line2Ren = FileReadLine($File)                                             ; Get a line
         If @error = -1 Then ExitLoop
If ($line2Ren <> "") and (StringInStr($line2Ren,"Check - Edit",0)= 0) and (StringInStr($line2Ren,"Folder=",0)= 0) Then
$EpFileName = StringStripWS(StringStripWS(StringReplace(StringLeft($line2Ren, StringInStr($line2Ren,">")),">",""),1),2)
$EpFileName = $RenameFileFolder & "\" & $EpFileName                      ; MsgBox(0, "Episode File to Rename", $EpFileName)
         $NewFileName = StringStripWS(StringStripWS(StringReplace(GetStrInStr( $line2Ren, ">", ">", ""),">",""),1),2)
If $NewFileName <> "" Then
     $NewFileName = $RenameFileFolder & "\" & $NewFileName               ; MsgBox(0, "New File Name to Rename File", $NewFileName)
     If FileExists($EpFileName) Then                                         ; MsgBox(0, "File Exists", $EpFileName)
     FileMove ( $EpFileName, $NewFileName , 0 )
     $FileCount = $FileCount + 1                                         ; Increment Files Done
     If Not FileExists($NewFileName) Then $ErrorCount = $ErrorCount + 1 ; Increment Error Count
     Else
MsgBox(0, "ERROR: File Not Found", $EpFileName)
ToolTip(" File Rename Errors ", $ttX, $ttY)
         EndIf
Else
$ErrorCount = $ErrorCount + 1                                        ; A New File Name Doesn't Exist Increment Error Count
ToolTip(" File Rename Errors ", $ttX, $ttY)
EndIf
Endif
Wend
             FileClose($file)
If $ErrorCount > 0 Then MsgBox(0, "FILE RENAME : ERROR", "( " & $ErrorCount & " ) Files were not Renamed")
If $FileCount > 0 Then MsgBox(0, "FILE RENAME : SUCESS", "( " & $FileCount & " ) Files were Renamed")
Else
         MsgBox(0, "File not Found", $RenameList)
EndIf
     ToolTip("", $ttX, $ttY)
EndFunc

; ----------------------------------------------------- Open IMDB SEARCH WEBPAGE --------------------------------------------------------------
; Open IMDB Webpage Search, Get Title Name, Get Season to Rename, or Full Episode List, If Error Ask user for Search Link, Esc Key = Quit
; Searchbar: /html/body/div[1]/div[2]/layer/div[1]/div[2]/form/div/input ; id="navbar-query" name="q" ; BUTTON Go class="nb_primary" type="submit"

Func ImdbSearch()
$ImdbLink = "http://www.imdb.com/search/"

ToolTip("", $ttX, $ttY)
ToolTip(" Opening IMDB Search ", $ttX, $ttY)
_FFOpenURL($ImdbLink)                                                                        ; Open IMDB Search Webpage
CheckLoadError()
$SrcLink = _FF_GetCurrentURL()

If (StringInStr( $SrcLink,$ImdbLink)= 0) Then                                                ; Error Loading search ask user
     $SrcLink = InputBox( "ERROR LOADING IMDB SEARCH", "Enter Link : IMDB Title Name Search", $ImdbLink,"",375,150)
     If @error or ($SrcLink = "") Then DoQuit()

If (StringInStr( $SrcLink,"imdb.com")<> 0) Then                                      ; Open user Provided Link
     ToolTip("", $ttX, $ttY)
         ToolTip(" Opening IMDB Website ", $ttX, $ttY)
         _FFOpenURL($SrcLink)
         CheckLoadError()
         EndIf
EndIf

ToolTip("", $ttX, $ttY)                                                                  ; Show Help Information
ToolTip(" Search for Series Title Name ", $ttX, $ttY)
MsgBox (0, 'IMDB EPISODE RENAMER SEARCH', "Search for TV Series Title [ NAME ] and Select [ SEASON ] ... Hold Esc Key to Quit" ,2 )
ToolTip("", $ttX, $ttY)

MouseMove ( (@DesktopWidth / 2)-120, (@DesktopHeight / 5) )                              ; move mouse near Search Bar at top
While 1
         $SrcLink = _FF_GetCurrentURL()                                                      ; Get Webpage link Address
If (StringInStr( $SrcLink,"imdb.com/find?s=all") <> 0) Then
ToolTip(" Select a Title from List ")                                                ; List : Page of titles to select
Else
     ToolTip(" Search - Series Title Name & Click [ Go ]")                               ; Blink help at mouse pointer
EndIf
     Sleep(500)
ToolTip("")
If (StringInStr( $SrcLink,"/title/") <> 0) Then ExitLoop                                 ; Title Selected Go get season
Sleep(250)
     If Not WinExists("[CLASS:MozillaWindowClass]") Then DoQuit()                            ; Firefox window closed
If EscKeyPressed() Then Ask2Quit()                                                   ; If user pressed Esc Ask if Quit
WEnd

ToolTip(" Please Wait ")
_FFLoadWait()
ToolTip("", $ttX, $ttY)

MouseMove ( (@DesktopWidth / 4), @DesktopHeight - (@DesktopHeight / 5) )                     ; Move mouse near Seasons at bottom
While 1
     $SrcLink = _FF_GetCurrentURL()                                                      ; Get Webpage link Address
ToolTip(" Select Season or Full Episode List")
     Sleep(500)
ToolTip("")
If (StringInStr( $SrcLink,"episodes") <> 0) Then ExitLoop                                ; Season or Full Episode list selected
Sleep(250)
If Not WinExists("[CLASS:MozillaWindowClass]") Then DoQuit()                             ; Firefox window closed
If EscKeyPressed() Then Ask2Quit()                                                   ; If user pressed Esc Ask if Quit
WEnd

ToolTip(" Please Wait ")
_FFLoadWait()
ToolTip("", $ttX, $ttY)

ToolTip(" Reading Webpage ", $ttX, $ttY)
EndFunc

; *********************************************************** MAIN BODY OF PROGRAM **********************************************************

ToolTip(" Starting FireFox ", $ttX, $ttY)
_FFStart()
$Socket = _FFConnect()

If _FFIsConnected() Then                                                                             ; If MozRepl AddOn and firefox connected
ToolTip(" Maximize ", $ttX, $ttY)                                                                ; Maximize Window
_FFAction("Maximize")

     While ($DoContinue = 6)                                                                         ; User Selected Continue in Msgbox
         $WebpageSourceCode = ""
     ImdbSearch()                                                                                ; Open search get title & season
     $WebpageSourceCode = _FFReadHTML()                                                      ; Read Webpage Html Source Code
     GetSeason()                                                                                 ; Get Season from Webpage URL
     GetSeriesName()                                                                             ; Get Series Name from Webpage
     GetFileList()                                                                           ; Get User Selected list of files to rename

     If GetFileListData() Then                   ; GetFileListData -- Check file exists, Get format info & Predict season from filelist
     CreateRenameList()                      ; Scan WebpageSourceCode & File List: for Episode Name, and Create Rename List
RenameFiles()                            ; User Verify or Edits List, and then Asks if want to Rename
     ToolTip("", $ttX, $ttY)                     ; If user cancel by return then clear tooltip
         Else ; --------------------------------------------- File Not Found ERROR ----------------------------------------------------
         MsgBox(0, "File Not Found", "List of Files to Rename : Imdb - Rename.txt")
         EndIf ; ---------------------------------------------- END of GetFileListData --------------------------------------------------

     DeleteCookies()
     $DoContinue = MsgBox (4, "IMDB EPISODE RENAMER", "Do you want to Search & Rename another Series ?")
     Wend
Else
MsgBox(0,"Error: Unable to Connect", "FireFox with MozRepl AddOn Required !")
EndIf ; ------------------------------------------------ End If _FFIsConnected () -----------------------------------------------

ToolTip(" Quiting FireFox ", $ttX, $ttY)
_FFQuit ()
ToolTip("", $ttX, $ttY)

ToolTip(" Shuting Done ", $ttX, $ttY)
Sleep(2000)
ToolTip("", $ttX, $ttY)

EXIT(0)
Edited by CountryBoy

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0