Folder Backup every 5 minutes (Applescript - Droplet) - applescript

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

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.

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

how to prevent password prompt pops up many times

My code looks like:
set sourceFolder1 to (path to library folder as text) & "Frameworks:SDL.framework"
set sourceFolder2 to (path to library folder as text) & "Frameworks:SDL_ttf.framework"
set sourceFolder3 to (path to library folder as text) & "Frameworks:SDL_image.framework"
tell application "Finder"
if exists folder sourceFolder1 then
delete folder sourceFolder1
end if
if exists folder sourceFolder2 then
delete folder sourceFolder2
end if
if exists folder sourceFolder3 then
delete folder sourceFolder3
end if
end tell
When I test it, the password prompt pops up 3 times to ask for password. Is there a way to prevent the password prompt pops up more than once? Thanks.
LJ
The Finder is asking for password because you're trying to remove a file from a location that the user doesn't have delete privileges for.
One way to solve this would be to do the deletion via shell commands. Replace delete folder sourcefolder1 with:
do shell script ("rm -rf '" & posix path of sourcefolder1 & "'") ¬
with administrator privileges user name "username" password "password"
Then it won't ask at all. If you want it to ask once, remove everything from user name onward. It will remember the entry for the subsequent commands.
Update: per comment below, the need is to be able to move the item to the Trash rather than delete it outright as rm does. I couldn't think of any way to do it in straight AppleScript, because the administrator prompting is coming from the Finder, and AppleScript (as far as I know) can only perform a privileged action programmatically with the do shell script command. So I wrote a routine that should be equivalent to "Move To Trash" in the Finder:
to deleteItem(thisItem)
set thisItemPath to (POSIX path of thisItem)
set uid to (do shell script "id -u")
if thisItemPath starts with "/Volumes" then
set AppleScript's text item delimiters to "/"
set volName to text item 3 of thisItemPath
set AppleScript's text item delimiters to ""
set targetPath to ¬
("/Volumes/" & volName & "/.Trashes/" & uid)
else
set targetPath to ((POSIX path of (path to home folder)) & ".Trash")
end if
set moveToTrashCmd to ¬
("mkdir -p '" & targetPath & "'; " & ¬
"mv '" & thisItemPath & "' '" & targetPath & "'")
-- set global vars first for userName and password, or omit for prompt
do shell script moveToTrashCmd ¬
with administrator privileges user name userName password userPw
end if
end deleteItem
Here's a sample program that uses the routine:
global fileItems, userName, userPw
on run
set userPw to "password"
set AppleScript's text item delimiters to ":"
set userName to text item -2 of (path to home folder as string)
set AppleScript's text item delimiters to ""
try
fileItems
on error
set fileItems to ¬
(choose folder with prompt ¬
"Select folders to delete:" with multiple selections allowed)
end try
repeat with thisItem in fileItems
deleteItem(thisItem)
end repeat
end run
-- drag 'n' dropped files
on open docs
set fileItems to docs
run
end open
To prevent the password prompt pops up more than once : Use the delete command only once by putting all the folders or files in a list.
Like this:
set frmWKsList to {}
set librF to path to library folder as text
set end of frmWKsList to librF & "Frameworks:SDL.framework"
set end of frmWKsList to librF & "Frameworks:SDL_ttf.framework"
set end of frmWKsList to librF & "Frameworks:SDL_image.framework"
set foldersToDelete to {}
tell application "Finder"
repeat with i in frmWKsList
if exists folder i then set end of foldersToDelete to i as alias
end repeat
delete foldersToDelete
end tell

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

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