How to reveal default Safari downloads folder through Applescript? - macos

I am new to AppleScript and would like to know how to reveal the default downloads folder in Safari through AppleScript.
--- WHAT I HAVE ALREADY TRIED ---
set filePath to do shell script "defaults read com.apple.Safari DownloadsPath"
do shell script "open " & quoted form of filePath
The above script to my understanding will set the variable "filePath" to Safari's default PList entry in preferences.
This works great as long as the location is NOT somewhere within the user home folder. If its within a user folder, the Log shows me a "~/" before the path with no reference to anything prior to the user home folder (relative path)
How do i accomplish my goal? is there a way to get the absolute path to the folder? Or perhaps an alternative method?

Based on #WilliamTFroggard's answer:
tell application "Finder"
set folderPath to do shell script "defaults read com.apple.Safari DownloadsPath"
if folderPath = "~" or folderPath starts with "~/" then ¬
set folderPath to text 1 thru -2 of POSIX path of (path to home folder) & rest of characters of folderPath
open POSIX file folderPath as alias
activate
end tell
The text element is used to strip the trailing / from the home folder (/Users/johndoe/).
The rest property returns every character following the ~ in folderPath (~/Downloads).
/Users/johndoe + /Downloads = /Users/johndoe/Downloads.

You can do this by Applescript GUI Scripting to make Applescript click the 'show downloads' option from the 'view' menu:
tell application "Safari"
activate
end tell
tell application "System Events"
tell process "Safari"
tell menu bar 1
tell menu bar item "view"
tell menu "View"
click menu item "Show downloads"
end tell
end tell
end tell
end tell
end tell

Here's a method using Python:
do shell script "python -c \"import os; print os.path.expanduser('`defaults read com.apple.Safari DownloadsPath`')\""
If you really want the long AppleScript method, try this:
set filePath to ""
set AppleScript's text item delimiters to "/"
set filePathWords to words of (do shell script "defaults read com.apple.Safari DownloadsPath")
if item 1 of filePathWords is "~" then
set item 1 of filePathWords to (POSIX path of (path to home folder as string))
set filePath to filePathWords as string
else
set filePath to "/" & filePathWords as string
end if
If that second "/" in the path bothers you (it sort of bothers me...), you can use this instead:
set filePath to ""
set AppleScript's text item delimiters to "/"
set filePathWords to words of (do shell script "defaults read com.apple.Safari DownloadsPath")
if item 1 of filePathWords is "~" then
set item 1 of filePathWords to (do shell script "cd ~ && pwd")
set filePath to filePathWords as string
else
set filePath to "/" & filePathWords as string
end if

I think what you want is this:
tell application "Finder"
activate
open ("/Users/yourname/Downloads" as POSIX file)
end tell
Just replace "yourname" with your name in Finder.

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.

Error when replacing characters applescript

I am trying to make a script that executes a runnable Jar file in the form of an applescript application. I'm not very experienced in applescript, so I mostly went off of online snippets. The first problem I ran into was that the directory automatically formats as using a ":" instead of a slash (ex. "usr:bin" instead of "usr/bin") so I found something that's supposed to replace the : with a /. This, however, produces an error every time.
I've found little on how to fix my error and the stuff I found was very specific to those cases and didn't make much sense to me.
This is my code:
tell application "Finder"
set current_path to container of (path to me) as alias
end tell
set AppleScript's text item delimiters to ":"
set currPath to text items of current_path
set AppleScript's text item delimiters to "/"
set current_path to currPath as string
set AppleScript's text item delimiters to {""}
currPath
tell application "Terminal"
activate
set currentTab to do script ("cd " & current_path)
set currentTab to do script ("java -jar Inoisulcnoc Pre-Alpha 2")
end tell
The error I get every time says:
error "Can’t get every text item of alias \"Macintosh HD:Users:knotsnappy:Desktop:Inoisulcnoc Pre-Alpha 2:\"." number -1728 from every text item of alias "Macintosh HD:Users:knotsnappy:Desktop:Inoisulcnoc Pre-Alpha 2:"
How should I be able to fix this?
You'll want to change the standard path into a POSIX path.
tell application "Finder"
set current_path to (POSIX path of (container of (path to me) as alias))
end tell
tell application "Terminal"
activate
set currentTab to do script ("cd " & current_path)
set currentTab to do script ("java -jar Inoisulcnoc Pre-Alpha 2")
end tell
The delimiters, etc. are unneeded once you have the correct syntax.

Struggling to reference cliclick (stored in the same location as script) within applescript workflow

I've been writing a workflow for Alfred 2 which takes a selected jpeg on the users desktop - inserts it to google chrome then use cliclick to right click and reverse search the image via google search.
I cant seem to avoid having the user to put the cliclick in there home folder any attempt to reference the file elsewhere seems to return a systems events error in applescript.
Any help would be appreciated! (I'm extremely new to applescript and alfred apologises if this is a very simple problem)
--get location of selected folder
tell application "Finder"
set sel to the selection as text
set the clipboard to POSIX path of sel
end tell
activate application "Google Chrome"
--open selected jpeg in google chrome
tell application "System Events" to tell process "Google Chrome"
delay 1
keystroke "t" using command down
keystroke "v" using command down
key code 36
delay 1
-- calculate the top left corner of the image
set myBounds to bounds of window 1 of application "Google Chrome"
set x to item 1 of myBounds
set y to item 2 of myBounds
--locate cliclick in users home
set uHome to get path to home folder
set locHome to POSIX path of uHome
--run the right click -> search by image mouse event
do shell script "" & locHome & "/cliclick m:" & x & "," & y & "w:100 kd:ctrl c:+2,+74 ku:ctrl w:1000 c:+66,+90 w:700"
end tell
--close "file://" tab
tell application "Google Chrome"
set windowList to every tab of every window whose URL starts with "file://"
repeat with tabList in windowList
set tabList to tabList as any
repeat with tabItr in tabList
set tabItr to tabItr as any
delete tabItr
end repeat
end repeat
end tell
I tried using
set UnixPath to POSIX path of ((path to me as text) & "::" & "cliclick")
in replacement of
set uHome to get path to home folder
set locHome to POSIXpath of uHome
but replacing it into the shell script with
do shell script "" & UnixHome & " m:" & x & "," & y & "w:100 kd:ctrl c:+2,+74 ku:ctrl w:1000 c:+66,+90 w:700"
stops the workflow with the System Event error
The Script as it stands (cl.ly link)
You could put cliclick in the resource folder of your app and call it like this:
set pathtocc to quoted form of (POSIX path of (path to resource "cliclick"))
do shell script pathtocc & " -h"
Or let curl do the job:
set imagefile to POSIX path of ¬
(choose file of type "public.image" default location path to desktop)
do shell script "
open -a 'Google Chrome' $(curl -F 'encoded_image=#" & imagefile & ¬
"' https://www.google.com/searchbyimage/upload | grep 'tbs=sbi' | sed 's/^.*http/http/;s/\".*$//')"
curl -F uploads the file to reverse search. The output is a redirect which includes the URL to the google result page.

Writing current file path in comment of file in Automator

I'm trying to write the current file path in the comment text box; the one you see when you right-click and Get Info. I'm pretty close, because I got it to write a file path to all the files inside a folder, but all the file paths are the same for some reason.
For example, when I right click a file after I run the script and see the comment, it might be "'/Users/Admin/Desktop/automator test/folder/spikyBall#2x copy 4.png'" and it will be that for all the files.
My Shell Script variable is defined as:
bashFilePath=$(osascript -e 'tell application "Finder" to set filePath to quoted form of posix path of (item 1 of (get selection) as text)');
echo $bashFilePath;
If I am interpreting your question correctly, try this:
echo $1
In shell scripts, $1 is the first argument ($2, $3, etc. also work). So the above just echoes the first argument... which with your automator program is the path of the file.
I ended up using pure Apple script for this. Select any files and folders that you want and run the script. It can also be made into a files or folders Service in Automator.
tell application "Finder"
activate
set fileList to selection
if (count result) is 0 then
try
get (target of front Finder window) as alias
on error
choose folder with prompt "Set comments of files in this folder:"
end try
try
set theFolder to result
set fileList to every file of folder (result) as alias list
end try
end if
display dialog "How would you like to set comments?" buttons {"Overwrite", "Cancel"} default button 2 with title "Set Spotlight Comments current to file path"
set userInput to the result
set itemNum to 1
if (button returned of userInput) is "Overwrite" then
if (class of first item of fileList) is alias then
set comment of every file of folder theFolder to POSIX path of (item itemNum of (get selection) as text)
set itemNum to itemNum + 1
else
repeat with thisFile in fileList
set comment of thisFile to POSIX path of (item itemNum of (get selection) as text)
set itemNum to itemNum + 1
end repeat
end if
end if
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

Resources