Applescript: Finder got an error: AppleEvent handler failed - applescript

I have this script set up or rename my torrent folders, however it keeps giving me that weird finder error. It works when I don't read it from a text file, but I need that so that I don't need to select the folder all the time: Please help:
set read_folder to read (POSIX path of "/.torrentcleanup-prefs.txt") as text
set autofolder to (POSIX file read_folder)
set folderlist to ("")
tell application "Finder" to set folderlist to (get name of folders of folder autofolder)
repeat with i in folderlist
set dfilepath to (POSIX path of ((autofolder & i) as text))
set dfoldername to quoted form of POSIX path of dfilepath
set dfolder to i
set dmovie to quoted form of (text 1 thru ((length of dfolder) - 7) of dfolder as text)
try
do shell script "cd " & dfoldername & "; mv ./*.mkv ../" & dmovie & ".mkv"
end try
try
do shell script "cd " & dfoldername & "; mv ./*.mp4 ../" & dmovie & ".mp4"
end try
do shell script "rm -r " & dfoldername & ""
end repeat
By the Way, the contents of "/.torrentcleanup-prefs.txt" is:
/Users/student/Desktop/FIX ME NOW/Test Folder/

I didn't look at your whole script but you're reading the file wrong in the first line. You need to do it like this. So replace your first line with these two...
set myFile to "/.torrentcleanup-prefs.txt"
set read_folder to read (POSIX file myFile)

Related

AppleScript to append date to file

I was recently able to make a drag and drop script in Automator that allowed me to zip and name a file and then automatically apply the date (DDMMYY) but now it's defaulting to (DDMMYYYY) and I can't change it. I've googled for a solution and nothing works since this needs to be at the end of the file name.
Does anyone know what I'm doing wrong or does anyone have an actual script that can help me? Everything I've found only works if the date is at the start of the file name, not at the end (but before the extension).
You can use this AppleScript inside a Run AppleScript action, it renames the archive inserting the date before the file extension
on run {input, parameters}
set thePath to POSIX path of (item 1 of input)
set currentDate to do shell script "date +%d%m%y"
set newPath to text 1 thru -5 of thePath & "_" & currentDate & ".zip"
do shell script "mv " & quoted form of thePath & space & quoted form of newPath
return {POSIX file newPath as alias}
end run
Since you didn't provide any code I can't guess how you name your files, but the way to get DDMMYY is to use shell with the do shell script command:
tell application "Finder"
set theFile to (choose file)
set theName to name of theFile
set name of theFile to theName & "_" & (do shell script "date +%d%m%y") & ".xxx"
end tell
This doesn't get rid of the file extension of the original file. For that to work you would have to use something like this:
tell application "Finder"
set theFile to (choose file)
set theName to name of theFile
set periodIndex to offset of "." in theName
set theName to text 1 thru (periodIndex - 1) of theName
set name of theFile to theName & "_" & (do shell script "date +%d%m%y") & ".xxx"
end tell
The code responsible for removing the file extension comes from this post.
You can add punctuation how you like by putting the desired symbols before the next %. So date +%d.%m.%y is possible and improves readability.

AppleScript - Copying Folder Content shows error - Download & UnZip Works

UPDATE01: The cleaned Up code - Zip download was removed and current issue is that the 'Copy' command gets executed before 'unzip' is completed; resulting in a copy of an empty folder over to the destination folder. when running as an .app but when running as a script in AppleScriptEditor.. it runs fine :/
property DownloadsFolder : path to downloads folder
property appSupport : path to application support from user domain
property ZIPName : "ResourcesOffline.zip" -- downloaded ZIP file
property AppName : "MyApp" -- name of App in Application Support
property ExtractedFolderName : "MyContent" -- name for folder in Downloads where ZIP is saved
property ExtractedFolderPath : ((DownloadsFolder as text) & ExtractedFolderName & ":")
property DataFolder : ":UserBottle:FFApp:D_C:PData:LP:App:Data"
-- inform user of process --
display dialog "
IMPORTANT:
Before running this App, please be sure you have downloaded the 'ResourcesOffline.zip', and it is in your 'Downloads' Folder.
Press [OK] when you are ready to start.
" buttons {"Ok"}
-- Set up DSResources folders in Downloads and User's Bottle --
do shell script "mkdir -p " & quoted form of (POSIX path of ExtractedFolderPath) & space & quoted form of POSIX path of {(appSupport as text) & AppName & (DataFolder as text) & ":DSResources"}
display dialog "Check! Directories in Downloads and Data" buttons {"Ok"}
-- Extract to the folder created in Downloads --
try
do shell script "unzip -u " & quoted form of POSIX path of ((DownloadsFolder as text) & ZIPName) & " -d " & quoted form of POSIX path of ExtractedFolderPath
on error
display dialog "
Process failed.
Could not find 'ResourcesOffline.zip' in 'Downloads' folder.
Please be sure that the file exists in the specified location.
" buttons {"Quit"} with icon 0
if button returned of the result is "Quit" then error number -128
end try
display dialog "Check! UnZipped in MyContent" buttons {"Ok"}
-- Copy items to the folder created in Application Support --
tell application "Finder"
set SourceFolder to folder (ExtractedFolderPath as text)
set DestinationFolder to folder ((appSupport as text) & AppName & (DataFolder as text))
duplicate (entire contents of first folder of SourceFolder) to DestinationFolder with replacing
display dialog "
All content was copied successfully. Thank you!
" buttons {"Ok"}
end tell
display dialog "Check! All done - About to Delete TEMP Extracted files" buttons {"Ok"}
do shell script "rm -rf " & quoted form of POSIX path of ExtractedFolderPath
quit
==========================================================================
I am new to scripting, in general. Carry a basic understanding, but not much of a programmer.
I am trying to write an AppleScript script to do the following:
Download 'XXX.ZIP' from 'http://MyLink.com/XXX.zip'
Download in 'Downloads' folder and overwrite any existing file if it already exists
Show a progress bar of the download (<- I know a progress bar is tough, so this is a nice to have
Once downloaded, unpack the ZIP in same 'Downloads' location
Once Unzipped: I will have this (this is what is in the ZIP already):
One Main Folder [001]
One SubFolder in MainFolder [001A]
One File in MainFolder 001B.txt
Up till here all works fine; however from this point onwards I am struggling
Copy 'All Contents' of MainFolder (not the main folder itself; just the subfolder and text file in it) from 'Downloads' folder to 'Library/Application Support/MyApp/Resources' and Replace any existing files
Once copied, display popup dialogue that 'process is completed' - [OK]
Notes:
I am using ~/Folder locations because this script is for anyone to use, so I can't hard code the full path i.e: MacHD/Users/USERNAME/Downloads .. etc
PS - I am new to coding; so a lot of things in this code may seem 'senseless'; but I am trying so please bare with me. I have gone through a lot of forums to derive what I have but Gods of coding aren't happy with me… I am having issues trying to make all this work; this is the script I have till now:
set newFolderPath to quoted form of (expandPath("~/Downloads/MYCONTENT"))
set cmdStr to "if [[ ! -d " & newFolderPath & " ]]; then
mkdir -m 755 " & newFolderPath & "; fi"
do shell script cmdStr
on expandPath(pPathStr)
local fullPath
set fullPath to pPathStr
if fullPath = "~" then
set fullPath to (POSIX path of (path to home folder))
else if fullPath starts with "~/" then
set fullPath to (POSIX path of (path to home folder)) & text 3 thru -1 of fullPath
end if
return fullPath
end expandPath
-- Download --
tell application "Finder"
do shell script "curl -L -o ~/Downloads/MYCONTENT/SOME_RESOURCES.ZIP 'https://MyWebsite.com/Stuff/DownloadableContent/SOME_RESOURCES.ZIP' > ~/Downloads/MYCONTENT/status 2>&1 &"
set fileSize to 0
set curTransferred to 0
set curProgress to 0
repeat until curProgress = "100"
try
set lastLine to paragraph -1 of (do shell script "cat ~/Downloads/MYCONTENT/status")
set curProgress to word 1 of lastLine
set fileSize to word 2 of lastLine
set curTransferred to word 4 of lastLine
tell me
display dialog "Downloading; Please wait, this will take a while.
Status: " & curTransferred & " of " & fileSize & " (" & curProgress & "%)" buttons {"Refresh", "cancel"} giving up after 5
if the button returned of the result is "cancel" then return
end tell
on error
display dialog "Download failed. To restart the download, please press the 'Retry' button" buttons {"Quit", "Retry"} with icon 0
end try
end repeat
set theDialogText to "Download is complete. Press [OK] to continue"
display dialog theDialogText
-- Extract --
do shell script "unzip -u ~/Downloads/MYCONTENT/SOME_RESOURCES.ZIP -d ~/Downloads/MYCONTENT/"
do shell script "/bin/sleep 10"
-- ** FROM HERE ONWARDS I AM GETTING AN ERROR **
-- Copy --
set DownloadFolder to "~/Downloads/MYCONTENT/RESOURCES/"
set DestinationFolder to "~/Library/Application Support/MYAPPLICATION/RESOURCES/"
copy every file of folder (DownloadFolder's entire contents) to folder DestinationFolder
set theDialogText to "All content has been copied. Thank you!"
display dialog theDialogText
end tell
Your outline and script example are a bit different, so I went with the outline:
Create folders in the user's Downloads and Application Support folders as needed
Download a zip file to the folder created in Downloads and extract it to that folder - the zip file contains a main folder containing a sub folder (or folders) containing files
Copy the entire contents of the main folder to the Resources folder in the folder created in Application Support for the application
There are a few ways to do a progress bar or download status using some AppleScriptObjC, but for better control those should probably be done from an application.
The main problems with your script are that the Finder does not understand POSIX paths, and you missed creating the folder structure in Application Support. There are standard commands to get paths to the various system folders, so string manipulations aren't needed to get the script to work on other machines. In the following script, I keep track of the regular HFS paths, just coercing them to POSIX for the shell scripts, and added properties for the various names so they are in one spot.
property downLoads : path to downloads folder
property appSupport : path to application support from user domain
property webPage : "HTTPS://MYWEBSITE.COM/STUFF/DOWNLOADABLECONTENT/"
property webResource : "SOME_RESOURCES.ZIP" -- name for the downloaded file
property myApp : "MYAPPLICATION" -- name for folder in Application Support (bundle identifier would be better)
property baseName : "MYCONTENT" -- name for folder in Downloads
property basePath : ((downLoads as text) & baseName & ":")
-- Set up folders in Downloads and Application Support as needed --
do shell script "mkdir -p " & quoted form of (POSIX path of basePath) & space & quoted form of POSIX path of ((appSupport as text) & myApp & ":Resources")
-- Download and progress - more error handling is needed --
do shell script "curl -L " & quoted form of (webPage & webResource) & " -o " & quoted form of POSIX path of (basePath & webResource) & " > " & quoted form of POSIX path of (basePath & "status") & " 2>&1 &"
set fileSize to 0
set curTransferred to 0
set curProgress to 0
repeat until curProgress = "100"
try
set lastLine to paragraph -1 of (do shell script "cat " & quoted form of POSIX path of (basePath & "status"))
set curProgress to word 1 of lastLine
set fileSize to word 2 of lastLine
set curTransferred to word 4 of lastLine
tell me
display dialog "Downloading; Please wait, this will take a while.
Status: " & curTransferred & " of " & fileSize & " (" & curProgress & "%)" buttons {"Refresh", "Cancel"} giving up after 1
if the button returned of the result is "Cancel" then return
end tell
on error
display dialog "Download failed. To restart the download, please press the 'Retry' button" buttons {"Quit", "Retry"} with icon 0
if button returned of the result is "Quit" then error number -128
end try
end repeat
display dialog "Download is complete. Press [OK] to continue"
-- Extract to the folder created in Downloads --
do shell script "unzip -u " & quoted form of POSIX path of (basePath & webResource) & " -d " & quoted form of POSIX path of basePath -- Main Folder > Sub Folder > text file
-- Copy items to the folder created in Application Support --
tell application "Finder"
set downLoadFolder to folder basePath
set DestinationFolder to folder ((appSupport as text) & myApp & ":Resources")
duplicate (entire contents of first folder of downLoadFolder) to DestinationFolder with replacing -- contents of "Main Folder" -- 'duplicate' is the command to use for files
display dialog "All content has been copied. Thank you!"
end tell
Change the placeholder items in the properties as needed - Note that the shell scripts and web file names are case sensitive.

Using backslashes in text replacement in AppleScript

I'm currently trying to create an AppleScript Application which will copy a folder from its "Contents" folder to the user's desktop. The code I have at the moment is:
set theFile to path to me as string
set hfsme to theFile & "Contents:Folder"
set posixPath to POSIX path of hfsme
set contentfolder to posixPath
set AppleScript's text item delimiters to " "
set textItem to text items of contentfolder
set AppleScript's text item delimiters to "\\ "
set contentfolder to textItem as string
set AppleScript's text item delimiters to {""}
do shell script "cp -a " & contentfolder & " $HOME/Desktop"
However, I receive the following error upon run:
"cp: /Users/myusername/Desktop/Test Application.app/Contents/Folder: No such file or directory"
I think this is because I expect the copy location to be:
/Users/myusername/Desktop/Test\ Application.app/Contents/Folder
But the script fails to add the backslash before the space which is what the shell command requires.
My question is: how do I replace the spaces in the variable with "\ " ?
P.S. Before suggesting simply renaming the application a name which doesn't have a space, it is very important for me to have an application name with a space.
I have also tried using "duplicate" command with AppleScript but wasn't able to get this to work but I am open to suggestions!
(Please bear in mind that I'd like this script to work on other people's computers as well meaning that I cannot assume I already know the user's username.
Thank you in advance for any help!
Kind regards, Tom
Just add quoted form of, it handles the quotation in a very smart (and reliable) way.
set theFile to POSIX path of (path to me)
set contentfolder to theFile & "Contents/Folder"
do shell script "cp -a " & quoted form of contentfolder & " $HOME/Desktop"
If do shell script does not support $HOME write
do shell script "cp -a " & quoted form of contentfolder & space & quoted from of POSIX path of (path to desktop)

using Paragraphs in Xcode in AppleScriptObjC

do shell script "mdfind kMDItemCFBundleIdentifier = com.test.sample > ~/Documents/sampleBuilds.txt"
set homeFolder to (path to home folder)
set sampleFiles to paragraphs of (read POSIX file (POSIX path of homeFolder & "/Documents/sampleBuilds.txt"))
if (count of sampleFiles) is 0 then
display notification "No Sample builds are present on the system"
else
set sampleFiles to paragraphs of (read POSIX file (POSIX path of homeFolder & "/Documents/sampleBuilds.txt"))
display dialog "You have " & (count of sampleFiles) & " build(s) of Sample on your system. Would you like to remove them all? This cannot be undone"
repeat with c in SampleFiles
do shell script "rm -rf " & (quoted form of c)
display notification "Sample build located at " & c & " has been removed from your system"
end repeat
do shell script "rm -rf ~/Documents/SampleBuilds.txt"
end if
When placing script into Xcode with correct sender I get the error:
[AppDelegate testScript:]: Can’t make current application into type file. (error -1700) on the line
set sampleFiles to paragraphs of (read POSIX file (POSIX path of homeFolder & "/Documents/sampleBuilds.txt"))
Any thoughts on how to get Xcode in AppleScript Application to accept this script?
The coercion to POSIX file is not needed which solves the issue.
set sampleFiles to paragraphs of (read (POSIX path of homeFolder & "/Documents/sampleBuilds.txt"))
Basically in AppleScriptObjC POSIX file foo doesn't work, you have to write foo as POSIX file.
Side note:
Reading the text twice is redundant. You can delete the second set sampleFiles to ... line.

Applescript System Events Returns .DS_Store - How can I ignore

I have looked around on the net for hours looking for this answer so I apologize if its there somewhere. This script below works fine except for the fact that it returns the .DS_Store file how can I exclude it from this query and all other hidden files for that matter but because I am creating the folder in my script the only one there is .DS_Store
tell application "System Events"
set listOfInputs to POSIX path of every disk item of folder a as list
end tell
Here is the full script below. I have been dropping files into the in folder after it is created but will eventually prompt for files before it is created.
on run
tell application "Finder"
if not (exists folder "IN") then
make new folder at desktop with properties {name:"IN"}
end if
if not (exists folder "OUT") then
make new folder at desktop with properties {name:"OUT"}
end if
end tell
set theINfolder to path to the desktop as string
set a to theINfolder & "IN:"
tell application "System Events"
set listOfInputs to POSIX path of every disk item of folder a as list
end tell
set inputs to listOfInputs
set theOutfolder to path to the desktop as string
set outputFolder to theOutfolder & "OUT:"
set params to {}
main(inputs, outputFolder, params)
end run
The following will work:
set listOfInputs to list folder a without invisibles
But without invisibles cannot be combined with POSIX path, so we use a loop instead:
set listOfInputs to {}
tell application "System Events"
set the_items to list folder a without invisibles
repeat with i from 1 to the count of the_items
set this_item to alias ((a as Unicode text) & (item i of the_items))
set end of listOfInputs to POSIX path of this_item
end repeat
end tell
The List Folder command has been deprecated and may stop working unexpectedly.
Try:
set inFolder to (path to desktop as text) & "IN"
do shell script "mkdir -p " & quoted form of (POSIX path of inFolder)
set listOfInputs to paragraphs 2 thru -1 of (do shell script ("find " & quoted form of (POSIX path of inFolder) & " \\! -name \".*\""))
You can get the result as a string separated by spaces like this:
set inFolder to (path to desktop as text) & "IN"
do shell script "mkdir -p " & quoted form of (POSIX path of inFolder)
set {TID, text item delimiters} to {text item delimiters, " "}
set listOfInputs to paragraphs 2 thru -1 of (do shell script ("find " & quoted form of (POSIX path of inFolder) & " \\! -name \".*\"")) as text
set text item delimiters to TID

Resources