Advertisement
Automation

Creating an AppleScript to Switch Between Multiple iTunes Accounts

by

Introduction

If you own an Apple device, you'll have an Apple ID which will also be your account for shopping in iTunes. Some Apple owners may have multiple Apple IDs: perhaps work, personal, for shared content with family members or even Apple IDs for iTunes stores in different countries.

If you have multiple Apple IDs that you use with iTunes, you'll already be familiar with the hassle of changing accounts frequently and having to type the credentials each time.

In this tutorial, I'll be showing you how create an AppleScript that enables easy switching, between all of your Apple IDs, with a single click inside iTunes.


Before We Begin

Before we begin, it is important to understand that this is an advanced tutorial using AppleScript. If you are unfamiliar with AppleScript, you are first advised to check out some beginner tutorial published on Mactuts+. I've listed them below.


1. The Aim

The aim of this tutorial is to code an AppleScript that enables you to:

  • save all your Apple ID accounts in a plist file
  • log in into iTunes using a registered account
  • delete all registered accounts

The script saves all of your Apple ID accounts in a plist file with following structure: each file row has as key a label that identify the account, and it has as value an array that contains the Apple ID email address and password.

Tip: Note that the password fields, in the plist file, are not encrypted. In order to protect this, it is recommended that you set up a password on your OS X user account. Consider setting up separate user accounts in OS X if you share your Mac with anyone else.

The image below shows an example of the plist file updated with two Apple IDs registered.

Accounts Plist file
Accounts Plist file

If you are unfamiliar with plist files, I recommend you read the documentation about it on the Apple Developer site.


2. Launch the AppleScript Editor

Launch the AppleScript Editor app. You will find the application inside Applications > Utility. Alternatively, type the app name into Spotlight (or Alfred app) to launch it.

AppleScript Editor
AppleScript Editor

The AppleScript Editor is your development environment where you can write, edit, compile and test your AppleScript code. Once you have opened the app you can start to write the script.


3. Begin Coding the Script

The script has some functions that simplify the main code so it will be more readable and clear. Let's code the functions.

Step 1

The first function allows the creation of a plist file which contains all of your Apple ID accounts. The code below defines the function.

-- Function to create a plist file 
on createAccountsFile(filePath)
    tell application "System Events"
        -- Create the Root Dictionary
        set rootDict to make new property list item with properties {kind:record}
        -- Add the Root Dictionary to a new plist file saved in filePath
        set plistFile to make new property list file with properties {contents:rootDict, name:filePath}
    end tell
end createAccountsFile

The createAccountsFile(filePath) function has one parameter filePath which is the POSIX path of your plist file. Line 5 creates the Root dictionary and line 7 saves it to the new plist file.

Step 2

A second function allows you to add a new Apple account to plist file. The addAccount(filePath, label, email, pass) function has four parameters:

  • filePath is the POSIX path of plist file
  • label is a label to identify the Apple account
  • email is the email of Apple ID account
  • pass identifies the account password

The code below implements the function defined.

-- Function to register a new Apple account
on addAccount(filePath, label, email, pass)
    tell application "System Events"
        -- Open the plist file
        tell property list file filePath
            -- Get the plist file content
            tell contents
                -- Append a new row with all account info to the Root Dictionary of plist file
                make new property list item at end with properties {kind:list, name:label, value:{email, pass}}
            end tell
        end tell
    end tell
end addAccount

Step 3

The function coded below returns a list of all labels of each account. The getLabels(filePath) has one parameter only: the filePath that is the plist file POSIX path.

-- Function to get all accounts labels
on getLabels(filePath)
    -- Define an empty list that will contains all labels 
    set labels to {}
    tell application "System Events"
        -- Get the plist file content and save it in fileContent variable
        set fileContent to property list items of contents of property list file filePath
        -- Scan each file row and add each label to labels list
        repeat with account in fileContent
            set label to name of account
            set end of labels to label
        end repeat
    end tell
    -- Return the list with all labels
    return labels
end getLabels

Step 4

Another important function is getAccountInfo(filePath, selectedAccount) that returns information (email and password) about a registered Apple account. The function below has two parameters:

  • filePath is the POSIX path of plist file
  • selectedAccount is the chosen account when you run the final script

The code below implements the function.

-- Function to get email and password of a selected account
on getAccountInfo(filePath, selectedAccount)
    tell application "System Events"
        -- Open the plist file and get its content
        set fileContent to property list file (filePath)
        -- Get information based on selectedAccount
        set info to value of property list item selectedAccount of fileContent
    end tell
    -- Return the info array
    return info
end getAccountInfo

Step 5

The getPath(fileName) function coded below, implements a utility function that returns the absolute POSIX path of a file specified by the parameter fileName. In our case, the file name will represent the plist file with all Apple accounts.

-- Function to get the absolute path of a file
on getPath(fileName)
    tell application "Finder"
        -- Get the absolute path of parent folder of your AppleScript file.
        set _path to parent of (path to me) as string
        -- Transform the path in a POSIX path
        set _path to POSIX path of _path
        -- Concatenate the folder path with the file name
        set _path to _path & fileName
        -- Return the POSIX path of plist file with name 'filename' that is inside the folder of AppleScript file
        return _path
    end tell
end getPath

Step 6

Finally, let's code the last function: the core function. It allows us to sign into iTunes, automatically, with any account registered in the plist file. The iTunesLogin(info) function has one parameter only: info represents an array which contains email and password of an Apple account.

To login to iTunes automatically, AppleScript language simulates the manual operations you would do to achieve the following:

  • Launch iTunes
  • Click on Store > Sign In…
  • Type your email
  • Type your password
  • Click on Sign In button

The function below does all steps above for you.

-- Function for iTunes sign in
on iTunesLogin(info)
    -- Launch iTunes
    tell application "iTunes" to activate
    tell application "System Events"
        tell process "iTunes"
            set frontmost to true
            -- Logout before executing a new login
            try
                click menu item loginBtn of menu "Store" of menu bar 1
            on error
                click menu item logoutBtn of menu "Store" of menu bar 1
                delay 2
                click menu item loginBtn of menu "Store" of menu bar 1
            end try
            delay 1
            -- Type account email
            keystroke item 1 of info
            keystroke tab
            delay 1
            -- Type account password
            keystroke item 2 of info
            -- Press the return key
            keystroke return
            delay 3
            keystroke return
        end tell
    end tell
end iTunesLogin

In this function, there are two global variables loginBtn and logoutBtn. They represent the buttons for signing into and signing out of iTunes. The button names are base on the system language; you have to set them correctly for the AppleScript to work.


4. AppleScript Main Code

Once you have finished coding all previous functions, you can write the main code of your AppleScript. Inside the AppleScript, place you cursor at the top of file.

Step 1

The first step to complete our tutorial is set some variables and do some checks.

-- Set the name of plist file which will contains all your Apple accounts
set fileName to "accounts.plist"

-- Get the absolute path of plist file using the 'getPath(fileName)' function
set filePath to getPath(fileName)

-- Define the iTunes login and logout buttons name based on your system language
property loginBtn : "Sign In…"
property logoutBtn : "Sign Out"

tell application "Finder"
    -- Check if the plist file already exists. If false let's create it with 'createAccountsFile(filePath)' function
    if not (exists filePath as POSIX file) then
        my createAccountsFile(filePath)
    end if
end tell

Step 2

The next step is to display a dialog box which asks the user what they want to do? Our AppleScript has following features:

  • Choose Account (for iTunes sign in)
  • Add a new Apple Account (to the plist file)
  • Reset Accounts (empty the plist file)
Actions Dialog
Actions Dialog

The code below implements the dialog.

-- Display the actions dialog box
set dialogResult to display dialog "Switch Apple Account" buttons {"Choose Account", "Add Account", "Reset  Accounts"} with hidden answer

Step 3

Now it's time to parse the user choice.

-- Parse the result
if dialogResult = {button returned:"Add Account"} then

    -- Click on 'Add Account' button

else if dialogResult = {button returned:"Choose Account"} then

    -- Click on 'Choose Account' button

else if dialogResult = {button returned:"Reset Accounts"} then

    -- Click on 'Reset Accounts' button

end if

If the user clicks on Add Account button the script ask to him to insert the credentials for a new Apple account. It will display three dialog boxes with input fields for account label, email and for the password. The code below implements this process.

-- Click on 'Add Account' button

-- Ask to insert the account label 
display dialog "Insert a label for the new Apple account" default answer ""
-- Save the field value in label variable
set label to (text returned of result)

-- Ask to insert the account email 
display dialog "Insert the email of Apple Account" default answer ""
-- Save the field value in email variable
set email to (text returned of result)

-- Ask to insert the account password 
display dialog "Insert the password of Apple Account" default answer "" with hidden answer
-- Save the field value in pass variable
set pass to (text returned of result)

-- Insert the new account inside the plist file using the 'addAccount(filePath, label, email, pass)' function
addAccount(filePath, label, email, pass)

-- Display a success messagge   
display dialog "The " & label & " account was registered successfully!" buttons {"Done"}

If a user clicks on the Choose Account button, the script displays a dialog with all of the registered accounts. When the user chooses an account, the script runs iTunes login. Let's implement the action.

-- Click on 'Choose Account' button

-- Get all accounts labels using the 'getLabels(filePath)' function
set labels to getLabels(filePath)

-- Check if the user has inserted at least one account 
if the (count of labels) is not 0 then

    -- Display all available accounts
    choose from list labels with title "Apple Accounts" with prompt "Login in iTunes with:" OK button name "Choose" cancel button name "Cancel"

    -- Save the choice
    copy the result as string to selectedAccount

    -- If user has not pressed the Cancel button go ahead 
    if not selectedAccount is equal to "false" then
        -- Get the account info about chosen account using 'getAccountInfo(filePath, selectedAccount)'
        set info to getAccountInfo(filePath, selectedAccount)
        -- Run the login
        iTunesLogin(info)
    end if

else
    display dialog "No accounts registered yet! Insert a new one!" buttons {"Done"}
end if

If the user clicks on the Reset Accounts button, the script overwrites the plist file with an empty one. The code below calls the createAccountsFile(filePath) function again to complete the process.

-- Click on 'Reset Accounts' button

try
    -- Ask user to confirm the action
    display dialog "Do you want to delete all inserted accounts?"

    --  If user does not cancel the action overwrite the plist file
    createAccountsFile(filePath)

    -- Display a success message
    display dialog "All accounts are deleted successfully" buttons {"Done"}
on error
    -- Do nothing
end try

5. Run the Script Inside iTunes

The last task required, in order to finish the tutorial, is installing your AppleScript into iTunes so you can easily access it anytime it is required.

Step 1

First, export the AppleScript. Inside the AppleScript Editor app click on File > Export… from the top menu.

Inside the export panel you have to:

  • export as "Access To iTunes"
  • choose as location your Desktop
  • choose Script as file format
  • and select the Run-only option

When you are ready click the Save button.

Export Script
Export Script

Step 2

Now move the exported script into iTunes. To do that, launch Finder app and choose Go > Go To Folder from the top menu.

Complete the panel input field with /Users/Your.System.User/Library/iTunes/ and click on the Go button.

Go To Folder
Go To Folder

Now move the the Access To iTunes file from the Desktop to the Script folder (if this folder does not already exist, you will need to create it first) to complete the process.

Move Script
Move Script

Step 3

Another important step to ensure your AppleScript works correctly is to enable access to assistive devices: open System Preferences app, choose the Accessibility icon and check Enable access to assistive devices. The image below show the panel with this option.

Accessibility
Accessibility

Step 4

Now you are able to trigger the AppleScript directly from iTunes.

Trigger Script
Trigger Script

Conclusion

Congratulations! You have completed the AppleScript. If you have followed all of the steps you will be able to use the AppleScript from within iTunes. In this tutorial you have learned how to code an AppleScript, to switch between your Apple accounts, without having to repeatedly type in different email addresses and passwords. You can easily adapt this AppleScript to work with Mac App Store, too. Simply modify the iTunesLogin function. I hope you enjoyed this tutorial, let me know how you get on with the scripts and any comments or questions that you have using the comments section, below.

Related Posts