TweetFollow Us on Twitter

An Introduction to Scripting Fetch

Volume Number: 22 (2006)
Issue Number: 5
Column Tag: Scripting

AppleScript Essentials

An Introduction to Scripting Fetch

by Benjamin S. Waldie

For the past several months, we have discussed ways to store and access data from AppleScript. We have talked about script properties, property list files, scriptable database applications, and more. In this month's column, I'd like to switch gears, and talk about a great application that I have been scripting quite a lot lately. That application is Fetch.Fetch is a popular FTP/SFTP client for the Macintosh. It is a commercial application, and a demonstration version is available for download from the Fetch Softworks website at <http://www.fetchsoftworks.com>. If you do not own a license for Fetch, then I encourage you to download a demonstration version, so that you may follow along with the various example scripts throughout this month's column.



Figure 1. Fetch's Well-Known Icon

All of the example code that we will discuss was written and tested with Fetch version 5.1b2. As when scripting any application, if you are using an older or newer version of Fetch, then you may notice some differences in the AppleScript terminology. If this occurs, please refer to Fetch's AppleScript dictionary for guidance in determining the proper syntax to use.

Connecting to a Server

The first thing that we are going to discuss, is the process of connecting to a remote server. For my testing, I enabled incoming FTP access in the Sharing system preference on another Mac OS X computer, on my local network. However, I could have just as easily chosen to access a remote server, such as the one hosting my website, or one of a client. For your testing, if you have a second machine running Mac OS X, then you can enable incoming FTP access (you'll probably want to ensure that your network is secure, or enable a firewall prior to doing this) for testing. Otherwise, you will need to find a server that you can access remotely via FTP or SFTP.

Making a new server connection in Fetch, is done by creating a new window, called a transfer window. See figure 2.



Figure 2. A Transfer Window Connection

Creating a transfer window is done with the use of the make command, as demonstrated in the example code below. You will want to replace my example IP address, username, password, and initial directory with ones that are relevant to the server to which you are attempting to connect.

set theServerAddress to "10.0.1.3"
set theUserName to "myUserName"
set thePassword to "myPassword"
set theDirectory to "Documents/FTP Main/"

tell application "Fetch"
   make new transfer window at beginning with properties {hostname:theServerAddress, 
   username:theUserName, password:thePassword, initial folder:theDirectory}
end tell
--> transfer window id 120663408 of application "Fetch"

As you can see from the code above, the result of making a new transfer window is a reference to the newly created window. Notice that the window is referenced by its ID. As you navigate to different folders on the remote server, the transfer window's name will change. Therefore, to refer to the newly created transfer window again later in your code, you may want to capture this result in a variable. For example:

tell application "Fetch"
   set theTransferWindow to make new transfer window at beginning with properties 
   {hostname:theServerAddress, username:theUserName, password:thePassword, initial 
   folder:theDirectory}
end tell

When a transfer window is made, its default authentication type is FTP. However, you may explicitly specify that a different type of authentication be used, such as SFTP. This can be done by specifying a value for the transfer window's authentication property, when the transfer window is created, as the following code demonstrates.

tell application "Fetch"
   make new transfer window at beginning with properties {hostname:theServerAddress, 
   username:theUserName, password:thePassword, initial folder:theDirectory, authentication:SFTP}
end tell

As previously mentioned, one way to refer to a transfer window in the future is to do so by setting a variable to the result when making a transfer window. This variable would include a reference to the transfer window using a unique ID. If you are working with an existing transfer window, you can find out its unique ID with the use of the following code:

tell application "Fetch"
   id of front transfer window
end tell
--> 120663408

Once you have a window's ID, you can refer to it later by that ID. For example:

tell transfer window id 96356736
   -- Add Code Here
end tell

You may also have the need to retrieve the name of a transfer window. However, as mentioned before, the name of the transfer window will change if you open a remote folder.

tell application "Fetch"
   name of transfer window 1
end tell
--> "10.0.1.3 -- FTP Main"

You can also refer to a transfer window by its index, or front to back order. For example, the following code would target the frontmost transfer window, which has an index of 1.

tell transfer window 1
   -- Add Code Here
end tell

Throughout this column, all of my example code will target a transfer window by its index.

Working with Remote Items (Part 1)

Now that we have discussed connecting to a server, let's begin to look at ways to interact with the remote items on that server. First, let's turn to remote folders.

Suppose you want to create a remote folder on the server. First, you will probably want to determine if the folder already exists. To do this, use the exists command. For example:

tell application "Fetch"
   tell transfer window 1
      remote folder "Job 1000" exists
   end tell
end tell
--> false

If the remote folder did not exist, then you can choose to create it. Like creating a server connection, you will use the make command to create a folder. The following example code demonstrates the proper syntax for performing this task. Figure 3 shows an example of a newly created remote folder.

tell application "Fetch"
   make remote folder at transfer window 1 with properties {name:"Job 1000"}
end tell



Figure 3. A Newly Created Remote Folder

Now that you have a remote folder, you may want to open it. To do this, use the open command, as demonstrated by the following code.

tell application "Fetch"
   tell transfer window 1
      open remote folder "Job 1000"
   end tell
end tell

Note that, after opening a folder, the name of the transfer window will be changed to reflect the currently opened folder. An example of this can be seen in figure 4.



Figure 4. An Opened Remote Folder

Uploading

We will return to interacting with remote items shortly. For now, we will discuss uploading items to the server.

To upload an item to a remote directory, you will make use of Fetch's put into command. The following example code demonstrates the proper use of this terminology. First, it will prompt the user to select a file. It will then upload that file to the currently opened remote folder on the server. Figure 5 shows an example of an uploaded item.

set thePath to choose file with prompt "Please select an item to upload:" without invisibles
tell application "Fetch"
   with timeout of 300 seconds
      put into transfer window 1 item thePath
   end timeout
end tell



Figure 5. An Uploaded Item

The put into command's only required parameter is the item parameter, which we have utilized in the previous code to indicate the path of the desired file to be uploaded. The put into command also offers the ability to specify a number of optional parameters , which can affect how the item is uploaded. For example, you might specify the resume parameter if you want to resume a previous upload. Or, you might specify the uniquename parameter, if you want Fetch to automatically assign a unique name to the item if an item with the same name that already exists. For a complete list of the put into command's optional parameters, please refer to Fetch's AppleScript dictionary.

Working with Remote Items (Part 2)

Whether or not you have uploaded items to the server yourself, there will probably be times when you will want, or need, to interact with remote items on a server. See figure 6.



Figure 6. A Folder of Remote Items

We have already discussed how to navigate folders on a server. Now, let's talk about how to get the contents of a folder. The following example code will retrieve the names of every remote item in the currently opened folder.

tell application "Fetch"
   tell transfer window 1
      name of every remote item
   end tell
end tell
--> {"Job Image 1.png", "Job Image 2.png", "Job Image 3.png"}

    NOTE: In the previous code, we referenced every remote item. A remote item can be either a file or a folder on the server. To target one or the other specifically, use either remote file or remote folder instead.

You can also retrieve numerous properties of remote items on a server, such as the remote item's path, modification date, permissions, and more. The following example code demonstrates how to retrieve the size of a remote item, in bytes.

tell application "Fetch"
   tell transfer window 1
      size of remote item "Job Image 1.png"
   end tell
end tell
--> 66242

As you work with remote items, you may also have the need to delete a remote item. This can be done by using the delete command. For example:

tell application "Fetch"
   tell transfer window 1
      delete remote item "Job Image 2.png"
   end tell
end tell

Downloading

We have covered uploading items to a server. Now, let's talk briefly about downloading items. To download an item, use the download command, and specify a folder into which the remote item should be downloaded. For example:

set theOutputFolder to path to desktop folder
tell application "Fetch"
   tell transfer window 1
      download remote item "Job Image 1.png" to theOutputFolder
   end tell
end tell
--> {file "Macintosh HD:Users:bwaldie:Desktop:Job Image 1.png"}

As you can see from the previous example code, the download command will result in a list of file references to the newly downloaded items.

Miscellaneous Tasks

When working with a transfer window, whether uploading, downloading, or otherwise, you may want to determine the status of the server connection. This can be done by accessing the transfer window's status property. For example:

tell application "Fetch"
   tell transfer window 1
      status
   end tell
end tell
--> "Connected."

The status property will return the text of the current status of the fetch window, as it appears visually at the bottom of the window itself. Other transfer window attributes, which can often be useful when scripting Fetch, are also accessible via properties. Such attributes include the elapsed transfer time, and the bytes transferred, of a current transfer.

Once you have completed your Fetch scripting, you may want to have your script close down the server connection. This can be done by using the close command to close the transfer window. For example:

tell application "Fetch"
   close transfer window 1
end tell

Recording and Next Steps

Now that we have discussed various ways to interact with Fetch via AppleScript, I should also mention that Fetch is one of those rare applications that supports recording! That is, you can click the Record button in a Script Editor window, perform tasks manually in Fetch, and those tasks will be translated into AppleScript code, and written for you automatically in the Script Editor window. See figure 7 for an example of a recorded Fetch script.



Figure 7. Recording Manual Fetch Activity

You may be asking "Why didn't he mention that Fetch was recordable in the first place?" Well, one reason I didn't mention this is because I wanted to show how easy it is to begin scripting Fetch without recording. Another reason is that there are limitations to recording AppleScript code in any application. A recorded script does not include variables, if/then statements, or repeat loops. Because of this, recorded scripts are typically not as efficient as scripts written from scratch. Recorded scripts also perform tasks exactly as you recorded them, and do not have the ability to analyze situations and take different courses of action. However, recording is still a good way to get started, and it can often be helpful in determining the proper syntax for performing that certain task when you just can't figure it out on your own. Furthermore, you always have the ability to go back and edit your recorded scripts, to make them more efficient, or to add logic to them.



Figure 8. Fetch Example Scripts

If you plan to begin scripting Fetch, another good place to start is to download the example scripts that are available from the Fetch Softworks website at <http://fetchsoftworks.com/downloads.html>. These example scripts will provide you with unlocked, editable sample code for performing tasks such as connecting to servers, uploading items, and more. See figure 8.

In Closing

Although this month's column focused specifically on using Fetch as a scriptable FTP/SFTP client, please be aware that it is not your only choice. There are other applications and tools that are used by AppleScript developers for transferring files across networks.

Transmit, available from Panic Software at <http://www.panic.com>, and Cyberduck, available at http://www.cyberduck.ch are two other popular FTP/SFTP clients for Macintosh, and are frequently utilized by scripters. URL Access Scripting, which is built into Mac OS X, can be used for performing uploads and downloads to remote servers. URL Access Scripting can be found in the System > Library > ScriptingAdditions folder in Mac OS X. Many AppleScript developers also choose to utilize the power of UNIX for performing network file transfers. The do shell script AppleScript command in Mac OS X can be used in conjunction with UNIX tools such as curl or ftp to perform such tasks.

Until next time, keep scripting!


Ben Waldie is the author of the best selling books "AppleScripting the Finder" and the "Mac OS X Technology Guide to Automator", available from http://www.spiderworks.com. Ben is also president of Automated Workflows, LLC, a company specializing in AppleScript, and workflow automation consulting. For years, Ben has developed professional AppleScript-based solutions for businesses including Adobe, Apple, NASA, PC World, and TV Guide. For more information about Ben, please visit http://www.automatedworkflows.com, or email Ben at applescriptguru@mac.com.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

MacPilot 15.0.2 - $15.96 (53% off)
MacPilot gives you the power of UNIX and the simplicity of Macintosh, which means a phenomenal amount of untapped power in your hands! Use MacPilot to unlock over 1,200 features, and access them all... Read more
Visual Studio Code 1.85.0 - Cross-platfo...
Visual Studio Code provides developers with a new choice of developer tool that combines the simplicity and streamlined experience of a code editor with the best of what developers need for their... Read more
Spotify 1.2.26.1187 - Stream music, crea...
Spotify is a streaming music service that gives you on-demand access to millions of songs. Whether you like driving rock, silky R&B, or grandiose classical music, Spotify's massive catalogue puts... Read more
Transmission 4.0.5 - Popular BitTorrent...
Transmission is a fast, easy, and free multi-platform BitTorrent client. Transmission sets initial preferences so things "just work", while advanced features like watch directories, bad peer blocking... Read more
Fantastical 3.8.9 - Create calendar even...
Fantastical is the Mac calendar you'll actually enjoy using. Creating an event with Fantastical is quick, easy, and fun: Open Fantastical with a single click or keystroke Type in your event details... Read more
Notion 3.0.0 - A unified workspace for m...
Notion is the unified workspace for modern teams. Features: Integration with Slack Documents Wikis Tasks Release notes were unavailable when this listing was updated. Download Now]]> Read more
GarageBand 10.4.10 - Complete recording...
GarageBand is the easiest way to create a great-sounding song on your Mac. Add realistic, impeccably produced and performed drum grooves to your song with Drummer. Easily shape the sound of any... Read more
Pacifist 4.1.0 - Install individual file...
Pacifist opens up .pkg installer packages, .dmg disk images, .zip, .tar. tar.gz, .tar.bz2, .pax, and .xar archives and more, and lets you extract or install individual files out of them. This is... Read more
Xcode 15.0.1 - Integrated development en...
Xcode includes everything developers need to create great applications for Mac, iPhone, iPad, and Apple Watch. Xcode provides developers a unified workflow for user interface design, coding, testing... Read more
Google Chrome 120.0.6099.62 - Modern and...
Google Chrome is a Web browser by Google, created to be a modern platform for Web pages and applications. It utilizes very fast loading of Web pages and has a V8 engine, which is a custom built... Read more

Latest Forum Discussions

See All

TouchArcade Game of the Week: ‘Sonic Dre...
I can still remember the time I played my first 3D Sonic game. It was at Hollywood Video (that’s a video rental store for you young ones out there) and my buddy was the manager, and he invited me and my friend to hang out in the store after they... | Read more »
SwitchArcade Round-Up: Strictly Limited...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for December 8th, 2023. In today’s article, we start off with a couple of news items. Nothing from The Game Awards, that’s a bit beyond the scope of what I usually do here. But I do have... | Read more »
Football Manager 2024 Interview – We Tal...
Last month, SEGA and Sports Interactive released Football Manager 2024 on Apple Arcade (Touch), Netflix (Mobile), consoles, PC, and even Game Pass. If you missed my detailed review covering many versions of the game, read it here. | Read more »
‘Shiren the Wanderer: The Mystery Dungeo...
Recently, my son and I were invited to attend a special hands-on preview event at Spike Chunsoft’s headquarters in Tokyo to play the upcoming Shiren the Wanderer: The Mystery Dungeon of Serpentcoil Island for Nintendo Switch, which is scheduled for... | Read more »
Apple Arcade Weekly Round-Up: Updates fo...
We just had a huge content drop on Apple Arcade earlier this week with Sonic Dream Team, Disney Dreamlight Valley, Puzzles and Dragons, and more hitting the service. Today (and as of a few days ago), many notable games on the service have gotten... | Read more »
‘Genshin Impact’ Version 4.3 Update “Ros...
Following two trailers during The Game Awards 2023, HoYoverse has more news today with the next major Genshin Impact (Free) update detailed for all platforms. | Read more »
Christmas comes to Pokemon Unite, closel...
It's time to swap your Pokeballs for snowballs as a new festive mode has launched in The Pokemon Company International’s 5v5 MOBA Pokemon Unite. The presents don't stop there, however, as a brand new challenger is entering the arena, all the way... | Read more »
What to expect in World of Tanks Blitz’s...
World of Tanks Blitz is updating that old story of Santa sneaking down your chimney and silently leaving presents like a jolly old ninja into something a little more modern. Vinnie Jones has traded the sleigh for a tank and is ringing in the... | Read more »
‘Arknights: Endfield’ From Gryphline Get...
Last year, Arknights developer Hypergryph announced Arknights: Endfield for mobile and PC platforms. Arknights: Endfield is a 3D real-time RPG with strategic elements set in the world of Arknights. | Read more »
‘Zenless Zone Zero’ TGA 2023 Trailer Con...
During The Game Awards 2023, HoYoverse had two trailers. The first was a quick recap video for Honkai Star Rail with a tease of things to come next year. It continues to look superb. The highlight was urban fantasy action RPG Zenless Zone Zero... | Read more »

Price Scanner via MacPrices.net

Update: Apple Watch Series 9 models now $70 o...
Walmart has Apple Watch Series 9 models on Holiday sale for $70 off MSRP on their online store this weekend (that’s $20 cheaper than their earlier price). Sale prices available for online orders only... Read more
Apple’s AirTags 4-Pack is on Holiday sale for...
Apple retailers have 4-pack AirTags on sale this weekend for $19 off MSRP as part of their Holiday sales. These make a great stocking stuffer: (1): Amazon has Apple AirTags 4 Pack on sale for $79.99... Read more
Sunday Sale: $100 off every Apple iPad mini 6
Amazon is offering Apple’s 8.3″ iPad minis for $100 off MSRP, including free shipping, as part of their Holiday sale this weekend. Prices start at $399. Amazon’s prices are the lowest currently... Read more
16-inch M3 Pro MacBook Pros (18GB/512GB) are...
Looking for the best price on a 16″ M3 Pro MacBook Pro this Holiday shopping season? B&H and Amazon are currently offering a $250 discount on the 16″ M3 Pro MacBook Pro (18GB RAM/512GB SSD),... Read more
Apple Watch SE models on Holiday sale for $50...
Walmart has Apple Watch SE GPS-only models on Holiday sale on their online store for $50 off MSRP this weekend. Sale prices for online orders only, in-store prices may vary. Order online, and choose... Read more
Apple Watch Series 9 models on Holiday sale t...
Walmart has Apple Watch Series 9 models on Holiday sale for $50 off MSRP on their online store this weekend. Sale prices available for online orders only, in-store prices may vary. Order online, and... Read more
Apple has the 13-inch M2 MacBook Air in stock...
Apple has Certified Refurbished 13″ M2 MacBook Airs available starting at only $929 and ranging up to $210 off MSRP. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year... Read more
Apple’s 10th-generation iPads on Holiday sale...
Amazon has Apple’s 10th-generation WiFi iPads on sale for $100 off MSRP, starting at only $349, as part of their Holiday sales this weekend. With the discount, Amazon’s prices are the lowest we’ve... Read more
Apple Watch Series 9 models Holiday sale this...
Amazon has Apple Watch Series 9 models on sale for up to $90 off MSRP, each including free shipping, as part of their Holiday sale this weekend. Stock is likely to come and go at Amazon, so check... Read more
Apple Watch Ultra 2 models on Holiday sale th...
Amazon is offering a $50 discount on Apple Watch Ultra 2 models as part of their Holiday sale this weekend. Their price is now $749 for most models. Shipping is free. Amazon’s price is the lowest... Read more

Jobs Board

Principal Offering Sales - Modern Workplace...
…Job Description **Who you are** + **Drives Modern Workplace sale, focusing on Apple Managed Services across the enterprise globally.** + **Owns the Apple Read more
Material Handler 1 - *Apple* (1st shift) -...
Material Handler 1 - Apple (1st shift)Apply now " Apply now + Start apply with LinkedIn + Apply Now Start + Please wait Date:Dec 8, 2023 Location: Irwindale, CA, US, Read more
Macintosh/ *Apple* Systems Administrator, TS...
…to a team-based environment. + Perform systems administration support tasks for Apple MacOS and iOS operating systems. + TDY travel (approximately 25%) for Read more
Principal Offering Sales - Modern Workplace...
…Job Description **Who you are** + **Drives Modern Workplace sale, focusing on Apple Managed Services across the enterprise globally.** + **Owns the Apple Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.