AppleScript Wi-Fi connector - applescript

I have been trying to explore AppleScript a bit by writing a few simple lines of code. I have tried writing a small bit that would allow me to access the list of Wi-Fi's available, and input the password to said Wi-Fi.
So far I have gotten to the point where it recognizes the Wi-Fi's available, but does not allow me to make the Wi-Fi into a type string. I have written the code for selecting the Wi-Fi from a list, but I cannot figure out how to make the Wi-Fi's into a list.
Would anyone be able to help me figure this out?
display dialog "Wifi Selector © Afnaan Qureshi"
set main to display dialog " ." buttons {"Quit", "Enter Password"}
if main = {button returned:"Enter Password"} or trueaftermain = "1" then
set results to paragraphs 2 thru -1 of (do shell script "/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -s | sed -nE 's/[ ]*(.*) [a-z0-9]{2}:[a-z0-9]{2}:.+/\\1/p'")
set my_list to results
set AppleScript's text item delimiters to ", "
set list_2_string to my_list as text
set main to display dialog my_list
set wpass to choose from list {my_list} with title "Pick The Wifi" with prompt "Choose WPA2" OK button name "Choose" cancel button name "Cancel" default items {"quit"}
end if

Your code is too complicated.
results is already the list you are expecting.
set results to paragraphs of (do shell script "/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -s | sed -nE 's/[ ]*(.*) [a-z0-9]{2}:[a-z0-9]{2}:.+/\\1/p'")
set wpass to choose from list results with title "Pick The Wifi" with prompt "Choose WPA2" OK button name "Choose"
Be aware that wpass is also a list, or false if the user presses Cancel
And if you are using text item delimiters make sure to reset the delimiters later to avoid unexpected behavior.

Related

AppleScript "on open" misbehavior

I have a list of jpeg images on a local server that I use an AppleScript droplet to resize in Photoshop. I use "on open" to do this, but something strange happens: they open in two parts.
The files are named as follows:
0_203.jpg
1_203.jpg
2_203.jpg
3_203.jpg
4_203.jpg
5_203.jpg
6_203.jpg
7_203.jpg
8_203.jpg
9_203.jpg
10_203.jpg
11_203.jpg
12_203.jpg
13_203.jpg
14_203.jpg
15_203.jpg
16_203.jpg
17_203.jpg
18_203.jpg
19_203.jpg
20_203.jpg
The script should do its actions to each file in turn, but something strange happens: it breaks the files into two groups and runs the script twice. The script splits the groups like this:
1_203.jpg
2_203.jpg
3_203.jpg
4_203.jpg
5_203.jpg
6_203.jpg
7_203.jpg
8_203.jpg
9_203.jpg
10_203.jpg
11_203.jpg
12_203.jpg
...and then runs again with these files...
0_203.jpg
13_203.jpg
14_203.jpg
15_203.jpg
16_203.jpg
17_203.jpg
18_203.jpg
19_203.jpg
20_203.jpg
What the hell is going on here?
Here's the test script I used to debug:
on open myItems
set myList to {}
set AppleScript's text item delimiters to ":"
repeat with thisItem in myItems
set newItem to thisItem as string
copy newItem to end of myList
end repeat
display dialog myList as string
end open
See the question and answers posted here. I gave a work-around as a solution.

Applescript, show all files with tag

I am trying to build an applescript which will open show all files tagged with the school class I am currently in, based on current time. For instance, if the time is 10 AM on a Tuesday, it will show all my files tagged with Chemistry. Now, I have made the AppleScript to get the correct name of the class.
Now I need to tell Finder to open the files with the correct tags. How would I do this?
Basicaly, something like this:
set tagged to "Tag:Chemistry"
tell application "Finder"
reveal tagged
activate
end tell
Ofcourse, tagged here would be dynamically assigned.
The way way I would do this in the GUI is with Smart Folders. Go in the Finder, click on File->New Smart Folder and a new Finder window appears. Click on + at the top right beside Save and change Kind at top left of window to Tags. Beside Tags choose contains and then type Chemistry. Click Save at top right and call it Chemistry Stuff and allow it to be added to the side-bar. Then it will appear on the left of all Finder windows.
In the shell/Terminal, where I usually reside, I use tag for that purpose. I installed it with homebrew using brew install tag. Then I can do tag -f sometag and it lists all the files that are tagged sometag.
tag - A tool for manipulating and querying file tags.
usage:
tag -a | --add <tags> <file>... Add tags to file
tag -r | --remove <tags> <file>... Remove tags from file
tag -s | --set <tags> <file>... Set tags on file
tag -m | --match <tags> <file>... Display files with matching tags
tag -l | --list <file>... List the tags on file
tag -f | --find <tags> Find all files with tags
<tags> is a comma-separated list of tag names; use * to match/find any tag.
additional options:
-v | --version Display version
-h | --help Display this help
-n | --name Turn on filename display in output (default)
-N | --no-name Turn off filename display in output (list, find, match)
-t | --tags Turn on tags display in output (find, match)
-T | --no-tags Turn off tags display in output (list)
-g | --garrulous Display tags each on own line (list, find, match)
-G | --no-garrulous Display tags comma-separated after filename (default)
-H | --home Find tagged files only in user home directory
-L | --local Find tagged files only in home + local filesystems (default)
-R | --network Find tagged files in home + local + network filesystems
-0 | --nul Terminate lines with NUL (\0) for use with xargs -0
You can use the GUI Scripting to click on left-pane in the finder window.
Because this script use GUI Scripting to control the user-interface, you must add the applet to an approval list, displayed in the Security & Privacy system preference pane.
set tagName to "Chemistry" -- the full tag's name
my showFinderWindow(tagName)
on showFinderWindow(thisTag)
tell application "Finder" to if not (exists Finder window 1) then make new Finder window
tell application "System Events"
tell process "Finder"
repeat with i in windows
tell outline 1 of scroll area 1 of splitter group 1 of i to if exists then
tell (first row whose value of its static text 1 is thisTag) to if exists then perform action "AXOpen" of static text 1
exit repeat
end if
end repeat
end tell
end tell
end showFinderWindow
You can use the command line tool "mdfind" to search for tagged files using "kMDItemUserTags". So that's how I would find the tagged files.
The other part of your problem is finding the proper tag for the current time-of-day. I would use applescript records for this. For example you can make a record like this:
{theTag:"Chemistry", startTime:date ("10:00 AM"), endTime:date ("11:00 AM")}
So if you make a list of records you can loop through them and compare the start and end times of each record in the list to the current date.
Finally, once you have that and assuming you found some files with mdfind then you can just loop through the found files and ask the Finder to open them.
Try this. Note you have to supply your values for "requirementsRecords" and "searchFolder" in the user variables section.
-- user variables
set requirementsRecords to {{theTag:"Chemistry", startTime:date ("10:00 AM"), endTime:date ("11:00 AM")}, {theTag:"Math", startTime:date ("11:00 AM"), endTime:date ("12:00 PM")}}
set searchFolder to path to desktop
-- find the tag information given the current time
set now to current date
set thisTag to missing value
repeat with i from 1 to count of requirementsRecords
set thisRecord to item i of requirementsRecords
set thisStartTime to startTime of thisRecord
set thisEndTime to endTime of thisRecord
if now is greater than or equal to thisStartTime and now is less than or equal to thisEndTime then
set thisTag to theTag of thisRecord
exit repeat
end if
end repeat
if thisTag is missing value then error "Could not find a tag for the current time!"
-- search the search folder for files with the tag
set cmd to "mdfind -onlyin " & quoted form of POSIX path of searchFolder & " \"kMDItemUserTags == " & quoted form of thisTag & "\""
set resultsList to paragraphs of (do shell script cmd)
if resultsList is {} then error "Could not find any files tagged \"" & thisTag & "\" in the search folder"
-- open the found files with the Finder
repeat with anItem in resultsList
set thisFile to POSIX file anItem
tell application "Finder" to open thisFile
end repeat

Determine OS X keyboard layout ("input source") in the terminal/a script?

I would like to determine the OS X keyboard layout (or "input source" as OS X calls it) from the terminal so that I can show it in places like the tmux status bar.
So I want to know if the current layout is "U.S." or "Swedish - Pro" for example.
Googling turns up nothing for me. Is this possible?
Note: #MarkSetchell deserves credit for coming up with the fundamental approach - where to [start to] look and what tools to use.
After further investigation and back and forth in the comments I thought I'd summarize the solution (as of OS X 10.9.1):
do shell script "defaults read ~/Library/Preferences/com.apple.HIToolbox.plist \\
AppleSelectedInputSources | \\
egrep -w 'KeyboardLayout Name' | sed -E 's/^.+ = \"?([^\"]+)\"?;$/\\1/'"
Note how \ is escaped as \\ for the benefit of AppleScript, which ensures that just \ reaches the shell. If you want to execute the same command directly from the shell (as one line), it would be:
defaults read ~/Library/Preferences/com.apple.HIToolbox.plist AppleSelectedInputSources | egrep -w 'KeyboardLayout Name' |sed -E 's/^.+ = \"?([^\"]+)\"?;$/\1/'
The currently selected keyboard layout is stored in the user-level file ~/Library/Preferences/com.apple.HIToolbox.plist, top-level key AppleSelectedInputSources, subkey KeyboardLayout Name.
defaults read ensures that the current settings are read (sadly, as of OSX 10.9, the otherwise superior /usr/libexec/PlistBuddy sees only a cached version, which may be out of sync).
Since defaults read cannot return an individual key's value, the value of interest must be extracted via egrep and sed - one caveat there is that defaults read conditionally uses double quotes around key names and string values, depending on whether they are a single word (without punctuation) or not.
Update:
Turns out that AppleScript itself can parse property lists, but it's a bit like pulling teeth.
Also, incredibly, the potentially-not-fully-current-values problem also affects AppleScript's parsing.
Below is an AppleScript handler that gets the current keyboard layout; it uses a do shell script-based workaround to ensure that the plist file is current, but otherwise uses AppleScript's property-list features, via the Property List Suite of application System Events.
Note: Obviously, the above shell-based approach is much shorter in this case, but the code below demonstrates general techniques for working with property lists.
# Example call.
set activeKbdLayout to my getActiveKeyboardLayout() # ->, e.g., "U.S."
on getActiveKeyboardLayout()
# Surprisingly, using POSIX-style paths (even with '~') works with
# the `property list file` type.
set plistPath to "~/Library/Preferences/com.apple.HIToolbox.plist"
# !! First, ensure that the plist cache is flushed and that the
# !! *.plist file contains the current value; simply executing
# !! `default read` against the file - even with a dummy
# !! key - does that.
try
do shell script "defaults read " & plistPath & " dummy"
end try
tell application "System Events"
repeat with pli in property list items of ¬
property list item "AppleSelectedInputSources" of ¬
property list file plistPath
# Look for (first) entry with key "KeyboardLayout Name" and return
# its value.
# Note: Not all entries may have a 'KeyboardLayout Name' key,
# so we must ignore errors.
try
return value of property list item "KeyboardLayout Name" of pli
end try
end repeat
end tell
end getActiveKeyboardLayout
Recently I had written a small console utility (https://github.com/myshov/xkbswitch-macosx) on Objective-C to do this. It's a lot faster than a script based solutions. It can to get the current input layout but also it can to set the given input layout.
To get a current layout:
$xkbswitch -ge
> US
To set a given layout:
$xkbswith -se Russian
I am not sure of this answer, but it may be worth checking out. If you look in file:
/Library/Preferences/com.apple.HIToolbox.plist
there is a variable called
AppleCurrentKeyboardLayoutSourceID
and mine is set to "British" and I am in Britain...
You can read the file in a script with:
defaults read /Library/Preferences/com.apple.HIToolbox.plist AppleEnabledInputSources
sample output below:
(
{
InputSourceKind = "Keyboard Layout";
"KeyboardLayout ID" = 2;
"KeyboardLayout Name" = British;
}
)
So, I guess your question can be simply answered using this:
#!/bin/bash
defaults read /Library/Preferences/com.apple.HIToolbox.plist AppleEnabledInputSources | grep -sq Swedish
[[ $? -eq 0 ]] && echo Swedish
This question led to the creation of the keyboardSwitcher CLI Tool:
https://github.com/Lutzifer/keyboardSwitcher
Though similar to the already mentioned https://github.com/myshov/xkbswitch-macosx this has additional features, e.g. the list of Layouts is not hardcoded and thus can also support third party layouts (e.g. Logitech) and supports installation via homebrew.
Figured out how to do it with AppleScript, assuming you have the menu bar input menu.
Run this in a terminal:
osascript -e 'tell application "System Events" to tell process "SystemUIServer" to get the value of the first menu bar item of menu bar 1 whose description is "text input"'
Works fine even if you only show the input menu as flag icons, without the input source name.
Mavericks will probably prompt you to allow access, the first time. In earlier versions of OS X I suspect you'll need to turn on support for assistive devices in your accessibility preferences.
I was searching for an answer to an issue I was having with the keyboard layout that lead me to this post. I found the solution for my problem here.
Resolved Issues
You might experience difficulty logging into your account because the keyboard layout may change unexpectedly at the
Login window. (40821875)
Workaround: Log in to your account, launch Terminal, and execute the
following command:
sudo rm -rf /var/db/securityagent/Library/Preferences/com.apple.HIToolbox.plist
This is an Apple official release note for Mojave

The End If Woes in Applescript

Hey everyone. I can't figure this out for the life of me. Why can't I use 'end if' here?
display dialog "Input your Hard Drive name *Case sensitive*
For Example:
Jimi
Steve
Jony" default answer ""
set hdd_name to text returned of result
set folder_name to "~/Desktop/Backup Files"
display alert "Time Machine Extractor" message "Would you like to backup the" & folder_name & " directory now?" & return buttons {"Cancel", "Backup Now"} default button "Backup Now"
set theButton to button returned of the result
if theButton is "Cancel" then error number -128
**end if**
set shellCmd to "open /Volumes/" & quoted form of hdd_name & "/"
set shellCopy to "cp -r " & quoted form of folder_name & " /Volumes/" & quoted form of hdd_name
tell application "ASObjC Runner"
reset progress
set properties of progress window to {button title:"Cancel", button visible:true, message:"Backing up...", indeterminate:true}
activate
show progress
end tell
try
do shell script shellCmd
end try
try
set shellOutput to do shell script shellCopy
end try
tell application "ASObjC Runner" to hide progress
display dialog "Copy Complete"
So where I have the end if, it keeps telling me I have a syntax error. Any ideas?
You need to start a new line after the then
i.e,
if theButton is "Cancel" then
error number -128
end if

Remove specific characters from highlighted text using AppleScript or Automator

I have a question and maybe someone can point me in the right direction.
I would like to be able to copy Text (mostly from "Get Info") and replace all the “.” with a space excluding the “.”before the file extension using AppleScript or Automator. I'd like to use this service when i right click and select the script or automator service.
E.G
Contraband.2012.DVDRip.htif-NYsIC.avi
will turn to
Contraband 2012 DVDRip htif-NYsIC.avi
I've search everywhere on this site and various places but I just cant seem to find what i need. I don’t know where to start writing this script. Is what i described even possible in apple script? I just need to be pointed in the right direction and I'll try and figure the rest out I'm just at a loss right now.
Thank's in advance.
You could use a Run Shell Script action like this:
for f; do
base=${f##*/}
[[ $base =~ .+\..+ ]] || continue
noext=${base%.*}
mv "$f" "${f%/*}/${noext//./ }.${base##*.}"
done
Set "Pass input" to "as arguments". ${f##*/} removes the longest */ pattern from the start of f and ${f%/*} removes the shortest /* pattern from the end of f.
You could also use a Run AppleScript action like this:
on run {input}
repeat with f in input
set text item delimiters to "."
tell application "Finder"
set ti to text items of (get name of (f as alias))
if number of ti > 2 then
set AppleScript's text item delimiters to " "
set name of (f as alias) to (items 1 thru -2 of ti as text) & "." & item -1 of ti
end if
end tell
end repeat
end run

Resources