Generate AFP connect script
Last modification: Sunday, November 01, 2009 10:05 amThis script will ask a few questions and generate a script application saved on the current user's desktop. The applet, which is editable, can be used to connect to a remote AFP server.
Implementation
on run-- Check requirements
if requireSystemVersion({__major:10, __minor:5, __revision:0}) is false then return false
-- Gather information
copy askUserForDetails() to {_macName, _address, _user, _share, _iconPosixPath}
if _macName is false then return false
generateConnectScript(_macName, _address, _user, _share, _iconPosixPath)
end run
on generateConnectScript(_macName, _address, _user, _share, _iconPosixPath)
-- Set destination folder
set _destinationFolder to (path to desktop folder from user domain as string)
-- Compose and compile the script
set _source to composeScript(_macName, _address, _user, _share)
if _share is not false and _share is not "" then
set _scriptName to _macName & " | " & _share
else
set _scriptName to _macName
end if
set _scriptPath to uniquePath(_destinationFolder, _scriptName, ".app")
set _scriptQPP to quoted form of (POSIX path of _scriptPath)
do shell script "/bin/echo " & quoted form of _source & " | /usr/bin/osacompile -o " & _scriptQPP
-- Copy the custom icon
if _iconPosixPath is not false then
set _iconPath to _scriptPath & ":Contents:Resources:applet.icns"
set _iconQPP to quoted form of (POSIX path of _iconPath)
do shell script "/bin/cp " & quoted form of _iconPosixPath & " " & _iconQPP
end if
end generateConnectScript
on uniquePath(_parent, _name, _suffix)
if existsFile(_parent & _name) is false then return (_parent & _name & _suffix)
set _rNumber to 2
repeat
set _testPath to _parent & _name & " " & (_rNumber as string) & _suffix
if existsFile(_testPath) is false then return (_testPath)
set _rNumber to _rNumber + 1
end repeat
end uniquePath
on existsFile(_path)
tell application "System Events"
return exists file _path
end tell
end existsFile
on composeScript(_macName, _address, _user, _share)
set _source to connectScriptSource()
set _source to searchAndReplace(_source, "--COMPUTER_NAME--", _macName)
set _source to searchAndReplace(_source, "--ADDRESS--", _address)
set _source to searchAndReplace(_source, "--USER_NAME--", _user)
set _source to searchAndReplace(_source, "--SHARE_NAME--", _share)
return _source
end composeScript
on askUserForDetails()
set _serviceType to "afpovertcp"
set _discoveredMacs to discoverBonjourServices(_serviceType, 0.5)
set _macName to letUserSelectDiscoveredMac(_discoveredMacs)
if _macName is false then
set _macName to askUserForString("computer_name_dialog_title", "")
if _macName is false then return {false, false, false, false, false}
set _address to false
else
copy lookupBonjourService(_serviceType, _macName, 0.5) to {_address, _port}
end if
set _address to askUserForString("address_dialog_title", _address)
if _address is false then return {false, false, false, false, false}
set _user to askUserForString("username_dialog_title", do shell script "/usr/bin/whoami")
set _share to askUserForString("sharename_dialog_title", "")
set _iconPosixPath to chooseMachineIcon()
return {_macName, _address, _user, _share, _iconPosixPath}
end askUserForDetails
on askUserForString(_localizedStringKey, _default)
if _default is false then set _default to ""
try
activate
set _string to text returned of (display dialog localizedString(_localizedStringKey) default answer _default)
on error
return false
end try
return _string
end askUserForString
on letUserSelectDiscoveredMac(_names)
set _defaultItems to {item 1 of _names}
activate
try
set _chosenMacs to choose from list _names default items _defaultItems with prompt localizedString("discovered_mac_selection_prompt")
if _chosenMacs is {} then error 1
return item 1 of _chosenMacs
on error
return false
end try
end letUserSelectDiscoveredMac
on discoverBonjourServices(_serviceType, _scantime)
-- Service types can be looked up at: http://www.dns-sd.org/ServiceTypes.html
script DiscoverBonjourServices_Extras
on sortList(_list)
set _prvDlmt to text item delimiters
set text item delimiters to ASCII character 10
set _string to _list as string
set text item delimiters to _prvDlmt
try
set _sortedString to do shell script "echo " & quoted form of _string & " | sort"
on error
return _list
end try
set _prvDlmt to text item delimiters
set text item delimiters to ASCII character 13
set _sortedList to text items of _sortedString
set text item delimiters to _prvDlmt
return _sortedList
end sortList
on hostnamesFromDiscoveryResults(_results, _serviceType)
set _hostnames to {}
set _prvDlmt to text item delimiters
set text item delimiters to ("_" & _serviceType & "._tcp.")
repeat with _i from 1 to count of _results
try
set _hostname to text item 2 of (item _i of _results)
set end of _hostnames to stripWhitespace(_hostname)
end try
end repeat
set text item delimiters to _prvDlmt
return _hostnames
end hostnamesFromDiscoveryResults
on filterDuplicateString(_strings)
set _uniqueStrings to {}
repeat with _i from 1 to count of _strings
if (item _i of _strings) is not in _uniqueStrings then
set end of _uniqueStrings to (item _i of _strings)
end if
end repeat
return _uniqueStrings
end filterDuplicateString
on stripWhitespace(_string)
set _charCount to count of characters of _string
-- Exit early if there's no string to process
if _charCount is 0 then return ""
-- Determine the first character that is not whitespace
repeat with _startChar from 1 to _charCount
if (ASCII number (character _startChar of _string)) > 32 then exit repeat
end repeat
-- Determine the last characters that is not whitespace
set _endChar to _charCount
repeat
if (ASCII number (character _endChar of _string)) > 32 then exit repeat
set _endChar to _endChar - 1
if _endChar is 0 then exit repeat
end repeat
-- Get the substring
set _prvDlmt to text item delimiters
set text item delimiters to ""
set _string to characters _startChar thru _endChar of _string as string
set text item delimiters to _prvDlmt
return _string
end stripWhitespace
on runDiscoveryScript(_serviceType, _scantime)
try
-- Start the script
set _script to {"#!/bin/bash"}
-- Use the mDNS tool to discover services
set end of _script to "/usr/bin/mDNS -B _" & _serviceType & "._tcp local &"
-- Keep track of the process id for the mDNS tool
set end of _script to "mDNSpid=$!"
-- Wait a little for mDNS to discover services
set end of _script to "sleep " & (_scantime as string)
-- Quit the mDNS tool
set end of _script to "kill -HUP $mDNSpid"
-- Compose the script
set _script to combineList(_script, ASCII character 10)
-- Run the script
set _result to do shell script _script
-- Get the actual results without the header
set _results to paragraphs 4 thru -1 of _result
return _results
on error _eMsg number _eNum
return {}
end try
end runDiscoveryScript
on combineList(_list, _delimiter)
set _prvDlmt to text item delimiters
set text item delimiters to _delimiter
set _list to _list as string
set text item delimiters to _prvDlmt
return _list
end combineList
end script
tell DiscoverBonjourServices_Extras
set _results to runDiscoveryScript(_serviceType, _scantime)
set _hostnames to hostnamesFromDiscoveryResults(_results, _serviceType)
set _hostnames to filterDuplicateString(_hostnames)
set _hostnames to sortList(_hostnames)
end tell
return _hostnames
end discoverBonjourServices
on lookupBonjourService(_serviceType, _computerName, _scantime)
script LookupBonjourService_Extras
on addressAndPortFromLookupResult(_result)
if _result does not contain "Service can be reached at" then return {false, false}
set _prvDlmt to text item delimiters
set text item delimiters to "Service can be reached at"
set _address to text item 2 of _result
set text item delimiters to ":"
set _port to text item 2 of _address
set _address to text item 1 of _address
set text item delimiters to ASCII character 13
set _port to text item 1 of _port
set text item delimiters to _prvDlmt
set _address to stripWhitespace(_address)
set _port to stripWhitespace(_port)
return {_address, _port}
end addressAndPortFromLookupResult
on runLookupScript(_serviceType, _computerName, _scantime)
try
-- Start the script
set _script to {"#!/bin/bash"}
-- Use the mDNS tool to discover services
set end of _script to "/usr/bin/mDNS -L " & quoted form of _computerName & " _" & _serviceType & "._tcp local &"
-- Keep track of the process id for the mDNS tool
set end of _script to "mDNSpid=$!"
-- Wait a little for mDNS to discover services
set end of _script to "sleep " & (_scantime as string)
-- Quit the mDNS tool
set end of _script to "kill -HUP $mDNSpid"
-- Compose the script
set _script to combineList(_script, ASCII character 10)
-- Run the script
set _result to do shell script _script
return result
-- Get the actual results without the header
set _results to paragraphs 4 thru -1 of _result
return _results
on error _eMsg number _eNum
return {}
end try
end runLookupScript
on combineList(_list, _delimiter)
set _prvDlmt to text item delimiters
set text item delimiters to _delimiter
set _list to _list as string
set text item delimiters to _prvDlmt
return _list
end combineList
on stripWhitespace(_string)
set _charCount to count of characters of _string
-- Exit early if there's no string to process
if _charCount is 0 then return ""
-- Determine the first character that is not whitespace
repeat with _startChar from 1 to _charCount
if (ASCII number (character _startChar of _string)) is greater than 32 then exit repeat
end repeat
-- Determine the last characters that is not whitespace
set _endChar to _charCount
repeat
if (ASCII number (character _endChar of _string)) is greater than 32 then exit repeat
set _endChar to _endChar - 1
if _endChar is 0 then exit repeat
end repeat
-- Get the substring
set _prvDlmt to text item delimiters
set text item delimiters to ""
set _string to characters _startChar thru _endChar of _string as string
set text item delimiters to _prvDlmt
return _string
end stripWhitespace
end script
tell LookupBonjourService_Extras
set _result to runLookupScript(_serviceType, _computerName, _scantime)
return addressAndPortFromLookupResult(_result)
end tell
end lookupBonjourService
on chooseMachineIcon()
script ChooseMachineIcon_Extras
on machineIconPaths()
try
set _iconDirectory to "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/"
return paragraphs of (do shell script "find " & _iconDirectory & "* -iname 'com.apple.*.icns'")
on error _eMsg
return {}
end try
end machineIconPaths
on machineIconNamesFromPaths(_paths)
set _names to {}
repeat with _i from 1 to count of _paths
set _prvDlmt to text item delimiters
set text item delimiters to "/"
set _fileName to text item -1 of item _i of _paths
set text item delimiters to _prvDlmt
set end of _names to correctCase(_fileName)
end repeat
return _names
end machineIconNamesFromPaths
on letUserSelectMachine(_machineIconPaths, _machineIconNames)
if _machineIconNames contains "Mac" then
set _defaultItems to {"Mac"}
else
set _defaultItems to {item 1 of _machineIconNames}
end if
activate
try
set _chosenIconName to choose from list _machineIconNames default items _defaultItems with prompt localizedString("machine_selection_prompt")
if _chosenIconName is {} then error 1
set _chosenIconName to item 1 of _chosenIconName
on error
return false
end try
repeat with _i from 1 to count of _machineIconNames
if item _i of _machineIconNames is _chosenIconName then
return item _i of _machineIconPaths
end if
end repeat
end letUserSelectMachine
on correctCase(_string)
set _string to searchAndReplace(_string, "com.apple.", "")
set _string to searchAndReplace(_string, ".icns", "")
set _string to searchAndReplace(_string, "-", " ")
set _string to searchAndReplace(_string, "macbook", "MacBook")
set _string to searchAndReplace(_string, "pro", " Pro")
set _string to searchAndReplace(_string, "air", " Air")
set _string to searchAndReplace(_string, " Airport", "Airport")
set _string to searchAndReplace(_string, "extreme", "Extreme")
set _string to searchAndReplace(_string, "time capsule", "Time Capsule")
set _string to searchAndReplace(_string, "xserve", "Xserve")
set _string to searchAndReplace(_string, "macmini", "Mac mini")
set _string to searchAndReplace(_string, "aluminum", "Aluminum")
set _string to searchAndReplace(_string, "black", "Black")
set _string to searchAndReplace(_string, "white", "White")
set _string to searchAndReplace(_string, "titanium", "Titanium")
set _string to searchAndReplace(_string, "graphite", "Graphite")
set _string to searchAndReplace(_string, "mirrored drive doors", "MDD")
set _string to searchAndReplace(_string, "quicksilver", "Quicksilver")
set _string to searchAndReplace(_string, "mac", "Mac")
set _string to searchAndReplace(_string, "book", "Book")
set _string to searchAndReplace(_string, "power", "Power")
set _string to searchAndReplace(_string, "g4", "G4")
set _string to searchAndReplace(_string, "g5", "G5")
set _prvDlmt to text item delimiters
set text item delimiters to " "
set _lastWord to text item -1 of _string
set text item delimiters to _prvDlmt
try
set _lastWord to _lastWord as integer
if _lastWord is greater than 0 then set _string to _string & "\""
end try
return _string
end correctCase
on searchAndReplace(_string, _search, _replace)
if _string does not contain _search then return _string
set _prvDlmt to text item delimiters
try
set text item delimiters to _search
set _stringItems to text items of _string
set text item delimiters to _replace
set _string to _stringItems as string
end try
set text item delimiters to _prvDlmt
return _string
end searchAndReplace
on localizedString(_string)
set _supportedLanguages to {"en", "de"}
set _targetLanguage to systemLanguage()
if _targetLanguage is not in _supportedLanguages then
set _targetLanguage to item 1 of _supportedLanguages
end if
set _stringKey to _string & "/" & _targetLanguage
if _stringKey is "machine_selection_prompt/en" then return "Please select a machine that matches the host:"
if _stringKey is "machine_selection_prompt/de" then return "Bitte w" & (ASCII character 138) & "hlen Sie das Model des anderen Macs:"
end localizedString
on systemLanguage()
try
return first word of (do shell script "/usr/bin/defaults read NSGlobalDomain AppleLanguages")
on error
return "en"
end try
end systemLanguage
end script
tell ChooseMachineIcon_Extras
set _machineIconPaths to machineIconPaths()
set _machineIconNames to machineIconNamesFromPaths(_machineIconPaths)
set _machineIconPath to letUserSelectMachine(_machineIconPaths, _machineIconNames)
end tell
return _machineIconPath
end chooseMachineIcon
on requireSystemVersion(_args)
-- Declare a few additional necessary functions
script RequireSystemVersion_Extras
on systemVersion()
try
-- Use system_profiler command line tool to get the information about the system version
set _spOutput to paragraph 1 of (do shell script "system_profiler SPSoftwareDataType -detailLevel mini | grep 'System Version: '")
-- Remove the label "System Version" from the line
set _prvDlmt to AppleScript's text item delimiters
set AppleScript's text item delimiters to "System Version: "
set _versionString to text item 2 of _spOutput
set AppleScript's text item delimiters to _prvDlmt
-- Find the position of the first numerical character
set _firstNumPosition to false
repeat with _i from 1 to count of _versionString
try
get (character _i of _versionString) as integer
set _firstNumPosition to _i
exit repeat
end try
end repeat
if _firstNumPosition is false then error "No numerical character found."
-- Break the string at the position of the first numerical character
set _prvDlmt to AppleScript's text item delimiters
set AppleScript's text item delimiters to ""
set _versionString to characters _firstNumPosition thru -1 of _versionString as string
-- Get the text before first space
set AppleScript's text item delimiters to " "
set _versionString to text item 1 of _versionString as string
-- Get the text before first space
set AppleScript's text item delimiters to "."
copy (text items of _versionString) to {_major, _minor, _revision}
set AppleScript's text item delimiters to _prvDlmt
-- Transform strings to integers
set _major to _major as integer
set _minor to _minor as integer
set _revision to _revision as integer
on error _eMessage
-- Reset the delimiters
set AppleScript's text item delimiters to _prvDlmt
-- This alternative will work for systems that do not support the do shell script command
set _hex to system attribute "sysv"
-- Get the revision
set _revision to _hex mod 16
set _hex to _hex div 16
-- Get the minor version
set _minor to _hex mod 16
set _hex to _hex div 16
-- Get the major version
set _major1 to _hex mod 16 as string
set _hex to _hex div 16
set _major2 to _hex mod 16 as string
set _hex to _hex div 16
set _major to (_major2 & _major1 as string) as integer
-- Concatenate the version string
set _versionString to (_major as string) & "." & (_minor as string) & "." & (_revision as string)
end try
return {__major:_major, __minor:_minor, __revision:_revision, __string:_versionString}
end systemVersion
on localizedString(_string, _var)
set _stringKey to _string & "/" & systemLanguage()
if _stringKey is "requirements_not_met_dialog_title/en" then return "System not supported"
if _stringKey is "requirements_not_met_dialog_title/de" then return "Nicht unterst" & (ASCII character 159) & "tztes System"
if _stringKey is "requirements_not_met_dialog_message/en" then return "This script requires at least system version " & _var & ". "
if _stringKey is "requirements_not_met_dialog_message/de" then return "Dieses Skript erfordert mindestens die Systemversion " & _var & ". "
end localizedString
on systemLanguage()
try
return first word of (do shell script "defaults read NSGlobalDomain AppleLanguages")
on error
return "en"
end try
end systemLanguage
end script
-- Get the current system version
tell RequireSystemVersion_Extras to set _currentVersion to systemVersion()
-- Check if requirements are met
if (__major of _currentVersion) < (__major of _args) then
set _requirementsMet to false
else if (__major of _currentVersion) = (__major of _args) then
if (__minor of _currentVersion) < (__minor of _args) then
set _requirementsMet to false
else if (__minor of _currentVersion) = (__minor of _args) then
if (__revision of _currentVersion) < (__revision of _args) then
set _requirementsMet to false
else
set _requirementsMet to true
end if
else
set _requirementsMet to true
end if
else
set _requirementsMet to true
end if
if _requirementsMet is false then
-- Display a dialog if requirements are not met
set _requiredVersionString to (__major of _args as string) & "." & (__minor of _args as string) & "." & (__revision of _args as string)
tell RequireSystemVersion_Extras
set _dialogTitle to localizedString("requirements_not_met_dialog_title", null)
set _dialogMessage to localizedString("requirements_not_met_dialog_message", _requiredVersionString)
end tell
activate
try
if (__major of _currentVersion) ≥ 10 and (__minor of _currentVersion) ≥ 4 then
display alert _dialogTitle message _dialogMessage buttons {"OK"} default button "OK" as warning
else
error 1
end if
on error
display dialog _dialogTitle & return & return & _dialogMessage buttons {"OK"} default button "OK" with icon 2
end try
return false
else
return true
end if -- _requirementsMet is false
end requireSystemVersion
on localizedString(_string)
set _supportedLanguages to {"en", "de"}
set _targetLanguage to systemLanguage()
if _targetLanguage is not in _supportedLanguages then
set _targetLanguage to item 1 of _supportedLanguages
end if
set _stringKey to _string & "/" & _targetLanguage
if _stringKey is "discovered_mac_selection_prompt/en" then return "Please select the Mac to create the connection script for. Press Cancel to enter custom information."
if _stringKey is "discovered_mac_selection_prompt/de" then return "Bitte w" & (ASCII character 138) & "hlen Sie den Mac aus, f" & (ASCII character 159) & "r den Sie das Verbindungsskript erstellen wollen. Sie k" & (ASCII character 154) & "nnen auch Abbruch dr" & (ASCII character 159) & "cken, um alle Informationen selbst anzugeben."
if _stringKey is "computer_name_dialog_title/en" then return "Please specify the name of the Mac to connect to:"
if _stringKey is "computer_name_dialog_title/de" then return "Bitte geben Sie den Namen des anderen Macs an:"
if _stringKey is "address_dialog_title/en" then return "Please specify the address of the Mac to connect to:"
if _stringKey is "address_dialog_title/de" then return "Bitte geben Sie die Adresse des anderen Macs an:"
if _stringKey is "username_dialog_title/en" then return "Please specify the user name to connect to the other Mac as:"
if _stringKey is "username_dialog_title/de" then return "Bitte geben Sie den Namen des Benutzers an, der sich an dem anderen Macs anmelden soll:"
if _stringKey is "sharename_dialog_title/en" then return "Please specify the name of the share:"
if _stringKey is "sharename_dialog_title/de" then return "Bitte geben Sie den Namen des Netzwerklaufwerks an:"
end localizedString
on systemLanguage()
try
return first word of (do shell script "/usr/bin/defaults read NSGlobalDomain AppleLanguages")
on error
return "en"
end try
end systemLanguage
on searchAndReplace(_string, _search, _replace)
if _string does not contain _search then return _string
set _prvDlmt to text item delimiters
try
set text item delimiters to _search
set _stringItems to text items of _string
set text item delimiters to _replace
set _string to _stringItems as string
end try
set text item delimiters to _prvDlmt
return _string
end searchAndReplace
on connectScriptSource()
return "set _computerName to \"--COMPUTER_NAME--\"
set _url to \"--ADDRESS--\"
set _user to \"--USER_NAME--\"
set _shareName to \"--SHARE_NAME--\"
connectToAFPServer(_computerName, _user, _url, _shareName)
on connectToAFPServer(_computerName, _user, _url, _shareName)
script ConnectToAFPServer_Extras
on connectHost(_user, _url)
try
if _user is \"\" or _user is false then
open location \"afp://\" & _url
else
open location \"afp://\" & _user & \"@\" & _url
end if
return true
on error
return false
end try
end connectHost
on connectShare(_user, _url, _shareName)
try
if _user is \"\" or _user is false then
open location \"afp://\" & _url & \"/\" & _shareName
else
open location \"afp://\" & _user & \"@\" & _url & \"/\" & _shareName
end if
return true
on error
return false
end try
end connectShare
on isShareMounted(_computerName, _shareName)
tell application \"System Events\"
set _foundDisks to disks whose name is _shareName and local volume is false and server is _computerName
end tell
if _foundDisks is {} then
return false
else
return true
end if
end isShareMounted
on openShare(_computerName, _shareName)
tell application \"System Events\"
repeat 15 times
set _foundDisks to disks whose name is _shareName and local volume is false and server is _computerName
if _foundDisks is not {} then exit repeat
delay 1
end repeat
if _foundDisks is {} then return false
set _diskPosixPath to (POSIX path of (item 1 of _foundDisks) as string)
set _diskQPP to quoted form of (POSIX path of (item 1 of _foundDisks) as string)
set _launchBarRunning to exists process \"LaunchBar\"
end tell
if _launchBarRunning then
tell application \"LaunchBar\" to open {_diskPosixPath}
else
do shell script \"/usr/bin/open \" & _diskQPP
end if
return true
end openShare
on displayError(_computerName, _shareName, _url)
if _shareName is \"\" or _shareName is false then
set _alertTitle to (localizedString(\"alert_title\", false, false))
else
set _alertTitle to (localizedString(\"alert_title_for_share\", _shareName, false))
end if
set _alertMessage to localizedString(\"alert_message\", _computerName, _url)
tell application \"Finder\"
activate
display alert _alertTitle message _alertMessage buttons \"OK\" default button 1 as warning
return false
end tell
end displayError
on localizedString(_string, _var, _var2)
set _supportedLanguages to {\"en\", \"de\"}
set _targetLanguage to systemLanguage()
if _targetLanguage is not in _supportedLanguages then
set _targetLanguage to item 1 of _supportedLanguages
end if
set _stringKey to _string & \"/\" & _targetLanguage
if _stringKey is \"alert_title/en\" then return \"Connection failed\"
if _stringKey is \"alert_title/de\" then return \"Fehler bei der Verbindung\"
if _stringKey is \"alert_title_for_share/en\" then return \"Could not connect to \" & _var
if _stringKey is \"alert_title_for_share/de\" then return \"Fehler bei der Verbindung mit \" & _var
if _stringKey is \"alert_message/en\" then return _var & \" could not be found on the network. Please check the following:
" & (ASCII character 225) & " \" & _var & \" is turned on and not in sleep mode
" & (ASCII character 225) & " \" & _var & \"’s address is indeed \" & _var2 & \"
" & (ASCII character 225) & " The Firewall settings on \" & _var & \" allow file sharing
" & (ASCII character 225) & " Network devices and cables are known to be working\"
if _stringKey is \"alert_message/de\" then return _var & \" konnte nicht im Netzwerk gefunden werden. Bitte \" & (ascii character 159) & \"berpruefen Sie Folgendes:
" & (ASCII character 225) & " \" & _var & \" ist eingeschaltet und nicht im Ruhezustand
" & (ASCII character 225) & " \" & _var & \"s Adresse ist tats" & (ASCII character 138) & "chlich \" & _var2 & \"
" & (ASCII character 225) & " Die Firewall Einstellungen von \" & _var & \" erlauben File Sharing
" & (ASCII character 225) & " Netzwerkkabel sind eingesteckt
" & (ASCII character 225) & " Netzwerkger" & (ASCII character 138) & "te funktionieren\"
end localizedString
on systemLanguage()
try
return first word of (do shell script \"/usr/bin/defaults read NSGlobalDomain AppleLanguages\")
on error
return \"en\"
end try
end systemLanguage
end script
tell ConnectToAFPServer_Extras
-- Exit early, if the remote share is already mounted.
if _shareName is not \"\" and _shareName is not false then
if isShareMounted(_computerName, _shareName) then return openShare(_computerName, _shareName)
end if
-- Exit early, if the remote host cannot be contacted.
if checkOpenPort(_url, 548, 3) is false then
return displayError(_computerName, _shareName, _url)
end if
if _shareName is \"\" or _shareName is false then
-- Connect to the remote host and let user select share
return connectHost(_user, _url)
else
-- Connect to the share
if connectShare(_user, _url, _shareName) is false then return false
return openShare(_computerName, _shareName)
end if
end tell
end connectToAFPServer
on checkOpenPort(_address, _port, _timeout)
script CheckOpenPort_Extras
on pathForTemporaryFile(_folderName)
(*
Generates a unique path for a file in the
current user's temporary items folder.
Takes a single argument that can be set
to the name of a subfolder or false to
create no subfolder.
*)
-- Create timestamp
set _date to current date
set _month to month of _date as integer
set _day to day of _date
set _year to year of _date as string
set _time to (time of _date)
set _hour to _time div 60 div 60
set _minute to (_time div 60) - (_hour * 60)
set _second to _time - (_minute * 60) - (_hour * 60 * 60)
if _month is less than 10 then set _month to \"0\" & _month
if _day is less than 10 then set _day to \"0\" & _day
set _yearShort to characters -2 thru -1 of _year
if _hour is less than 10 then set _hour to \"0\" & _hour
if _minute is less than 10 then set _minute to \"0\" & _minute
if _second is less than 10 then set _second to \"0\" & _second
set _prvDlmt to AppleScript's text item delimiters
set AppleScript's text item delimiters to \"\"
set _timeStamp to ((_year & \"-\" & _month & \"-\" & _day & \"_\" & _hour & \"-\" & _minute & \"-\" & _second) as string)
set AppleScript's text item delimiters to _prvDlmt
-- Generate pseudorandom numbers
set _rand1 to (round (random number from 100 to 999)) as string
set _rand2 to (round (random number from 100 to 999)) as string
set _rand3 to (round (random number from 100 to 999)) as string
set _rand4 to (round (random number from 100 to 999)) as string
set _randomString to _rand1 & \"-\" & _rand2 & \"-\" & _rand3 & \"-\" & _rand4
-- Create file name
set _fileName to ((_timeStamp & \"_\" & _randomString) as string)
-- Get the path to the parent folder
set _temporaryFolderPath to path to temporary items folder from user domain as string
if _folderName is false then
set _parentFolderPath to _temporaryFolderPath
else
set _parentFolderPath to _temporaryFolderPath & _folderName & \":\"
tell application \"System Events\" to if (exists folder _parentFolderPath) is false then make new folder at the end of folders of folder _temporaryFolderPath with properties {name:_folderName}
end if
-- Make sure the file does not exist
set _rNumber to 1
repeat
if _rNumber is 1 then
set _tempFilePath to _parentFolderPath & _fileName
else
set _tempFilePath to _parentFolderPath & _fileName & \"_\" & (_rNumber as string)
end if
tell application \"System Events\" to if (exists file _tempFilePath) is false then exit repeat
set _rNumber to _rNumber + 1
end repeat
return _tempFilePath
end pathForTemporaryFile
end script
-- Quote the address
set _addressQ to quoted form of _address
set _portQ to quoted form of (_port as string)
-- Get the path to a unique temporary file as a quoted posix path (QPP)
tell CheckOpenPort_Extras to set _strokeFilePath to pathForTemporaryFile(\"CheckOpenPort\")
set _strokeFileQPP to quoted form of (POSIX path of _strokeFilePath)
-- Reset cache
do shell script \"/usr/bin/dscacheutil -flushcache\"
-- Run stroke tool
set _strokeToolQPP to quoted form of \"/Applications/Utilities/Network Utility.app/Contents/Resources/stroke\"
set _pid to do shell script _strokeToolQPP & \" \" & _addressQ & \" \" & _portQ & \" \" & _portQ & \" > \" & _strokeFileQPP & \" 2>&1 & echo $!\"
-- Make sure the _pid is an integer
try
set _pid to _pid as integer
on error
set _pid to false
end try
-- Check for result
set _timeTaken to 0.0
repeat
try
set _strokeResult to do shell script \"/bin/cat \" & _strokeFileQPP
on error
set _strokeResult to \"\"
end try
if _strokeResult is not \"\" then
if _strokeResult contains \"Open TCP Port\" or _strokeResult contains \"Open UDP Port\" then
-- Clean up
try
if _pid is not false then do shell script \"/bin/kill \" & (_pid as string)
end try
do shell script \"/bin/rm -f \" & _strokeFileQPP
-- Return positive result
return true
end if
end if
delay 0.1
set _timeTaken to _timeTaken + 0.1
if _timeTaken is greater than or equal to _timeout then exit repeat
end repeat
-- Clean up
try
if _pid is not false then do shell script \"/bin/kill \" & (_pid as string)
end try
do shell script \"/bin/rm -f \" & _strokeFileQPP
-- Return negative result
return false
end checkOpenPort"
end connectScriptSource