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

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.

Related

How to automatically rename files when they get into folder

I've been trying to find a program or some sort of app to run all the time and check one folder. If any document would be saved in the folder it would rename it like file1.png the next one file2.png.
Transnomino has an automation feature that allows to automatically rename any file dropped in a folder using a specified renaming Recipe. The Apple Script that does this looks something like this:
on adding folder items to theAttachedFolder after receiving theNewItems
tell application "Finder" to set thePath to POSIX path of theAttachedFolder
return do shell script ¬
"open -a Transnomino --args -d \"" & thePath & "\" -r \"" & thePath & ".recipe\""
end adding folder items to
A complete guide how this can be setup is described on the website of Transnomino. Here: https://transnomino.bastiaanverreijt.com/automation/index.html

Folder Backup every 5 minutes (Applescript - Droplet)

i am trying to write a script ;
dragging a folder to droplet
The script sets "dropped folder" as source
List item
Set target (different location)
rsync every 5 minutes.
this is my starting point.
set source to "Dropped_Folder"
set destFolder to "/Users/xxx/Documents"
do shell script "/usr/bin/rsync -a " & (quoted form of source) & " " & (quoted form of destFolder)
Thanks!
This script will create a stay-open droplet that lets you store up a list of rsync commands and execute them periodically. Copy/paste this code into Script Editor, then save it as an Application, with the 'Stay open after run handler' checkbox clicked on.
Drag and drop a folder onto the app icon to set up an rsync
Double-click the app icon or click the dock icon to remove rsync commands from the internal list.
The app will execute all commands every execInterval seconds until you quit it, and resume executions when you restart it (unless you resave or recompile the app, which erases its persistant property storage).
property rsyncCommandList : {}
property execInterval : 300 -- 300 seconds is 5 minutes
on run
if (count of rsyncCommandList) = 0 then
display alert "No rsync commands set up. Drop a folder on the application icon to set up an rsync command." as informational
end if
end run
on reopen
if (count of rsyncCommandList) > 0 then
set deletableCommandList to (choose from list rsyncCommandList with prompt "Remove unwanted rsync commands" OK button name "Remove selected" with multiple selections allowed and empty selection allowed)
set revisedList to {}
repeat with thisItem in rsyncCommandList
if (get thisItem) is not in deletableCommandList then
copy thisItem to end of revisedList
end if
end repeat
set rsyncCommandList to revisedList
end if
end reopen
on open theseItems
repeat with thisItem in theseItems
set source to POSIX path of thisItem
set destination to POSIX path of (choose folder "Choose a destination folder for bacups of disk item '" & thisItem & "'")
set rsyncString to "/usr/bin/rsync -a " & (quoted form of source) & " " & (quoted form of destination)
copy rsyncString to end of rsyncCommandList
end repeat
end open
on idle
repeat with thisCommand in rsyncCommandList
do shell script thisCommand & " &> /dev/null"
end repeat
return execInterval
end idle

AppleScript - Change all app icons in a directory

I have folders containing applications. I want to be able to select the folder with an apple script, and have the script go through each app file in that directory, changing the icons for me.
I want to have the icon set from an image stored in the script directory.
I'd really appreciate any help because I've been trying to make this work for a while. This is my progress so far:
property appcurrentCount : 0
on run
set theFolder to (choose folder with prompt "Select the start folder")
doSomethingWith(theFolder)
end run
on doSomethingWith(aFolder)
tell application "Finder"
set subApps to every file of aFolder
repeat with eachFolder in subApps
-- replace icon here somehow
end repeat
end tell
display dialog "Count is now " & appcurrentCount & "."
end doSomethingWith
The script bellow does now what you want. As explained before, your icon file must be type icns. I now add this filter directly in the choose file command.
The selected icon will now replace ALL icons already in each Contents/Resources folder of all applications in the selected folder.
The replacement will be done preserving the name of the icns already in place.
Warning : there is no 'undo' command. your old icons are overwritten !!
set Myicon to choose file with prompt "Select Icns to be copied in every Application of the folder" of type "com.apple.icns"
set MyFolder to choose folder with prompt "Select the folder with all applications to be changed"
set Source to POSIX path of Myicon -- convert path to unix form
tell application "Finder"
set MyApps to every item of MyFolder whose name extension is "app"
display dialog "count apps=" & count of MyApps
repeat with anAps in MyApps -- loop for each App
set IcnFolder to ((anAps as string) & ":Contents:Resources:") as alias
set MyIcns to (every item of IcnFolder whose name extension is "icns")
display dialog "count of icn in " & alaps & " = " & (count of MyIcns)
repeat with oneIcon in MyIcns -- loop for each icns
set Destination to POSIX path of (oneIcon as string)
try
do shell script "cp " & (quoted form of Source) & " " & (quoted form of Destination)
end try
end repeat -- loop for each icns
end repeat -- loop for each App
end tell

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

Applescript: Finder got an error: AppleEvent handler failed

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)

Resources