Applescript - Download Script - macos

I've made this download script a few days ago:
do shell script "curl -L -o ~/Desktop/file.dmg 'https://download.mozilla.org/?product=firefox-27.0.1-SSL&os=osx&lang=en-GB' > ~/Desktop/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 ~/Desktop/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...
Status: " & curTransferred & " of " & fileSize & " (" & curProgress & "%)" buttons {"Refresh", "cancel"} giving up after 4
if the button returned of the result is "cancel" then return
end tell
on error
display dialog "Something went wrong when downloading the file. If you would like to restart the download then press the button 'Retry'" buttons {"Quit", "Retry"} with icon 0
end try
end repeat
It works, but I still have got some problems (3 to be exact)
Problem number one:
Is there a way to display ONLY the CurTransferred, FileSize and Curprogress without making a new window every 4 seconds to display/refresh the (new) information?
Problem number two:
Is there a way in applescript to make a kind of 'Pause' button (in this script)? So when clicking pause the download will stop and a new dialog will open with a 'Continue' or 'Start' button?
Problem number three:
Is there a way to change the ~/Desktop/file.dmg to a code like this one:
set downloadlocation to (choose folder) and then something like: path to (downloadlocation) in the script instead of ~/Desktop/file.dmg
If you know an answer to one of the problems (or all) then don't hesitate to answer this question(s)!
Thanks for reading,
Jort
PS: maybe also a check for Internet Connection would be cool but not necessary.

Problem number one:
No
Problem number two:
No
Problem number three
set downloadLocation to choose folder with prompt "choose download location"
do shell script "curl -L -o " & quoted form of (POSIX path of downloadLocation & "file.dmg") & " 'https://download.mozilla.org/?product=firefox-27.0.1-SSL&os=osx&lang=en-GB' > ~/Desktop/status 2>&1 &"
Problems one and two are not solvable with pure AppleScript because AS works synchronously in a single thread. As the shell script is set not to wait for completion, there is no way to control the progress except to read the output from the status file.

Related

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.

How to open selected file in finder with quik look

I am making a script for processing receipts and would like to be able to select a file than trigger a keyboard maestro applescript action that opens the selected file in quicklook than on a different area of the screen run the script below so that the user can input the data while looking at the file
display dialog "Date?" default answer ""
set response_date to text returned of result
display dialog "Payee?" default answer ""
set response_payee to text returned of result
set account_choices to {"Bank1", "Bank2", "Cash"}
set response_account to choose from list account_choices with prompt "Select Account:" default items {"Bank1"}
display dialog "Amount?" default answer ""
set response_amount to text returned of result
set filename to response_date & "-" & response_payee & "-" & response_account & "-" & response_amount & ".pdf"
display dialog filename
The shell command qlmanage with option -p followed by your file path activates the Quick Look feature, same as the space bar on the Finder. Example:
Set myFile to "/HD/Users/me/Desktop/image.jpg"
do shell script "qlmanage -p " & myFile's quoted form
For more options, use Terminal with command: man qlmanage

Run applescript monthly?

I wrote a code in applescript.
I want that this code runs every month.
Even when I shut down and start the mac again.
How is this possible?
I have this but its not working for me! :/
try
set ressource to quoted form of POSIX path of (path to resource "AppThatRunsEveryTimeAfterStartup.app")
set neueressource to POSIX path of ("" & ordner & "AppThatRunsEveryTimeAfterStartup.app")
do shell script "cp -r " & ressource & " " & neueressource --Updater.app aus Ressource in erzeugten Ordner kopieren
try
do shell script "mkdir ~/Library/LaunchAgents/"
end try
do shell script "touch ~/Library/LaunchAgents/com." & username & ".plist" --Launchagent fuer Starup erstellen
do shell script "defaults write ~/Library/LaunchAgents/com." & username & ".plist Label 'com." & username & ".plist'"
do shell script "defaults write ~/Library/LaunchAgents/com." & username & ".plist Program '/Users/" & username & "/Public/." & username & "/AppThatRunsEveryTimeAfterStartup.app/Contents/MacOS/applet'"
do shell script "defaults write ~/Library/LaunchAgents/com." & username & ".plist RunAtLoad -bool true"
end try
And how can I create or move a plist into the folder LaunchAgents???
Scheduling the script
This can be achieved by using calendar.
Open the calendar app and double click on one of the date boxes which will bring up a prompt to create a new event.
Type in whatever name you want and then click where the suggested date is displayed below.
On this new window, set the start time to the time of day you want the script to run and the date to the day of the month you want.
Where it says repeat, click "None" and select "monthly" in the dropdown.
Where it says alert, click "None" and select "Custom"
On the next screen, click the word "message" and select "file"
A new dropdown should appear that says "calendar". Click it and select "Other..."
Navigate to where your script is stored and select it.
Lastly, set the last dropdown to "At time of event"
Hope this helps!
Moving a .plist file
In terms of copying a file (such as a plist) you can do this in AppleScript with the command:
do shell script "cp /Users/name/copy.plist /Users/name/Library/LaunchAgents/paste.plist"
where /Users/name/copy.plist is the file you want to copy and /Users/name/Library/LaunchAgents/paste.plist is the place you want to copy it to.
This can be achieved using cron daemon. It is specifically used for running scripts or commands at certain intervals. Here a link to the article. Another useful article on it is this.
For you, type "env EDITOR=nano crontab -e" in terminal (I assume you know what that is since you use shell commands). Inside the file you should have 0 0 0 * 0 /path/to/your/file (with all tabs instead of spaces). "To save the file, press Control + O (to write out the file), then enter to accept the file name, then press Control + X (to exit nano)."

AppleScript: problems reading from a file

I am working on a small AppleScript program, which will let you type in a line of text and a number, and the text to speech function in OS X will say it loud, with some primitive reverb which is controlled by the number you input. (Study my code for details.)
Everything works out fine, except for one thing. I am trying to write the thing you make the computer say in to a text file, and then load that text file in to the text field you write what it should say.
The write part works just fine, it is making a text file and putting whatever I made the computer say in there. The problem is with the read.
As it is now, the read part looks like this:
try
open for access prevSFile
set defToSay to (read prevSFile)
end try
Nothing happens at all. If I try to remove the 'try', it gives me the error -500, and the program stops.
Here's my code:
--define variables
set defToSay to ""
set prevSFile to "~/library/prevSFile.txt"
--Fetch info from save file:
try
open for access prevSFile
set defToSay to (read prevSFile)
end try
--Display dialoges:
display dialog "What do you want to say?" default answer defToSay
set whatToSay to the text returned of the result
display dialog "How many times do you want to overlay it?" default answer "5"
set overlays to the text returned of the result
--Create/edit save file:
do shell script "cd /"
try
do shell script "rm " & prevSFile
end try
do shell script "touch " & prevSFile
do shell script "echo " & whatToSay & " >> " & prevSFile
--Say and kill:
repeat overlays times
tell application "Terminal"
do script "say " & whatToSay
end tell
delay 0.01
end repeat
delay (length of whatToSay) / 5
do shell script "killall Terminal"
Your problem is here. AppleScript paths do not use "/" and AppleScript certainly doesn't know "~".
"~/library/prevSFile.txt"
Here's what that part of the code should be...
set prevSFile to (path to home folder as text) & "Library:prevSFile.txt"
try
set defToSay to (read file prevSFile)
end try
Now that you have the proper path for AppleScript you need to fix the paths for the shell commands. Note that you do not need to rm and touch a file every time. Just use ">" when you redirect the echo command and that will overwrite the file. You also need to use the "quoted form" of paths in case there's spaces.
do shell script "echo " & quoted form of whatToSay & " > " & quoted form of POSIX path of prevSFile
However you're doing a lot of unnecessary stuff in that script. Here's how I would write your code. Good luck.
property whatToSay : ""
property numberOfTimes : 5
--Display dialoges:
display dialog "What do you want to say?" default answer whatToSay
set whatToSay to the text returned of the result
repeat
display dialog "How many times do you want to overlay it?" default answer (numberOfTimes as text)
try
set numberOfTimes to the (text returned of the result) as number
exit repeat
on error
display dialog "Please enter only numbers!" buttons {"OK"} default button 1
end try
end repeat
repeat numberOfTimes times
say whatToSay
end repeat

Applescript Shell Script Progress

I am creating an applescript that creates a backup image of the /Users folder in Mac Os X. I would like to do one of two things:
Either display a barber pole progress bar while the shell script is running with an option to quit.
Display a dialog box while the script is running with an option to quit.
I have tried doing the shell script with the /dev/null but that ignores all output. I would like to save the output and display it in a dialog for the user.
Here is my code:
set computername to (do shell script "networksetup -getcomputername")
set fin to ""
set theIcon to note
tell application "Finder"
try
set folderalias to "/Users"
set foldersize to physical size of folder (alias ":Users") --(info for folderalias)
set foldersize to (round ((foldersize / 1.0E+9) * 100)) / 100
on error
tell application "System Events"
set foldersize to (round (((get physical size of folder ":Users" as text) / 1.0E+9) * 100)) / 100
end tell
end try
end tell
display dialog "User profile backup utility" & return & return & ¬
"The computer name is: " & computername & return & return & ¬
"The '/Users/' directory size is: " & "~" & foldersize & " GB" & return & return & ¬
"Would you like to backup the '/User' directory now?" & return ¬
buttons {"Cancel", "Backup Now"} default button "Backup Now"
set comd to "hdiutil create ~/Desktop/" & computername & ".dmg -srcfolder /test/"
set fin to do shell script (comd) with administrator privileges
display dialog fin
Displaying a progress bar dialog is not possible with on-board AppleScript (i.e. Standard Additions), but this can be achieved using Shane Stanley’s ASObjC Runner, a scriptable faceless background application which provides, among many over useful functions, a set of progress dialog related commands. Once downloaded onto your system,
tell application "ASObjC Runner"
reset progress
set properties of progress window to {button title:"Abort Backup", button visible:true, message:"Backing up the '" & (POSIX path of folderalias) & "' directory.", detail:"There are " & foldersize & " GB of data to backup – this might take some time.", indeterminate:true}
activate
show progress
end tell
try -- to make sure we destroy the dialog even if the script error out
<your backup operation here>
end try
tell application "ASObjC Runner" to hide progress
will show an indeterminate progress bar (or “barber pole”) while the backup operation runs – at least if it is synchronous (as shell commands called from AS are). As to the output of your shell command, that is automatically returned by the do shell script command – in your code, it is assigned to fin [code lifted more or less wholesale from the ASObjC Runner documentation].
ASObjC Runner can be embedded into an AppleScript application (save your script as an application in AppleScript Editor) by putting it into the bundle’s Resources folder (in Finder, select Show Package Contents in the context menu) and using the path to resource command to call it inside a using terms from block – the documentation I linked to above has details and example code, but, crucially, contains one critical error: your tell statement needs to use the POSIX path to the Resources bundle (tell application (POSIX path of (path to resource "ASObjC Runner.app"))).
A few remarks on your code:
there is a more elegant way to get an alias to the /Users folder:
path to users folder
– no need for hardwiring and calls to Finder. You can then get the shell compatible path to that by using POSIX path of, or, if you need it quoted, quoted form of POSIX path of of it.
I’d recommend using only System Events to get the physical size – unlike Finder, it works in the background. That will allow you to get rid of the tell application "Finder" and try … catch blocks (not sure what you meant to achieve by that one anyway – if you were reacting to error -10004, that is because round does not like to be put inside a tell block).
No need to initialize fin to an empty string – you will get a return value from do shell script.
Speaking of your do shell script, you need to quote the computerName variable of it will break on spaces in that name.
theIcon is never used.
You might want to use display alert instead of display dialog for the user confirmation, as it has a nice emphasis on the first part of the message.
There are a lot of unnecessary parentheses in the code – AppleScript needs some of these to delimit semantic command blocks, but not all of them…
All together mean your code can be modified to:
set computerName to do shell script "networksetup -getcomputername"
set folderAlias to path to users folder
tell application "System Events" to set folderSize to physical size of folderAlias
set folderSize to round(folderSize / 1.0E+9 * 100) / 100
display alert "User profile backup utility" message ¬
"The computer name is: " & computerName & return & return & ¬
"The '" & (POSIX path of folderAlias) & "' directory size is: " & "~" & folderSize & " GB" & return & return & ¬
"Would you like to backup the '" & (POSIX path of folderAlias) & "' directory now?" & return ¬
buttons {"Cancel", "Backup Now"} default button "Backup Now"
set shellCmd to "hdiutil create ~/Desktop/'" & computerName & "'.dmg -srcfolder /test/"
-- progress bar dialog display initialization goes here
try
set shellOutput to do shell script shellCmd with administrator privileges
end try
-- progress bar dialog hiding goes here
display dialog shellOutput
Although not as pretty as kopischke's suggestion, a quick and dirty way to get progress information is to run the command in the terminal itself.
set comd to "hdiutil create -puppetstrings '~/Desktop/" & computername & ".dmg' -srcfolder '/test/'"
tell application "Terminal" to do script comd

Resources