Rest of AppleScript is ignored when I use a variable in posix path - variables

I'm using AppleScript in Automator to copy a page's source and save it to a file. For some reason when I use a variable (titleVal) in the posix path, the rest of my code in my loop is ignored, including the file that never gets written.
I updated the code before with my full AppleScript in case it has to do with more than the few lines I had before. I'm using Automator with specified Finder items in this order: "urlList.txt" and fileList.txt".
on run {input, parameters}
set updateCount to 0
read (item 1 of input)
set ps to paragraphs of the result
set tot to count ps
set TLFile to (("Users:Admin:Desktop:download captions:") as text) & "fileList.txt"
set TLLines to paragraphs of (read file TLFile as «class utf8»)
tell application "Safari"
reopen
activate
end tell
repeat with i from 1 to tot
set p to item i of ps
if p is not "" then
try
tell application "Safari"
tell front window
set r to make new tab with properties {URL:"https://www.youtube.com/timedtext_editor?v=" & p & "&lang=en&name=&kind=&contributor_id=0&bl=vmp&action_view_track=1"}
set current tab to r
set titleVal to item i of TLLines
set updateCount to updateCount + 1
do shell script "echo The value: " & updateCount
delay 2
do JavaScript "document.getElementById('movie_player').outerHTML = ''" in current tab
do JavaScript "document.getElementById('creator-page-sidebar').outerHTML = ''" in current tab
do JavaScript "document.getElementById('footer').outerHTML = ''" in current tab
delay 3
do JavaScript "document.getElementsByClassName('yt-uix-button yt-uix-button-size-default yt-uix-button-default action-track-button flip yt-uix-menu-trigger')[0].click()" in current tab
delay 1
do JavaScript "document.getElementById('aria-menu-id-2').getElementsByTagName('ul')[0].getElementsByTagName('li')[5].getElementsByTagName('a')[0].click()" in current tab
delay 4
-- using a variable in path1 is where it screws up. try changing it to another variable value and it will have the same effect.
set myString to source of current tab
set path1 to "/Users/Admin/Desktop/download captions/downloadedCaptions/" & titleVal & ".srt"
say path1
set newFile to POSIX file path1
--set newFile to POSIX file "/Users/Admin/Desktop/download captions/downloadedCaptions/test.xml.srt"
open for access newFile with write permission
write myString to newFile
close access newFile
-- i have exit repeat here to only test the first loop
exit repeat
end tell
end tell
end try
end if
end repeat
end run
Without a variable works fine, but I need the variable to make the script work properly in a loop. I've checked the value of the var. I also tried "& quoted form of titleVal &".
Update: When I remove the try/end try as suggested to get the error, the error is:
The action “Run AppleScript” encountered an error: “Safari got an error: Can’t get POSIX file "/Users/Admin/Desktop/download captions/downloadedCaptions/test.srt" of window 1.”

The error occurs because you are going to write the file in the tell window block of Safari which cannot work.
I recommend to use a separate handler. Put the on writeFile handler outside of the on run handler. I added reliable error handling and the data are saved UTF-8 encoded.
on writeFile(theData, fileName)
set newFile to "/Users/Admin/Desktop/download captions/downloadedCaptions/" & fileName & ".srt"
try
set fileDescriptor to open for access newFile with write permission
write theData to fileDescriptor as «class utf8»
close access fileDescriptor
on error
try
close access newFile
end try
end try
end writeFile
and call it (replace the part of your code from delay 4 to the end)
delay 4
-- using a variable in path1 is where it screws up. try changing it to another variable value and it will have the same effect.
set myString to source of current tab
my writeFile(myString, titleVal)
exit repeat
end tell
end tell
end try
end if
end repeat
end run

This was fixed very easily by changing one line:
set newFile to POSIX file path1
to:
set newFile to (path1 as POSIX file)
But I don't know why. Seems like a bug since it worked without the variable. Please provide any details in the comments why this works over the original set newFile line.

Related

Trying to print new folder names to a text edit/numbers file when logged (AppleScript)

I'm trying to add new folders added to a drive onto a textEdit or numbers file so that there's an up to date list of what projects I have active on individual drives.
I'm very new to AppleScript so I don't know what my limitations are, but I basically just need to figure out how to append to the end of the file (it seems like textEdit would be simplest) with the name of the new folder. I currently have:
on adding folder items to theAttachedFolder after receiving theNewItems
-- Get the name of the attached folder
tell application "Finder"
set theName to name of theAttachedFolder
-- Count the new items
set theCount to length of theNewItems
-- Display an alert indicating that the new items were received
activate
display alert "Attention!" message (theCount & " new items were detected in folder. Adding to TextEdit file.")
end repeat
end tell
Any help is much appreciated. Thank you!
The File Read/Write suite in the StandardAdditions scripting dictionary has open for access and write commands that can be used to append to a text file (the AppleScript Language Guide also has a command reference), and AppleScript's text item delimiters or string concatenation can be used to assemble a string from the list of file items.
There are some older topics describing ways to write to a file, but in the following example I've separated the main stuff from the folder action handler so that it can also be called from the run handler for testing in the Script Editor:
property logFile : "/path/to/output/textfile.txt" -- HFS or POSIX
on run -- test
set folderItems to (choose file with multiple selections allowed)
tell application "Finder" to set theFolder to container of first item of folderItems
doStuff(theFolder, folderItems)
end run
on adding folder items to theAttachedFolder after receiving theNewItems
doStuff(theAttachedFolder, theNewItems)
end adding folder items to
to doStuff(theFolder, theItems)
set folderItems to ""
activate
display alert "Attention!" message "" & (count theItems) & " new items were detected in folder." & return & "Adding to log file."
tell application "Finder" to set folderName to name of theFolder
repeat with anItem in theItems
tell application "Finder" to set newName to name of anItem
set folderItems to folderItems & tab & newName & return
end repeat
writeToFile(logFile, "Items added to " & folderName & ":" & return & folderItems & return)
end doStuff
to writeToFile(someFile, someText)
try
set theOpenFile to (open for access someFile with write permission)
write someText to theOpenFile starting at eof -- append
close access theOpenFile
on error -- make sure file is closed
try
close access theOpenFile
end try
end try
end writeToFile

Setup Factory 9 - Check File for String

Im am 100% new to Lua and need a way to check my etc/hosts file for a string. The other posts I found were dealing with searching in strings and and reading files line by line.
Here is some of my script which is a combination of some of the examples I found on here:
file = io.open("C:\Windows\System32\drivers\etc\hosts", "a")
function check(file)
if file.match(str, "nbs") then
file:close()
Screen.Next();
else
file:write("\n", %UserIP%, " nbs document")
file:close()
Screen.Next();
end
end;
As you can see Im searching the file hosts for the sting nbs. If it exists I want to move on. If it does not, I plan to append the file with a new line.
The above seems to do nothing when I enter it into my Lua Shell.
EDIT 1: adding full script; this is the full original script + my additions
-- These actions are performed when the Next button is clicked.
-- from _SUF70_Global_Functions.lua:
-- is the "Name:" field empty?
if(g_EditFieldIsEmpty(CTRL_EDIT_01)) then
-- the name field is empty...tell the user that it's a required field
-- and remain on this screen (don't advance to the next one)
-- "Invalid Entry"
local strTitle = SetupData.GetLocalizedString("MSG_INVALID_ENTRY");
-- get the label for the "Name:" edit field (since it may have been translated)
local strFieldName = DlgStaticText.GetProperties(CTRL_STATICTEXT_LABEL_01).Text;
-- strip off the trailing ":" (if present)
strFieldName = String.TrimRight(strFieldName, ":");
-- "The <fieldname> field cannot be empty."
local strPrompt = SetupData.GetLocalizedString("MSG_THE")
..strFieldName
..SetupData.GetLocalizedString("MSG_FIELD_CANNOT_BE_EMPTY");
Dialog.Message(strTitle, strPrompt, MB_OK, MB_ICONEXCLAMATION, MB_DEFBUTTON1);
else
--andrew you added the lines below
file = io.open("C:\Windows\System32\drivers\etc\hosts", "a")
function check(file)
if file.match(str, "test") then
file:close()
Screen.Next()
else
file:write("\n", "test")
file:close()
Screen.Next();
end
end;
-- the "Name:" field isn't empty...so
-- advance to the next screen
-- Screen.Next();
end;
This ended up being the solution I was looking for:
ip = SessionVar.Expand("%UserIP%")
result = TextFile.ReadToString(SessionVar.Expand("%SystemFolder%\\drivers\\etc\\hosts"));
if string.match(result, "nbs") then
Screen.Next()
else
file = io.open("C:\\Windows\\System32\\drivers\\etc\\hosts", "a")
file:write("\n", ip, " nbs document")
file:close()
Screen.Next()
end
In this case I was using the applications built in functions. These seem to make use of C as well so they would not work in a Lua shell.
Your code creates a file handle and defines a function check().
If it is supposed to do more you have to have to add more content. Like a function call to check.
Once you call check you'll most likely face a script error because you call a function file.match which does not exist in native Lua.
file = io.open("C:\Windows\System32\drivers\etc\hosts", "a")
-- this loop will give you each line of the file as a string and you can use string.match
for line in file:lines() do
if line:match("nbs") then
print("I found one!!")
end
end
I'm sure you can take it from here. Please refer to https://www.lua.org/manual/5.3/manual.html#6.8

Deleting a file immediately after closing it - 'Permission Denied' error

I want to save an email as a Word file through a macro, and then replace this with a converted PDF file via Word. The conversion part is working fine - the issue is when I try to delete the original .doc file.
Dim objWrd As Object
Dim objWrdDoc As Object
Dim wrdCurrentPrinter As String
Set objWrd = CreateObject("Word.Application")
Set objWrdDoc = objWrd.Documents.Open(filePath & fileName)
''Print' file as PDF - current printer is stored so it can be reverted back afterwards
wrdCurrentPrinter = objWrd.ActivePrinter
objWrd.ActivePrinter = "Microsoft Print To PDF"
'File name is specified here to avoid Save As prompt. PrintToFile property is 'True'
objWrd.PrintOut , , , filePath & Replace(fileName, ".doc", ".pdf"), , , , , , , True
objWrd.ActivePrinter = wrdCurrentPrinter
objWrd.Quit
Set objWrd = Nothing
Kill filePath & fileName
At Kill filePath & fileName I get error 70 - Permission denied.
I am able to delete the file manually without any problems, and if I add a breakpoint and step through the 'Kill' line, it works when there is even a slight delay between Word closing and the Kill command. Therefore I suspect that the code is being processed so quickly so that the file is still open at the time of running the command.
I have a feeling I may need to go down the route of creating a delay, which I have been having trouble with in Outlook. Is this the likely solution or is there something else that I have missed?
I have been able to get this to work consistently by simply closing the Word document before quitting Word altogether:
objWrdDoc.Close
objWrd.Quit
Set objWrd = Nothing
The error has not appeared since adding this line and testing with various emails.

Not able to save to a created folder (applescript)

so I have been trying to create a script that will create a folder on my desktop, then create a spreadsheet, and save the spreadsheet to said folder. here is the script...
set folderName to "Tester"
set FileName to "MayDay"
set SaveName to FileName & ".numbers" as string
set FilePath to "Macintosh HD:Users:Ryan:Desktop:" & FileName & ":"
tell application "Finder" to make new folder at desktop with properties {name:folderName}
tell application "Numbers" to activate
tell application "Numbers" to make new document with properties {name:FileName}
tell application "Numbers"
tell document 1
tell table 1 of sheet 1
merge range "B8:C8"
end tell
end tell
delay 1
tell application "Numbers" to activate
end tell
tell application "Numbers" to (save document 1) in FilePath
end
It has no problem making the folder, opening the spreadsheet, changing its name, and merging the cells, the problem comes in at the end when I try to save it.
I have tried adding (as numbers) no parenthesis after the save command, that errors out. After I run the script, and clear the crash, I can close out numbers and it will prompt me to save it in the "Tester" folder, but it won't do it on its own. insert grey hairs and headaches here.
I am really new to applescript, and I am hoping this is just a simple syntax thing, any help would be appreciated.
Thanks in advance!
R
Here's working code. A key is to use POSIX path and POSIX file and also the "save ... in ..." takes a file reference, not a string.
set folderName to "Tester"
set fileName to "MayDay.numbers"
set FilePath to (path to desktop as string) & folderName & ":" & fileName
set posixPath to POSIX path of FilePath
try
tell application "Finder" to make new folder at desktop with properties {name:folderName}
on error errMsg
end try
tell application "Numbers"
set myDoc to make new document with properties {name:fileName}
tell myDoc
tell table 1 of sheet 1
merge range "B8:C8"
end tell
end tell
delay 1
save myDoc in POSIX file posixPath
end tell

Embed Applescript in Global Field to (Export Container and Trigger Printing with Acrobat)

I am trying to tie together a filemaker script that will export PDFs to a temporary space and use and apple script to print them.
I was able to cull together info from this and some other boards to create an applescript that will print the PDFs using Acrobat from a folder.
I have already created a script that finds the Related attachments and exports them to the desktop.
What I'm having trouble with is merging the two.
I need to export the PDF to a folder or temporary place and trigger the apple script to initiate the printing...
This great Suggestion was provided by Chuck of chivalrysoftware.com/…...
Calculate the location to export by appending the filename to Get( TemporaryPath ).
Export the container field contents to FileMaker to that path.
Save the path to a global field in FileMaker
Use an embedded AppleScript to access the global field path
Use AppleScript to open the file in Preview and print it
This is my apple script:
set myFolder to (path to desktop folder as text) & "Print:"
set myfiles to list folder myFolder without invisibles
repeat with myfile in myfiles
set mycurrentfile to ((myFolder as string) & (myfile as string)) as string
batchprint(mycurrentfile)
end repeat
on batchprint(mycurrentfile)
tell application "Adobe Acrobat Pro"
activate -- bring up acrobat
open alias mycurrentfile -- acrobat opens that new file
tell application "System Events"
tell process "Acrobat"
click menu item "Print..." of menu 1 of menu bar item "File"¬
of menu bar 1
click button "Print" of window "Print"
tell application "System Events"
tell process "Acrobat"
click menu item "Close" of menu 1 of menu bar item "File"¬
of menu bar 1
end tell
end tell
end tell
end tell
end tell
tell application "Finder" -- to move the printed file out
set x to ((path to desktop folder as text) & "Printed PDFs:")
if alias x exists then
beep
else
make new folder at the desktop with properties {name:"Printed PDFs"}
end if
move alias mycurrentfile to folder "Printed PDFs"
end tell
end batchprint
My Filemaker script is:
Go to Related Record[
Show only related records; From table: 'Attachments";
Using layout: "Attachements Report' (Attachments); New window
]
Enter Find Mode
Constrain Found Set [Restore]
Sort Records [Restore; No dialog]
# After finding the related attachments and constraining them to the specific type
# we rename and export them to the desktop
Go to Record/Request/Page [First]
Loop
Set Variable [$Path; Value:
Get ( DesktopPath ) & Attachments::Record number & "-"
& Attachment Type List 2::Prefix_z & Lien::Lien_ID_z1]
Export Field Contents [Attachments::file_c; $Path]
Go to Record/Request/Page [Next: Exit after last]
End Loop
Close Window [Current Window]
First of all, the FileMaker part. Create a global text field in one of your tables. It looks like the Attachments table would be the best place for it. I'll call it g_applescript_parameter for this.
Now we're going to use your $Path variable, which given the calc you've provided should be something like /Aslan/Users/chuck/Desktop/1234-ABC4321. I'd recommend appending a .pdf to the end of it since you'll be exporting PDF files. This may help later.
Also, I would recommend that you use Get( TemporaryPath ) instead of Get( DesktopPath ). Anything you place in the temporary folder will be automatically deleted when you quit FileMaker, which means you don't have to write anything to clean up the desktop folder later and you don't have to manually trash them either. Let FileMaker do that work for you. :)
Regardless, FileMaker uses a path of the form filemac:/volumeName/directoryName/fileName (see the notes in the Specify output file dialog box for the Export Field Contents script step). So you should also prepend filemac: to the beginning of your path variable.
All told, your $Path should be set to something like this:
"filemac:" & Get( DesktopPath ) & Attachments::Record number & "-" &
Attachment Type List 2::Prefix_z & Lien::Lien_ID_z1 & ".pdf"
So your export path for FileMaker should work better now. But AppleScript requires a different format for the path to the same file. Given the above, AppleScript's version should be something like /Users/chuck/Desktop/1234-ABC4321.pdf. In other words, everything after the drive name. Fortunately FileMaker can get the drive name with the Get( SystemDrive ) function. For me that function returns /Aslan/. So if we take the $Path variable as defined above and remove filemac: and the name of the drive as defined by Get( SystemDrive ) and add an extra slash at the beginning, that would convert our FileMaker path into an AppleScript path:
"/" & Substitute( $Path; "filemac:" & Get( SystemDrive ); "" )
Use Set Variable to create an $ASPath variable and set it to the above.
Now within your loop store the contents of the $ASPath variable within that global text field:
Loop
Set Variable[ $Path; …]
Set Variable[ $ASPath; …]
Set Field[Attachments::g_applescript_parameter; $ASPath)
Export Field Contents[Attachments::file_c; $Path]
Go to Record/Request/Page[Next; Exit after last]
End Loop
Now AppleScript can extract that information. I'm assuming that given an accurate file being passed to the batchprint function, batchprint will work, so keep that, but remove everything before it and use something like this:
set _pdf_path to contents of cell "g_applescript_parameter" of current layout
batchprint(_pdf_path)
on batchprint(mycurrentfile)
...
end batchprint
Add a Perform AppleScript step after the Export Field Contents step and place the above code in it.
Note that the first line of the above AppleScript will only work as written from within FileMaker. If you're testing this outside of FileMaker in, for example, Script Editor, then you'll need to make that first line read
tell applicaiton "FileMaker" to set _pdf_path ...
You don't need to do this within the Perform AppleScript script step because by default commands are sent to the enclosing FileMaker application.