From 1048b80de4f5a3527f98ada1eb82484ab0e2a474 Mon Sep 17 00:00:00 2001 From: yuriy Date: Wed, 15 Feb 2023 23:35:29 -0500 Subject: [PATCH] Reworked pre-existing tab indexing for re-using tabs --- Freedomain Video Uploader.ahk | 6 +- Lib/SharedFunctions.ahk | 922 +++++++++++++++++----------------- 2 files changed, 466 insertions(+), 462 deletions(-) diff --git a/Freedomain Video Uploader.ahk b/Freedomain Video Uploader.ahk index fd9bcd2..99f1578 100644 --- a/Freedomain Video Uploader.ahk +++ b/Freedomain Video Uploader.ahk @@ -2214,7 +2214,7 @@ if(!InStr(LocalsPostPageURL, "/share/post")){ } ; replace any double slashes that migth have come from the combining -LocalsPostPageURL := StrReplace(LocalsPostPageURL, "//", "/") +; LocalsPostPageURL := StrReplace(LocalsPostPageURL, "//", "/") Status := NavigateFromBaseURLTo(LocalsPostPageURL) @@ -5109,7 +5109,7 @@ if(VideoThumbFilepath != "") { ; @todo: Add a check to see if progress gets stuck ; Check Upload Percentage - TooltipThis("Waiting for Video to Finish Uploading`nChecking Progress Every 5 Seconds") + TooltipThis("Waiting for Video to Finish Uploading") Loop, %Number_of_loops_to_Check_Upload_status% { sleep, %Time_Between_Loops_Upload_Status% @@ -5167,7 +5167,7 @@ js = document.getElementById('submitForm').click(); try driver.executeScript(js) ; -driver.executeScript("return document.readyState").equals("complete") ; wait until page loads completely before proceeding +try driver.executeScript("return document.readyState").equals("complete") ; wait until page loads completely before proceeding ; Select Rumble Only Licensing diff --git a/Lib/SharedFunctions.ahk b/Lib/SharedFunctions.ahk index 0fd6f6b..db79ccc 100644 --- a/Lib/SharedFunctions.ahk +++ b/Lib/SharedFunctions.ahk @@ -104,56 +104,56 @@ UpdateScript(){ - ; -------------------------------SaveOrPostProgress------------------------------- - ; PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar,DiscordErrorLogging,DiscordVideos" - SaveOrPostProgress(Message:="",PostType:=""){ +; -------------------------------SaveOrPostProgress------------------------------- +; PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar,DiscordErrorLogging,DiscordVideos" +SaveOrPostProgress(Message:="",PostType:=""){ - MessageBU := Message - ; Msgbox % "PostType: " PostType - ; Msgbox % "CurrentSite: " CurrentSite + MessageBU := Message + ; Msgbox % "PostType: " PostType + ; Msgbox % "CurrentSite: " CurrentSite - if(CurrentSite != "") - Message := CurrentSite . ": " . Message + if(CurrentSite != "") + Message := CurrentSite . ": " . Message - if(InStr(PostType, "Tooltip")){ - TooltipThis(Message) - } - if(InStr(PostType, "ErrorLoggingTextFile")){ - Func_LogErrorsToTextFile(Message) - } - if(InStr(PostType, "ErrorSummaryVar")){ - Func_LogErrorsToVar(Message) - } - if(InStr(PostType, "DiscordErrorLogging")){ - PostToDiscordChannel(Message,DiscordErrorLoggingWebhookBotURL) - } - if(InStr(PostType, "DiscordVideos")){ - Message := MessageBU - PostToDiscordChannel(Message,DiscordVideosWebhookURL) - } - if(InStr(PostType, "DiscordParler")){ - Message := MessageBU - PostToDiscordChannel(Message,DiscordParlerWebhookURL) - } + if(InStr(PostType, "Tooltip")){ + TooltipThis(Message) + } + if(InStr(PostType, "ErrorLoggingTextFile")){ + Func_LogErrorsToTextFile(Message) + } + if(InStr(PostType, "ErrorSummaryVar")){ + Func_LogErrorsToVar(Message) + } + if(InStr(PostType, "DiscordErrorLogging")){ + PostToDiscordChannel(Message,DiscordErrorLoggingWebhookBotURL) + } + if(InStr(PostType, "DiscordVideos")){ + Message := MessageBU + PostToDiscordChannel(Message,DiscordVideosWebhookURL) + } + if(InStr(PostType, "DiscordParler")){ + Message := MessageBU + PostToDiscordChannel(Message,DiscordParlerWebhookURL) + } - } - ; -------------------------------/SaveOrPostProgress------------------------------- - TakeScreenshotOfPage(SaveFilepath := ""){ +} +; -------------------------------/SaveOrPostProgress------------------------------- +TakeScreenshotOfPage(SaveFilepath := ""){ - if(!ScreenshotResult) - return + if(!ScreenshotResult) + return - TooltipThis("Sleeping 5 Seconds Before Taking Screenshot") - ; sleep, 5000 + TooltipThis("Sleeping 5 Seconds Before Taking Screenshot") + ; sleep, 5000 - if(SaveFilepath = ""){ - SaveFilepath := ErrorLoggingDirectory - } + if(SaveFilepath = ""){ + SaveFilepath := ErrorLoggingDirectory + } - ; if(!FileExist(SaveFilepath)) - FileCreateDir, %SaveFilepath% + ; if(!FileExist(SaveFilepath)) + FileCreateDir, %SaveFilepath% /* if(!TakeScreenshotsOfErrors) Return @@ -785,12 +785,14 @@ CreateArrayOfTabs() { Message = Creating an Array of All Chrome Tabs SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile") - DriverTitleArray := [] ; Create an array + ; Create an arrays + DriverTitleArray := [] DriverURLArray := [] try TotalTabsFound := Driver.Windows.Count + ; DevModeMsgBox(TotalTabsFound) - ; if only 1 tab exists, grab info, push to array and exit early +/* ; if only 1 tab exists, grab info, push to array and return if(TotalTabsFound = 1){ try Title := Driver.Title try URL := Driver.URL @@ -802,6 +804,7 @@ CreateArrayOfTabs() { return } + */ ; Msgbox % "TotalTabsFound: " TotalTabsFound ; if(DevMode) ; Msgbox % "TotalTabsFound: " TotalTabsFound @@ -813,14 +816,18 @@ CreateArrayOfTabs() { ; Sleep, 1000 StartTime := A_TickCount - Loop, { - Message = Creating an Array of All Chrome Tabs`nCurrent Loop: %A_index%/%TotalTabsFound% (Cannot loop through unloaded tabs)`nSometimes might get stuck for a short while if there is something loading in active tab - TooltipThis(Message) - ; SaveOrPostProgress(Message:=URL,PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar") - ; if(ArrayContainsURL = 3 AND A_index > TotalTabsFound) - ; Break + ; 5 is arbitrary number to do some extra loops to make sure all tabs are gone through + ; most likely not necessary because unloaded tabs cannot be activated + TotalLoops := TotalTabsFound + 5 + Loop % TotalLoops { + Message = Creating an Array of All Chrome Tabs`nCurrent Loop: %A_index%/%TotalLoops% (Cannot check on unloaded tabs)`nSometimes might get stuck for a short while if there is something loading in active tab + TooltipThis(Message) + + ; exit after looping through 1 tab, if only 1 tab found in count + if(TotalTabsFound = 1 AND A_index > TotalTabsFound) + return TabEndTime := A_TickCount - TabFoundStartTime TabEndTimeArray .= TabEndTime . "," @@ -831,495 +838,492 @@ CreateArrayOfTabs() { TabFoundStartTime := A_TickCount + if(TotalTabsFound < 4 AND A_index = 4) + break + ; TimeToGrabCurrentTab := A_TickCount - StartTime + ; Msgbox % "TimeToGrabCurrentTab: " TimeToGrabCurrentTab - IndexMinus3 := A_index - 3 - ; if(FirstURLPosition AND SecondURLPosition AND ThirdURLPosition AND IndexPlus3 > TotalTabsFound OR A_index = 30) { - if(IndexMinus3 > TotalTabsFound) { - ; DevModeMsgBox("First 3 tabs found. Breaking") - ; Msgbox % "A_index: " A_index "`n" "IndexPlus3: " IndexPlus3 - break + ; Stop page refresh if it's happening + ; try driver.executeScript("return window.stop") - } + try Title := Driver.Title + try URL := Driver.URL - if(TotalTabsFound < 4 AND A_index = 4) - break - ; TimeToGrabCurrentTab := A_TickCount - StartTime - ; Msgbox % "TimeToGrabCurrentTab: " TimeToGrabCurrentTab + ; TimeToGrabCurrentTab := A_TickCount - StartTime + ; Msgbox % "TimeToGrabCurrentTab: " TimeToGrabCurrentTab + ; VAR := HasVal(DriverURLArray, STRINGVAR) ; returns position of value in array - ; Stop page refresh if it's happening - ; try driver.executeScript("return window.stop") - try Title := Driver.Title - try URL := Driver.URL + if(HasVal(DriverURLArray, URL)){ ; returns position of value in array + Continue + } - ; TimeToGrabCurrentTab := A_TickCount - StartTime - ; Msgbox % "TimeToGrabCurrentTab: " TimeToGrabCurrentTab - ; VAR := HasVal(DriverURLArray, STRINGVAR) ; returns position of value in array - if(HasVal(DriverURLArray, URL)) ; returns position of value in array - { - URLPositionInArray := HasVal(DriverURLArray, URL) - if(URLPositionInArray = 1){ - FirstURLPosition := 1 - } - if(URLPositionInArray = 2){ - SecondURLPosition := 1 - } - if(URLPositionInArray = 3){ - ThirdURLPosition := 1 - } - if(URLPositionInArray = 4){ - FourthURLPosition := 1 - } - ; Msgbox % "PositionInArray: " PositionInArray - ; ArrayContainsURL += 1 - } - ; TimeToCheckArray := A_TickCount - StartTime - - ; Msgbox % "ArrayContainsURL: " ArrayContainsURL - - if(Title != "") - DriverTitleArray.Push(Title) - if(URL != "") - DriverURLArray.Push(URL) - -/* -if(TotalTabsFound = 1){ - TimeToKickOut := A_TickCount - StartTime - - ; Msgbox % "TimeToGrabCurrentTab: " TimeToGrabCurrentTab - ; Msgbox % "TimeToCheckArray: " TimeToCheckArray - ; Msgbox % "TimeToKickOut: " TimeToKickOut - ; MsgBox, %ElapsedTime% milliseconds have elapsed. - ; Msgbox % "A_index: " A_index - ; DevModeMsgBox("breaking early on loop 1?") - break - } ; if there is only 1 tab, then break out of loop and don't bother looping through same tab - - */ - try driver.SwitchToNextWindow ;Focuses Selenium on the newly opened/next window. - } ; end of loop - - ; Iterate from 1 to the end of the array: - Loop % DriverURLArray.Length() - { - ARRAYNAMEList .= DriverURLArray[A_Index] . "`n" - ; ArrayItem := DriverURLArray[A_Index] - ; MsgBox % DriverURLArray[A_Index] - } - ; Msgbox % "ARRAYNAMEList: " ARRAYNAMEList - - TimeToLoopThroughAllTabs := A_TickCount - StartTime - Message = Time to Loop through all tabs: %TimeToLoopThroughAllTabs% - SaveOrPostProgress(Message:=Message,PostType:="ErrorLoggingTextFile,DiscordErrorLogging") - ; DevModeMsgBox(Message) - return - } ; /FUNC - - InputFilePathIntoOpenWindow(Filepath){ - ; Msgbox % "Filepath: " Filepath - Message = Waiting for "Open" window to appear to input filepath into - SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile") - ; Tooltip,Waiting for "Open" window to appear to input filepath into,850,0 - ; WinWait, Open - WinWait,Open,,5 ; Wait for 10 seconds for window - if(ErrorLevel) - { - ; msgbox, failed to find window. - Return "Failed" - } - WinActivate, Open - sleep, 1000 - ControlSetText, Edit1, %Filepath%, Open - sleep, 1000 - ControlSend, Edit1, {Enter}, Open - sleep, 1000 - - ; Do an extra check in case the Open window is still open. - OpenWindowExist := WinExist("Open") - if(OpenWindowExist) - ControlSend, Edit1, {Enter}, Open - ToolTip, - } - ; -------------------------------NavigateFromBaseURLTo------------------------------- - NavigateFromBaseURLTo(URL,PageTitle := "New Tab"){ - if(!DriverStatus){ ; if not connected to selenium chrome, then re-connect - Status := CheckSeleniumDriver() - if(Status) - Return "Failed" - - CreateArrayOfTabs() - } + if(Title != "") + DriverTitleArray.Push(Title) + if(URL != "") + DriverURLArray.Push(URL) - if(ReuseTabs){ - URLBase := StrReplace(URL,"https://","") - URLBase := StrSplit(URLBase, "/") - URLBase := URLBase[1] - URLBase := StrReplace(URLBase, "www.","") - } + try driver.SwitchToNextWindow ;Focuses Selenium on the newly opened/next window. + } ; end of loop - if(!HasSubstringVal(DriverURLArray, URLBase)) ; returns position of value in array - { - try, run "%ChromeFilepath%" "%URL%" - DriverURLArray.Push(URL) ; Append an item to the array - NewTabCreated := 1 - sleep, 1000 - } - ; msgbox, + ; TimeToLoopThroughAllTabs := A_TickCount - StartTime + ; Message = Time to Loop through all tabs: %TimeToLoopThroughAllTabs% + ; SaveOrPostProgress(Message:=Message,PostType:="ErrorLoggingTextFile,DiscordErrorLogging") + ; DevModeMsgBox(Message) + return + } ; /FUNC - Message = Finding Tab - SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile") + InputFilePathIntoOpenWindow(Filepath){ + ; Msgbox % "Filepath: " Filepath + Message = Waiting for "Open" window to appear to input filepath into + SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile") + ; Tooltip,Waiting for "Open" window to appear to input filepath into,850,0 + ; WinWait, Open + WinWait,Open,,5 ; Wait for 10 seconds for window + if(ErrorLevel) + { + ; msgbox, failed to find window. + Return "Failed" + } + WinActivate, Open + sleep, 1000 + ControlSetText, Edit1, %Filepath%, Open + sleep, 1000 + ControlSend, Edit1, {Enter}, Open + sleep, 1000 + + ; Do an extra check in case the Open window is still open. + OpenWindowExist := WinExist("Open") + if(OpenWindowExist) + ControlSend, Edit1, {Enter}, Open + ToolTip, + } - TabFoundSuccessfully := + ; -------------------------------NavigateFromBaseURLTo------------------------------- + NavigateFromBaseURLTo(URL,PageTitle := "TodoDeleteme"){ + if(!DriverStatus){ ; if not connected to selenium chrome, then re-connect + Status := CheckSeleniumDriver() + if(Status) + Return "Failed" - NumberOfTabLoops := DriverURLArray.Length() + CreateArrayOfTabs() + } - ; NumberOfTabLoops := Driver.Windows.Count + 2 - loop % NumberOfTabLoops { ; loop through tabs to find matching tab - try driver.SwitchToNextWindow() + ; Msgbox % CreateArrayOfTabs.Length() ; Display total number of items in the array + ArrayLenght := DriverURLArray.Length() ; Save total number of items in the array + ; Msgbox % "ArrayLenght: " ArrayLenght + ; Iterate from 1 to the end of the array: + /* + Loop % DriverURLArray.Length(){ + ; ArrayItem := CreateArrayOfTabs[A_Index] + MsgBox % DriverURLArray[A_Index] + } - ; sleep, 1000 - ; msgbox, looping through tabs - try CurrentTabTitle := driver.window.title - try CurrentTabURL := driver.Url - if(CurrentTabTitle = PageTitle OR InStr(CurrentTabURL, URLBase)){ - ; msgbox, found it.`n%CurrentTabTitle% = %PageTitle%`n%CurrentTabURL% = %URLBase% - TabFoundSuccessfully := 1 - ; msgbox %CurrentTabTitle% = %PageTitle% - ; msgbox %CurrentTabURL% = %URL% - Break - } - } - - if(!NewTabCreated){ ; if re-using a tab then we want to re-navigate to URL because it might be the wrong page - try driver.Get(URL) ;Open selected URL - try driver.executeScript("return document.readyState").equals("complete") ; wait until page loads completely before proceeding - catch e { - ; msgbox, error caught. trying something - try driver.switchToalert().accept() - try driver.Get(URL) ;Open selected URL - catch e { - Message = Failed to Navigate to %URL%: Please Check for Any Open Dialogue Boxes - SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar,DiscordErrorLogging") - Return "Failed" - } - } - } - ; msgbox, no error caught - ; } + */ + ; message = URL: %URL% + ; DevModeMsgBox(message) - Return - } - ; End of Function - ; -------------------------------/NavigateFromBaseURL------------------------------- + if(ReuseTabs){ + URLBase := StrReplace(URL,"https://","") ; remove beginning of URL + URLBase := StrSplit(URLBase, "/") ; remove text after url base + URLBase := URLBase[1] + URLBase := StrReplace(URLBase, "www.","") ; remove www if there 1 + } - SaveDriverURL(){ ; save the url of the result page. That way if a tab is not found for a site, we can open up a tab from this tab instead of middle of nowhere. That way we can keep the tabs together - try LastWebsitePostURL := driver.URL + ; Message = URLbase after cleaning: %URLBase%`nOriginal URL: %URL% + ; DevModeMsgBox(message) - return LastWebsitePostURL - } + ; check if URLBase is a substring within any of the values in the array + if(!HasSubstringVal(DriverURLArray, URLBase)) + { + ; DevModeMsgBox("Creating new tab") + try, run "%ChromeFilepath%" "%URL%" + DriverURLArray.Push(URL) ; Append the new url to the array + NewTabCreated := 1 + sleep, 1000 + } +/* + else, { + Message = %URLBase% is the urlbase and it's within the DriverURLArray + DevModeMsgBox(Message) + } + */ + ; msgbox, + Message = Finding Tab + SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile") + DevModeMsgBox(Message) - ; -------------------------------SChrome_Get------------------------------- - SChrome_Get(URL := "", Profile := "Profile 1", IP_Port := "127.0.0.1:9222"){ - IP_Port_Nr := RegExReplace(IP_Port, ".*:(\d*)", "$1") - if WinExist("ahk_exe Chrome.exe"){ - WinGet, pid, PID, ahk_exe chrome.exe - for item in ComObjGet("winmgmts:").ExecQuery("SELECT * FROM Win32_Process WHERE ProcessId='" pid "'"){ - if RegExMatch(item.CommandLine, "i)--remote-debugging-port=\K\d+", port){ - break - } - } + TabFoundSuccessfully := - if (Port=""){ - MsgBox, 36, ,Chrome Needs to be started in debugging mode in order for Autohotkey to connect to it.`nIs it ok to restart Chrome in debugmode to enable a connection? - IfMsgBox, Yes - { - Message = Restarting Chrome in Debug Mode - SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,DiscordErrorLogging") + NumberOfTabLoops := DriverURLArray.Length() - While(WinExist("ahk_exe chrome.exe")) { - WinClose, ahk_exe chrome.exe - } - Process, WaitClose, chrome.exe - } - Else{ - Msgbox, 4096, Error, Cannot connect to Chrome profile if it is Not running in debug mode. Script Terminating - ExitApp - ; @todo: Make this error out to the script result screen - } - } - } + ; NumberOfTabLoops := Driver.Windows.Count + 2 + loop % NumberOfTabLoops { ; loop through tabs to find matching tab + try driver.SwitchToNextWindow() - ; ; yuriy's settings - ; IniRead, ChromeFilepath, C:\Users\%A_username%\Documents\Autohotkey\Lib\ScriptSettings.ini, Selenium, %A_Computername%, %A_Space% + ; sleep, 1000 + ; msgbox, looping through tabs + try CurrentTabTitle := driver.window.title + try CurrentTabURL := driver.Url - ; ; Establish Variable with Filepath to be used throughout the script - ; if(ChromeFilepath = ""){ - if(FileExist("C:\Program Files\Google\Chrome\Application\chrome.exe")){ - ChromeFilepath = C:\Program Files\Google\Chrome\Application\chrome.exe - } - else if (FileExist("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe")){ - ChromeFilepath = C:\Program Files (x86)\Google\Chrome\Application\chrome.exe - } - + if(CurrentTabTitle = PageTitle OR InStr(CurrentTabURL, URLBase)){ - if(ChromeFilepath = ""){ - Message = Failed to find chrome.exe in the usual locations. - SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,DiscordErrorLogging") - MsgBox 0x30, Error!, Unable to find Chrome.exe in the usual locations. `nScript Exiting. - ExitApp - } + Message = Found Tab:.`n%CurrentTabTitle% = %PageTitle%`n%CurrentTabURL% = %URLBase% + DevModeMsgBox(message) - if(!winExist("ahk_exe chrome.exe")){ - run, %ChromeFilepath% --remote-debugging-port=%IP_Port_Nr% %URL% - } + TabFoundSuccessfully := 1 + ; msgbox %CurrentTabTitle% = %PageTitle% + ; msgbox %CurrentTabURL% = %URL% + Break + } - Driver := ComObjCreate("Selenium.ChromeDriver") - Driver.SetCapability("debuggerAddress", IP_Port) - try Driver.Start() - catch e { + ; / loop through tabs + } - ShowSeleniumErrorMsgbox() + if(!NewTabCreated){ ; if re-using a tab then we want to re-navigate to URL because it might be the wrong page - } ; end of catch + ; Double check that the current tab URL matches the url base + try, CurrentTabURl := driver.url + Message = Reusing Tab. `nCurrentTabURl: %CurrentTabURl%`nURL Navigating to: %URL% + DevModeMsgBox(Message) - ; Save current chrome version to ini file - return Driver - } - ; -------------------------------/SChrome_Get------------------------------- - - ShowSeleniumErrorMsgbox(){ - GetChromeVersionCommand = powershell (Get-Item '%ChromeFilepath%').VersionInfo.ProductVersion - Chromeversion := RunCMD(GetChromeVersionCommand) - ChromeVersion := StrReplace(ChromeVersion, "`n", "") - - ; Clipboard := ChromeVersion - ; Msgbox % "Chromeversion: " Chromeversion - IniRead, PreviousWorkingChromeVersion, Settings.ini, Misc, ChromeVersion, %A_Space% - ; IniWrite, %ChromeVersion%, Settings.ini, Misc, ChromeVersion - ; msgbox, failed to connect to Chrome for some reason. - ; Message = Failed to Connect to Chrome. Most likely problem is either Chrome has some sort of dialogue box open or ChromeDriver needs to be updated. - ; SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar,DiscordErrorLogging") - - OnMessage(0x44, "OnMsgBoxChromeDriverFailed") - MsgBox 0x40043, Error, Failed to Connect to Chrome. `nMost likely issue is either Chrome has some sort of dialogue box open or ChromeDriver needs to be updated.`n`nClick "Reload" to reload the script to try again`nClick "ChromeDriver" to open up the ChromeDriver download page. `n`nClick "Instructions" to open up .pdf file with instructions for updating chromedriver.exe`n`nPossibly Helpful Info:`nCurrent Chrome Version: %Chromeversion%Chrome Version of Last Successfull Upload: %PreviousWorkingChromeVersion% - OnMessage(0x44, "") - - IfMsgBox Yes, { - ; Reload script - Reload - } Else IfMsgBox No, { - run, https://chromedriver.chromium.org/downloads - ExitApp - ; open chromedriver site - } Else IfMsgBox Cancel, { - URL = https://freedomainplaylists.com/wp-content/FreedomainScripts/Update`%20Selenium`%20ChromeDriver.pdf - Filepath = %A_ScriptDir%\Lib\Update Selenium ChromeDriver.pdf - if(!FileExist(Filepath)){ - UrlDownloadToFile, %URL%, %Filepath% - - run, %Filepath% - } - ExitApp - - } - } + + try driver.Get(URL) ;Open selected URL + catch e { + Message = Failed to Navigate to URL in pre-existing tab`nPlease See Error #5648 for code section + SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar,DiscordErrorLogging") + ; SaveDriverURLOFErrorPage() + ; Return + + ; msgbox, error caught. trying something + try driver.switchToalert().accept() + try driver.Get(URL) ;Open selected URL + catch e { + Message = Failed to Navigate to %URL%: Please Check for Any Open Dialogue Boxes + SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar,DiscordErrorLogging") + Return "Failed" + } + } + try driver.executeScript("return document.readyState").equals("complete") ; wait until page loads completely before proceeding + } + ; msgbox, no error caught + ; } - ; -------------------------------HasVal------------------------------- - ; Function needed for finding a value in an array - HasVal(haystack, needle) - { - if !(IsObject(haystack)) || (haystack.Length() = 0) - return 0 - for index, value in haystack - if (value = needle) - return index - return 0 - } - ; -------------------------------/HasVal------------------------------- + Return +} +; End of Function +; -------------------------------/NavigateFromBaseURL------------------------------- - HasSubstringVal(haystack, needle) - { - if !(IsObject(haystack)) || (haystack.Length() = 0) - return 0 - for index, value in haystack - if (InStr(value, Needle)) - return index - return 0 - } +SaveDriverURL(){ ; save the url of the result page. That way if a tab is not found for a site, we can open up a tab from this tab instead of middle of nowhere. That way we can keep the tabs together + try LastWebsitePostURL := driver.URL + + return LastWebsitePostURL +} + + +; -------------------------------SChrome_Get------------------------------- +SChrome_Get(URL := "", Profile := "Profile 1", IP_Port := "127.0.0.1:9222"){ + IP_Port_Nr := RegExReplace(IP_Port, ".*:(\d*)", "$1") + if WinExist("ahk_exe Chrome.exe"){ + WinGet, pid, PID, ahk_exe chrome.exe + for item in ComObjGet("winmgmts:").ExecQuery("SELECT * FROM Win32_Process WHERE ProcessId='" pid "'"){ + if RegExMatch(item.CommandLine, "i)--remote-debugging-port=\K\d+", port){ + break + } + } + + if (Port=""){ + MsgBox, 36, ,Chrome Needs to be started in debugging mode in order for Autohotkey to connect to it.`nIs it ok to restart Chrome in debugmode to enable a connection? + IfMsgBox, Yes + { + Message = Restarting Chrome in Debug Mode + SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,DiscordErrorLogging") + + While(WinExist("ahk_exe chrome.exe")) { + WinClose, ahk_exe chrome.exe + } + Process, WaitClose, chrome.exe + } + Else{ + Msgbox, 4096, Error, Cannot connect to Chrome profile if it is Not running in debug mode. Script Terminating + ExitApp + ; @todo: Make this error out to the script result screen + } + } + } + + ; ; yuriy's settings + ; IniRead, ChromeFilepath, C:\Users\%A_username%\Documents\Autohotkey\Lib\ScriptSettings.ini, Selenium, %A_Computername%, %A_Space% + + ; ; Establish Variable with Filepath to be used throughout the script + ; if(ChromeFilepath = ""){ + if(FileExist("C:\Program Files\Google\Chrome\Application\chrome.exe")){ + ChromeFilepath = C:\Program Files\Google\Chrome\Application\chrome.exe + } + else if (FileExist("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe")){ + ChromeFilepath = C:\Program Files (x86)\Google\Chrome\Application\chrome.exe + } - ; SubStr(String, StartingPos [, Length]) - ; InStr(value, Needle) + if(ChromeFilepath = ""){ + Message = Failed to find chrome.exe in the usual locations. + SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,DiscordErrorLogging") + MsgBox 0x30, Error!, Unable to find Chrome.exe in the usual locations. `nScript Exiting. + ExitApp + } + if(!winExist("ahk_exe chrome.exe")){ + run, %ChromeFilepath% --remote-debugging-port=%IP_Port_Nr% %URL% + } + Driver := ComObjCreate("Selenium.ChromeDriver") + Driver.SetCapability("debuggerAddress", IP_Port) + try Driver.Start() + catch e { + ShowSeleniumErrorMsgbox() + } ; end of catch + ; Save current chrome version to ini file + return Driver + } + ; -------------------------------/SChrome_Get------------------------------- + + ShowSeleniumErrorMsgbox(){ + GetChromeVersionCommand = powershell (Get-Item '%ChromeFilepath%').VersionInfo.ProductVersion + Chromeversion := RunCMD(GetChromeVersionCommand) + ChromeVersion := StrReplace(ChromeVersion, "`n", "") + + ; Clipboard := ChromeVersion + ; Msgbox % "Chromeversion: " Chromeversion + IniRead, PreviousWorkingChromeVersion, Settings.ini, Misc, ChromeVersion, %A_Space% + ; IniWrite, %ChromeVersion%, Settings.ini, Misc, ChromeVersion + ; msgbox, failed to connect to Chrome for some reason. + ; Message = Failed to Connect to Chrome. Most likely problem is either Chrome has some sort of dialogue box open or ChromeDriver needs to be updated. + ; SaveOrPostProgress(Message:=Message,PostType:="Tooltip,ErrorLoggingTextFile,ErrorSummaryVar,DiscordErrorLogging") + + OnMessage(0x44, "OnMsgBoxChromeDriverFailed") + MsgBox 0x40043, Error, Failed to Connect to Chrome. `nMost likely issue is either Chrome has some sort of dialogue box open or ChromeDriver needs to be updated.`n`nClick "Reload" to reload the script to try again`nClick "ChromeDriver" to open up the ChromeDriver download page. `n`nClick "Instructions" to open up .pdf file with instructions for updating chromedriver.exe`n`nPossibly Helpful Info:`nCurrent Chrome Version: %Chromeversion%Chrome Version of Last Successfull Upload: %PreviousWorkingChromeVersion% + OnMessage(0x44, "") + + IfMsgBox Yes, { + ; Reload script + Reload + } Else IfMsgBox No, { + run, https://chromedriver.chromium.org/downloads + ExitApp + ; open chromedriver site + } Else IfMsgBox Cancel, { + URL = https://freedomainplaylists.com/wp-content/FreedomainScripts/Update`%20Selenium`%20ChromeDriver.pdf + Filepath = %A_ScriptDir%\Lib\Update Selenium ChromeDriver.pdf + if(!FileExist(Filepath)){ + UrlDownloadToFile, %URL%, %Filepath% + + run, %Filepath% + } + ExitApp - ; -------------------------------FileXPro Get File Attributes------------------------------- - ;https://www.autohotkey.com/boards/viewtopic.php?t=59882 + } + } - Filexpro( sFile := "", Kind := "", P* ) { ; v.90 By SKAN on D1CC @ goo.gl/jyXFo9 - Local - Static xDetails - If ( sFile = "" ) - { ; Deinit static variable - xDetails := "" - Return - } + ; -------------------------------HasVal------------------------------- + ; Function needed for finding a value in an array + HasVal(haystack, needle) + { + if !(IsObject(haystack)) || (haystack.Length() = 0) + return 0 + for index, value in haystack + if (value = needle) + return index + return 0 + } + ; -------------------------------/HasVal------------------------------- - fex := {}, _FileExt := "" + HasSubstringVal(haystack, needle) + { + if !(IsObject(haystack)) || (haystack.Length() = 0) + return 0 + for index, value in haystack + if (InStr(value, Needle)) + return index + return 0 + } - Loop, Files, % RTrim(sfile,"\*/."), DF - { - If not FileExist( sFile:=A_LoopFileLongPath ) - { - Return - } + ; SubStr(String, StartingPos [, Length]) - SplitPath, sFile, _FileExt, _Dir, _Ext, _File, _Drv + ; InStr(value, Needle) - If ( p[p.length()] = "xInfo" ) ; Last parameter is xInfo - { - p.Pop() ; Delete parameter - fex.SetCapacity(11) ; Make room for Extra info - fex["_Attrib"] := A_LoopFileAttrib - fex["_Dir"] := _Dir - fex["_Drv"] := _Drv - fex["_Ext"] := _Ext - fex["_File"] := _File - fex["_File.Ext"] := _FileExt - fex["_FilePath"] := sFile - fex["_FileSize"] := A_LoopFileSize - fex["_FileTimeA"] := A_LoopFileTimeAccessed - fex["_FileTimeC"] := A_LoopFileTimeCreated - fex["_FileTimeM"] := A_LoopFileTimeModified - } - Break - } - If Not ( _FileExt ) ; Filepath not resolved - { - Return - } - objShl := ComObjCreate("Shell.Application") - objDir := objShl.NameSpace(_Dir) - objItm := objDir.ParseName(_FileExt) - If ( VarSetCapacity(xDetails) = 0 ) ; Init static variable - { - i:=-1, xDetails:={}, xDetails.SetCapacity(309) - While ( i++ < 309 ) - { - xDetails[ objDir.GetDetailsOf(0,i) ] := i - } + ; -------------------------------FileXPro Get File Attributes------------------------------- + ;https://www.autohotkey.com/boards/viewtopic.php?t=59882 - xDetails.Delete("") - } + Filexpro( sFile := "", Kind := "", P* ) { ; v.90 By SKAN on D1CC @ goo.gl/jyXFo9 + Local + Static xDetails - If ( Kind and Kind <> objDir.GetDetailsOf(objItm,11) ) ; File isn't desired kind - { - Return - } + If ( sFile = "" ) + { ; Deinit static variable + xDetails := "" + Return + } - i:=0, nParams:=p.Count(), fex.SetCapacity(nParams + 11) + fex := {}, _FileExt := "" - While ( i++ < nParams ) + Loop, Files, % RTrim(sfile,"\*/."), DF + { + If not FileExist( sFile:=A_LoopFileLongPath ) { - Prop := p[i] + Return + } - If ( (Dot:=InStr(Prop,".")) and (Prop:=(Dot=1 ? "System":"") . Prop) ) - { - fex[Prop] := objItm.ExtendedProperty(Prop) - Continue - } + SplitPath, sFile, _FileExt, _Dir, _Ext, _File, _Drv - If ( PropNum := xDetails[Prop] ) > -1 - { - fex[Prop] := ObjDir.GetDetailsOf(objItm,PropNum) - Continue - } - } + If ( p[p.length()] = "xInfo" ) ; Last parameter is xInfo + { + p.Pop() ; Delete parameter + fex.SetCapacity(11) ; Make room for Extra info + fex["_Attrib"] := A_LoopFileAttrib + fex["_Dir"] := _Dir + fex["_Drv"] := _Drv + fex["_Ext"] := _Ext + fex["_File"] := _File + fex["_File.Ext"] := _FileExt + fex["_FilePath"] := sFile + fex["_FileSize"] := A_LoopFileSize + fex["_FileTimeA"] := A_LoopFileTimeAccessed + fex["_FileTimeC"] := A_LoopFileTimeCreated + fex["_FileTimeM"] := A_LoopFileTimeModified + } + Break + } + + If Not ( _FileExt ) ; Filepath not resolved + { + Return + } + + + objShl := ComObjCreate("Shell.Application") + objDir := objShl.NameSpace(_Dir) + objItm := objDir.ParseName(_FileExt) + + If ( VarSetCapacity(xDetails) = 0 ) ; Init static variable + { + i:=-1, xDetails:={}, xDetails.SetCapacity(309) - fex.SetCapacity(-1) - Return fex + While ( i++ < 309 ) + { + xDetails[ objDir.GetDetailsOf(0,i) ] := i + } - } ;- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + xDetails.Delete("") + } + If ( Kind and Kind <> objDir.GetDetailsOf(objItm,11) ) ; File isn't desired kind + { + Return + } + i:=0, nParams:=p.Count(), fex.SetCapacity(nParams + 11) - ; GuiButtonIcon - ;------------------------------------------------ - GuiButtonIcon(Handle, File, Index := 1, Options := "") - { - RegExMatch(Options, "i)w\K\d+", W), (W="") ? W := 16 : - RegExMatch(Options, "i)h\K\d+", H), (H="") ? H := 16 : - RegExMatch(Options, "i)s\K\d+", S), S ? W := H := S : - RegExMatch(Options, "i)l\K\d+", L), (L="") ? L := 0 : - RegExMatch(Options, "i)t\K\d+", T), (T="") ? T := 0 : - RegExMatch(Options, "i)r\K\d+", R), (R="") ? R := 0 : - RegExMatch(Options, "i)b\K\d+", B), (B="") ? B := 0 : - RegExMatch(Options, "i)a\K\d+", A), (A="") ? A := 4 : - Psz := A_PtrSize = "" ? 4 : A_PtrSize, DW := "UInt", Ptr := A_PtrSize = "" ? DW : "Ptr" - VarSetCapacity( button_il, 20 + Psz, 0 ) - NumPut( normal_il := DllCall( "ImageList_Create", DW, W, DW, H, DW, 0x21, DW, 1, DW, 1 ), button_il, 0, Ptr ) ; Width & Height - NumPut( L, button_il, 0 + Psz, DW ) ; Left Margin - NumPut( T, button_il, 4 + Psz, DW ) ; Top Margin - NumPut( R, button_il, 8 + Psz, DW ) ; Right Margin - NumPut( B, button_il, 12 + Psz, DW ) ; Bottom Margin - NumPut( A, button_il, 16 + Psz, DW ) ; Alignment - SendMessage, BCM_SETIMAGELIST := 5634, 0, &button_il,, AHK_ID %Handle% - return IL_Add( normal_il, File, Index ) - } + While ( i++ < nParams ) + { + Prop := p[i] - ; \GuiButtonIcon - ;------------------------------------------------ + If ( (Dot:=InStr(Prop,".")) and (Prop:=(Dot=1 ? "System":"") . Prop) ) + { + fex[Prop] := objItm.ExtendedProperty(Prop) + Continue + } + + If ( PropNum := xDetails[Prop] ) > -1 + { + fex[Prop] := ObjDir.GetDetailsOf(objItm,PropNum) + Continue + } + } + + fex.SetCapacity(-1) + Return fex + + } ;- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + ; GuiButtonIcon + ;------------------------------------------------ + GuiButtonIcon(Handle, File, Index := 1, Options := "") + { + RegExMatch(Options, "i)w\K\d+", W), (W="") ? W := 16 : + RegExMatch(Options, "i)h\K\d+", H), (H="") ? H := 16 : + RegExMatch(Options, "i)s\K\d+", S), S ? W := H := S : + RegExMatch(Options, "i)l\K\d+", L), (L="") ? L := 0 : + RegExMatch(Options, "i)t\K\d+", T), (T="") ? T := 0 : + RegExMatch(Options, "i)r\K\d+", R), (R="") ? R := 0 : + RegExMatch(Options, "i)b\K\d+", B), (B="") ? B := 0 : + RegExMatch(Options, "i)a\K\d+", A), (A="") ? A := 4 : + Psz := A_PtrSize = "" ? 4 : A_PtrSize, DW := "UInt", Ptr := A_PtrSize = "" ? DW : "Ptr" + VarSetCapacity( button_il, 20 + Psz, 0 ) + NumPut( normal_il := DllCall( "ImageList_Create", DW, W, DW, H, DW, 0x21, DW, 1, DW, 1 ), button_il, 0, Ptr ) ; Width & Height + NumPut( L, button_il, 0 + Psz, DW ) ; Left Margin + NumPut( T, button_il, 4 + Psz, DW ) ; Top Margin + NumPut( R, button_il, 8 + Psz, DW ) ; Right Margin + NumPut( B, button_il, 12 + Psz, DW ) ; Bottom Margin + NumPut( A, button_il, 16 + Psz, DW ) ; Alignment + SendMessage, BCM_SETIMAGELIST := 5634, 0, &button_il,, AHK_ID %Handle% + return IL_Add( normal_il, File, Index ) + } + ; \GuiButtonIcon + ;------------------------------------------------ - ToggleTestingMode(){ - IniRead, TestingMode, Settings.ini, General, TestingMode, 0 - ; Msgbox % "TestingMode: " TestingMode - if(TestingMode) - IniWrite, 0, Settings.ini, General, TestingMode - else, - IniWrite, 1, Settings.ini, General, TestingMode - } + ToggleTestingMode(){ - ToggleManualSubmit(){ + IniRead, TestingMode, Settings.ini, General, TestingMode, 0 + ; Msgbox % "TestingMode: " TestingMode + if(TestingMode) + IniWrite, 0, Settings.ini, General, TestingMode + else, + IniWrite, 1, Settings.ini, General, TestingMode + } - IniRead, ManualSubmit, Settings.ini, General, ManualSubmit, 0 - ; Msgbox % "TestingMode: " TestingMode - if(ManualSubmit) - IniWrite, 0, Settings.ini, General, ManualSubmit - else, - IniWrite, 1, Settings.ini, General, ManualSubmit - } + ToggleManualSubmit(){ + IniRead, ManualSubmit, Settings.ini, General, ManualSubmit, 0 + ; Msgbox % "TestingMode: " TestingMode + if(ManualSubmit) + IniWrite, 0, Settings.ini, General, ManualSubmit + else, + IniWrite, 1, Settings.ini, General, ManualSubmit + } - ToggleDevMode(){ - IniRead, DevMode, Settings.ini, General, DevMode, 0 - ; Msgbox % "TestingMode: " TestingMode - if(DevMode) - IniWrite, 0, Settings.ini, General, DevMode - else, - IniWrite, 1, Settings.ini, General, DevMode - } + ToggleDevMode(){ + + IniRead, DevMode, Settings.ini, General, DevMode, 0 + ; Msgbox % "TestingMode: " TestingMode + if(DevMode) + IniWrite, 0, Settings.ini, General, DevMode + else, + IniWrite, 1, Settings.ini, General, DevMode + } - FormatTextToJSText(Var){ ; Replaces AHK newline characters with javascript ones + FormatTextToJSText(Var){ ; Replaces AHK newline characters with javascript ones /*\b Backspace \f Form Feed \n New Line - done