dmkit 2 0 api

Upload: pavel-kiryukhin

Post on 31-May-2018

226 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/14/2019 DMKit 2 0 API

    1/55

    DotMac Kit 2.0 (Developer Preview)

    Abstract

    The purpose of the DotMac Kit and its contained classes is to give developers all of thetools required to tightly integrate the Internet-based services offered by Apple in its .Macproduct with their own. Additionally, .Mac developers have the opportunity to jointhe .Mac Affiliate Program and earn a commission for every new .Mac membership thatthey help generate.

    The basic usage pattern for the Kit is that a DMMemberAccount instance can be createdand used to perform .Mac-specific functions, such as checking which services areavailable to a given account, and can also be used in creating instances of individualsessions with .Mac services, such as the iDisk service or the store-and-forward messaging

    service. Each session is a specific object that encapsulates all state, network, and generaloverhead work required to interface efficiently with a given .Mac service.

    Version 2.0 of the DotMac Kit introduces APIs for Internet-based collaboration,workflow and security, enabling powerful networked features not available on any otherplatform.

    Class Diagram

  • 8/14/2019 DMKit 2 0 API

    2/55

    2

    Description

    At the highest level, the DotMac Kit enables you to perform data transfer, distributedmessaging and related user account transactions with the .Mac Internet Servicesenvironment, all without having to worry about the underlying transport protocols,security, or servers. The framework enables data I/O via iDisk and an interfaceinto .Macs store-and-forward messaging service, along with mechanisms for dealingwith specific attributes of a members .Mac account. Used by Apples own iAppsand .Macs application servers, the Kit is open standards-based and is the easiest way tointegrate with .Mac.

    Many applications can benefit from the DotMac Kit. Document-centric applications, forinstance, can use the Kits workflow and collaboration features for sharing documents,and can use iDisk for data backup or secure distribution. Multi-player or turn-basedgames can use the Kit to communicate events across computers or to save game state toan iDisk. Any application that requires reliable notifications or inter-applicationcommunication, be it for distributed solutions or anything involving resource tracking or

    reservation, can benefit.

    And its free. At no cost to your application, the DotMac Kit gives you access tothe .Mac infrastructure and to well over half a million paying members. .Macs scalableservices, systems support and 24/7 monitoring make adding Internet-based features toyour application headache-free. Plus, you earn $15 for every member you sign up (seethe included Affiliate Program document for more information).

    The rest of this document covers the DotMac Kit 2.0 APIs in detail. Read on to learnhow easy it is to include powerful Internet-based features in your app.

  • 8/14/2019 DMKit 2 0 API

    3/55

    3

    Table of Contents

    ...........................................................................................Constants 4

    ...........................................................................Using Transactions 8

    ........................................................................................................................DMTransaction 8

    ......................................................................DMTransactionDelegate (Informal Protocol) 12

    ......................................................................DMTransactionGenerator (Formal Protocol) 13

    .........................................Credentials and Account Management 14

    ..........................................................................................DMCredential (Formal Protocol) 15

    ..............................................................................................................DMMemberAccount 15

    .................................................................................................................DMSecondaryUser 20

    ................................................................................................................................DMGroup 21

    ............................................................................................DMPrincipal (Formal Protocol) 22

    ..........................................................Security and Access Control 23

    .............................................................................................DMSecurity (Formal Protocol) 23

    .............................................................................................................................DMUtilities 25

    ...........................................................Transferring Data with iDisk 26

    ....................................................................................................................DMiDiskSession 27

    .........................................................DMiDiskFileManager (Category of DMiDiskSession) 35

    ...............................................................................Using DMSecurity on DMiDiskSession 37

    ..........................................Using Store-and-forward Messaging 38

    ...........................................................................................................DMMessagePublisher 39

    .........................................................................................................DMMessageSubscriber 43

    .....................................................................DMSubscriptionDelegate (Informal Protocol) 48

    .................................................................................................................................DMTopic 49

    ...........................................................................................................................DMMessage 52

  • 8/14/2019 DMKit 2 0 API

    4/55

    4

    Constants

    The NSString key constants below are used to access quota property values contained inthe NSDictionary created by DMiDiskSessions -quotaAttributes method (theNSDictionary is retrieved using DMTransactions result method):

    Key Constant Corresponding Value Type

    kDMiDiskQuotaInBytes NSNumber (bytes)

    kDMiDiskSpaceUsedInBytes NSNumber (bytes)

    DMMemberAccounts -servicesAvailableForAccount method creates an NSArray ofNSString values (retrieved using DMTransactions result method), each of which willequal one of these NSString constants:

    Service Constant Meaning

    kDMiDiskService The account has iDisk storage associated

    with it.kDMEmailService The account has an email address along with

    the associated email storage.

    kDMWebHostingService The account has web hosting capabilitiesthrough its iDisks Sites folder.

    kDMiSyncService The account has access to .Macs iSync-related functionality.

    Status Constants: The -validateCredentials and -errorType methods (fromDMMemberAccount and DMTransaction respectively) may return the following integer

    status codes (or kDMUndefined) as appropriate:Status Constant Meaning

    kDMSuccess The operation was successful.

    kDMNetworkError Unable to interact with .Mac because of anetworking error or lack of networkavailability.

    kDMInvalidCredentials The .Mac credentials set for this object donot have access to a .Mac account.

    kDMInsufficientStorage The .Mac account does not have sufficientdisk space to accommodate the given

    operation.kDMResourceNotFound A required resource was not found.

    kDMResourceExists Indicates an error due to the pre-existence of a given resource.

    kDMServiceBusy The given .Mac service was too busy toperform the requested operation and theoperation should be retried later.

    kDMInvalidParameter A user-provided parameter was invalid.

  • 8/14/2019 DMKit 2 0 API

    5/55

    5

    kDMUnknownError Unable to complete operation because of anunknown error.

    Certain methods in this framework return an Undefined value when appropriate and asnoted in the method descriptions of this document.

    Status Constant MeaningkDMUndefined Used by individual methods as noted in this

    documents method descriptions.

    DMiDiskSessions -basicAttributesAtPath: method creates an NSDictionary (retrievedusing DMTransactions result method) which contains resource attributes whose valuescan be accessed using the following NSString key constants:

    Key Constant Corresponding Value Type

    kDMContentLength NSNumber (bytes)

    kDMLastModified NSDate

    DMiDiskSessions -extendedAttributesAtPath: method creates an NSDictionary(retrieved using DMTransactions -result method) which contains resource attributeswhose values can be accessed using the following NSString key constants:

    Key Constant Corresponding Value Type

    kDMContentLength NSNumber (bytes)

    kDMLastModified NSDate

    kDMURI NSString

    kDMContentType NSString

    kDMIsCollection NSNumber (Boolean)

    kDMIsLocked NSNumber (Boolean)

    kDMLockOwner NSString

    kDMLockToken NSString

    kDMLockTimeout NSNumber (seconds)

  • 8/14/2019 DMKit 2 0 API

    6/55

    6

    DMTransactions -transactionState method returns one of the following integer statuscodes:

    Transaction State Constant Meaning

    kDMTransactionNotStarted The transaction has not yet started.

    kDMTransactionActive The transaction is in progress.

    kDMTransactionSuccessful The transaction completed successfully andwithout error.

    kDMTransactionAborted DMTransactions abort method was called,halting the given transaction.

    kDMTransactionHadError A non-success http status code was returned,a network error occurred, or the expecteddata was not received. To get the exact errorthat occurred, call DMTransactionshttpStatusCode or errorType methods.

    Privilege constants used for setting privileges when setting access rights onsecurable .Mac entities using DMSecurity methods (privileges are inherited unlessexplicitly overridden):

    Privilege Constant Meaning

    kDMRead Includes read and list access to a givenentity.

    kDMWrite Includes create, modify and deleteaccess to a given entity.

    kDMModify Includes modify access to a given entity.Does not include create or delete access.

    kDMReadChildren Includes read and list access to childrenof a given entity only. Does not includeread and list access to the entity itself.

    The following constants are used by the DMUtilities method,-principalPropertiesFromPrincipalID:, to to parse a principal ID string returned by aDMPrincipal method:

    Key Constant Corresponding Value

    kDMPrincipalName (NSString) The name of the given principal.

    kDMPrincipalOwner (NSString) The name of the .Mac memberwho owns the principal--this is the same asthe principal name if the principal representsa DMMemberAccount.

    kDMPrincipalType (NSString) The type of the given principal,which is one of the Principal TypeConstants listed below.

  • 8/14/2019 DMKit 2 0 API

    7/55

  • 8/14/2019 DMKit 2 0 API

    8/55

    8

    Using Transactions

    At the heart of the DotMac Kit is the DMTransaction class, which peforms all networkoperations with .Mac. All methods in the Kit that return DMTransaction objects conformto the DMTransactionGenerator protocol, a protocol that provides control over whethertransactions are done asynchronously or synchronously (the default is always async) andthat provides a mechanism for setting a transaction delegate object that conforms to theinformal DMTransactionDelegate protocol.

    DMTransaction

    Tracking transactions

    - (NSString *)transactionID;

    Returns a globally unique identifier string for this transaction.

    - (void) setContext: (id)context;

    Sets an object of the callers choosing on the given transaction that can be used to helpidentify a transaction. This method is especially useful in tracking transactions doneasynchronously. After obtaining an asynchronously-fired DMTransaction object, thecaller need not worry about the transaction completing and generating a delegate callback

  • 8/14/2019 DMKit 2 0 API

    9/55

    9

    before the context can be set--since callbacks are made on the same client thread whichlaunched the transaction, setting the context simply needs to be done immediately aftergenerating the transaction and in the same thread. That way, even if the transactioncompletes immediately, the context will still be set before the completion callback ismade.

    - (id)context;

    Returns the context object set for this transaction. This value is nil by default.

    - (NSString *)uri;

    Returns the target uri sent in this transactions originating request.

    Getting transaction status

    - (BOOL)isSuccessful;Returns YES if the transaction has finished successfully, no network errors occurred, and

    a valid http status code was returned. Otherwise, returns NO.

    - (BOOL)isFinished;

    This method will return YES if the given transaction is no longer active, due to success,

    error or cancellation. Otherwise, NO is returned.

    - (int)transactionState;

    Returns one of the following integer constants:Transaction State Constant Meaning

    kDMTransactionNotStarted The transaction has not yet started.

    kDMTransactionActive The transaction is in progress.

    kDMTransactionSuccessful The transaction completed successfully andwithout error.

    kDMTransactionAborted DMTransactions abort method was called,halting the given transaction.

    kDMTransactionHadError A non-success http status code was returned,

    a network error occurred, or the expecteddata was not received. To get the exact errorthat occurred, call DMTransactionshttpStatusCode or errorType methods.

  • 8/14/2019 DMKit 2 0 API

    10/55

    10

    - (int)httpStatusCode;

    Returns the HTTP status code for the request if applicable. Check RFC 2616 (HTTP/1.1)for a complete list of all of the applicable status codes. Some of the most noteworthyones are:

    200 Success 304 Not Modified 401 Authorization required

    403 Forbidden. Your authorization credentials will not allow the transactionattempted.

    404 Not Found

    [Note: kDMUndefined will be returned if the transaction has not yet completed, if an httpstatus code is not applicable for the given transaction type, or if the transaction failedbefore an HTTP status code could even be received, as might be the case if the clientcomputer could not contact the .Mac environment for some reason.]

    - (int)errorType;

    If an error occurred while generating the response associated with this object, this methodwill return a specific error type, as defined in the Constants section of this document.If an unknown error occurred, kDMUnknownError is returned. However, if no erroroccurred or the response has not yet completed when this method is called,kDMUndefined will be returned. [Note: If the http status code that was received isconsidered a failure code for the given transaction, kDMUnknownError is returned thehttp status code can be retrieved using the httpStatusCode method of this class.]

    - (id)result;

    Returns the result object of the given transaction as defined by the type of request thetransaction is handling, if currently available and applicable. Otherwise returns nil.

    - (SInt64)contentLength;

    Returns the length in bytes of the content being downloaded or uploaded. This returnedlength does not change over the life of the given transaction, except in the case where thismethod is called immediately after a GET request is started, before the content length hasbeen received from the serverthis method returns kDMUndefined if called too early.

    - (SInt64)bytesTransferred;

    Most useful for asynchronous operations, this method returns the number of bytesdownloaded or uploaded thus far.

  • 8/14/2019 DMKit 2 0 API

    11/55

    11

    Cancelling an in-flight transaction

    - (void)abort;

    Stops the current transaction if it is running asynchronously, halting its progress. If thetransaction is already complete (or resulted in an error) this method has no effect.

  • 8/14/2019 DMKit 2 0 API

    12/55

  • 8/14/2019 DMKit 2 0 API

    13/55

    13

    DMTransactionGenerator (Formal Protocol)

    - (void)setTransactionDelegate: (id)delegate;

    This method is used to set the delegate object which will receive status messages fromasynchronous transactions generated by the object that conforms to this protocol. Theobject passed in this method's delegate parameter must conform to the informalDMTransactionDelegate protocol. Transaction delegates receive their messages on therun loop originally used to create the given DMTransaction. It is safe to call this methodto change the delegate as needed--since an in-flight DMTransaction object uses thesettings that were in place at the time it was created, calling this method will not affectany transaction already in progress. A transaction delegate object does not receivecallbacks for transactions executed synchronously.

    - (id)transactionDelegate;

    This method is used to get the currently set delegate object that receives status messagesfrom asynchronous transactions generated by the object that conforms to this protocol.

    - (void)setIsSynchronous: (BOOL)useSynchronous;

    This method is used to set the synchronicity state for generated transactions. PassingYES for useSynchronous will cause the object's transaction methods to block until theyhave either completed their transaction or failed with an error. Passing NO will cause themethods to that return a DMTransaction object to return immediately, using anypreviously set delegate object to signal completion or error. It is safe to call this methodto switch between asynchronous and synchronous modes as needed--since an in-flightDMTransaction object uses the settings that were in place at the time it was created,calling this method will not affect any transaction already in progress. [Note: The defaultmode is asynchronous.]

    - (BOOL)isSynchronous;

    This method returns the synchronicity state used for newly generated transactions. YESis returned for synchronous or NO for asynchronous. [Note: The default mode isasynchronous.]

  • 8/14/2019 DMKit 2 0 API

    14/55

    14

    Credentials and Account Management

    Objects conforming to the DMCredential protocol, such as DMMemberAccount andDMSecondaryUser are used to provide credentials for .Mac session classes, such asDMiDiskSession, DMMessagePublisher and DMMessageSubscriber. Besides providingcredentials, the DMMemberAccount class offers a mechanism for obtaining account

    status such as which .Mac services are available and how many days the account has leftbefore expiration. It also provides methods for creating member-owned secondary usersand groups. (Well describe later how .Mac resources can be shared by using the Kitsaccess control features to grant access to other .Mac members, secondary users orgroups.)

  • 8/14/2019 DMKit 2 0 API

    15/55

    15

    DMCredential (Formal Protocol)

    - (NSString *)name;

    A username string is returned.

    - (NSString *)password;

    A password string is returned.

    - (NSString *)owner;

    The name of the .Mac member who owns the credential is returned.

    DMMemberAccount(Conforms to DMCredential, DMPrincipal, DMTransactionGenerator)

    Factories and Initers

    + accountWithName: (NSString *)name

    password: (NSString *)password

    applicationID: (NSString *)creatorCode;

    Returns an initialized, auto-released instance of DMMemberAccount keyed to a specificapplications identification string. The instance returned will use the provided name andpassword, rather than any credentials stored in the .Mac preferences on the system.(To have the credentials stored on the system pre-applied, use theaccountFromPreferencesWithApplicationID: method instead.) Pass the unique 4-character application identifier obtained fromhttp://developer.apple.com/datatype/creatorcode.html.

    + accountFromPreferencesWithApplicationID: (NSString *)creatorCode;Returns an initialized, auto-released instance of DMMemberAccount keyed to a specificapplications identification string. The instance returned will have the .Mac name andpassword from the system pre-applied. Pass the unique 4-character application identifierobtained from http://developer.apple.com/datatype/creatorcode.html.

    - initWithName: (NSString *)name

    password: (NSString *)passwordapplicationID: (NSString *)theID;

    Returns an initialized instance of DMMemberAccount keyed to a specific applicationsidentification string. The instance returned will use the provided name and password,rather than any credentials stored in the .Mac preferences on the system. (To have thecredentials stored on the system pre-applied, use theinitFromPreferencesWithApplicationID: method instead.) Pass the unique applicationidentifying string obtained fromhttp://developer.apple.com/datatype/creatorcode.html

  • 8/14/2019 DMKit 2 0 API

    16/55

    16

    - initFromPreferencesWithApplicationID: (NSString *)theID;

    Returns an initialized instance of DMMemberAccount keyed to a specific applicationsidentification string. The instance returned will have the .Mac name and password fromthe system pre-applied. Pass the unique application identifying string obtained fromhttp://developer.apple.com/datatype/creatorcode.html

    Convenience API (Inherited from DMAccount)

    - (NSString *)applicationID;

    The application ID currently set for this DMMemberAccount object is returned.

    - (void)setApplicationName: (NSString *)name;

    This method sets the human-readable name of the calling application. Once set, it will beincluded in the user-agent header sent with all http requests.

    - (NSString *)applicationName;

    The human-readable name of the calling application is returned if set.

    Checking account credentials

    - (int)validateCredentials;

    Use this method to check that the given account contains valid .Mac credentials. Thereturned integer will correspond to one of the Status Constants defined in the Constantssection of this document.

    - (BOOL)matchesSystemCredentials;

    Returns true if the name and password currently set for this DMMemberAccount objectmatch the .Mac credentials stored on the system.

    Requesting account properties

    - (DMTransaction *)servicesAvailableForAccount;

    The returned DMTransaction objects result method returns an NSArray of NSStringentries corresponding to available services for the .Mac account represented by this

    DMMemberAccount instance. If a given .Mac service is enabled for this account, thenthe array will contain a string equal to one of these NSString constants:

    Service Constant Meaning

    kDMiDiskService The account has iDisk storage associatedwith it.

    kDMEmailService The account has an email address along withthe associated email storage.

  • 8/14/2019 DMKit 2 0 API

    17/55

    17

    kDMWebHostingService The account has web hosting capabilitiesthrough its iDisks Sites folder.

    kDMiSyncService The account has access to .Macs iSync-related functionality.

    [Note: If the account credentials do not exist or some other error occurs, the returnedDMTransactions errorType method can be used to identify the error.]

    - (DMTransaction *)daysLeftUntilExpiration;

    The returned DMTransaction objects result method returns an NSNumber representingthe number of full days left until the given account expires.[Note: If the account credentials do not exist or some other error occurs, the returnedDMTransactions errorType method can be used to identify the error.]

    - (DMTransaction *)canUpgradeAccount;

    The returned DMTransaction objects result method returns an NSNumber, whose

    Boolean value can be retrieved using NSNumbers boolValue method. This value will beYES if the DMMemberAccount objects credentials are associated with an existing

    account that can be upgraded, such as a trial or email-only account, or if the account has

    expired and needs to be renewed. Otherwise, the resulting value will be NO.[Note: If the account credentials do not exist or some other error occurs, the returnedDMTransactions errorType method can be used to identify the error.]

    Upgrading or signing up a .Mac member

    - (void)upgradeAccount;This method will launch the users default web browser and open the appropriate .Macmembership upgrade page, which is localized based on system preferences.

    - (NSURL *)accountUpgradeURL;

    This method provides access to the same localized URL that the upgradeAccount methodloads in the default browser.

    + (void)signUpNewMember;

    This method will launch the users default web browser and open the .Mac new membersign-up page, which is localized based on system preferences. This method can be usedwhen the user of the given application is not yet a .Mac member and cannot fully enjoythe applications features without a .Mac account.

  • 8/14/2019 DMKit 2 0 API

    18/55

    18

    + (void)signUpNewMemberWithApplicationID: (NSString *)appID;

    This method performs the same function as the +signUpNewMembermethod, andadditionally ensures that the owner of the provided application ID (if a member of

    the .Mac Affiliate Program) earns a commission whenever a user of their applicationbecomes a paying .Mac member. For more information on the .Mac Affiliate Program,please visit http://www.mac.com/1/affiliates/faq.html.

    + (NSURL *)signUpURL;

    This method provides access to the same localized URL that the signUpNewMembermethod loads in the default browser. [Note: The URL returned by this method should notbe hard-coded within an application, as it may change in the future.]

    + (NSURL *)signUpURLWithApplicationID: (NSString *)appID;

    Returns the URL for the .Mac sign-up page, with commission tracking enabled if the

    owner of the provided application ID is a member of the .Mac Affiliate Program. Formore information on the .Mac Affiliate Program, please visit http://www.mac.com/1/affiliates/faq.html.[Note: The URL returned by this method should not be hard-coded within an application,as it may change in the future.]

    Managing secondary accounts

    - (DMTransaction *)secondaryUserNames;

    Lists all secondary users owned by this .Mac member. Returns a DMTransaction objectwhose -isSuccessful method can be used to test for success and whose -result methodreturns an NSArray of NSStrings on success.

    - (DMTransaction *)createSecondaryUserWithName: (NSString *)name andPassword: (NSString *)password;Adds a secondary user to .Mac if a secondary user of the same name does not alreadyexist for this owning member account. Returns a DMTransaction object whose-isSuccessful method can be used to test for success.

    - (DMTransaction *)removeSecondaryUserNamed: (NSString *)name;Removes the secondary user with the given name from .Mac. Returns a DMTransactionobject whose -isSuccessful method can be used to test for success.

    - (DMTransaction *)resetPassword: (NSString *)password forSecondaryUserNamed: (NSString *)name;Resets the password of the secondary user with the given name. Returns aDMTransaction object whose -isSuccessful method can be used to test for success.

  • 8/14/2019 DMKit 2 0 API

    19/55

    19

    Managing groups

    - (DMTransaction *)groupNames;

    Lists all groups owned by this .Mac member. Returns a DMTransaction object whose-isSuccessful method can be used to test for success and whose -result method returns anNSArray of NSString group names upon success.

    - (DMGroup *)groupNamed: (NSString *)name;Use this method to obtain a DMGroup object representing a known group that alreadyexists.

    - (DMTransaction *)createGroupWithName: (NSString *)name andMembers: (NSArray *)members;This method can be used to create a new DMGroup object with the provided name andmembers if a group of the same name does not already exist for the owners accounton .Mac. The members argument is an NSArray of principal ID strings identifyingprincipals corresponding to DMMemberAccounts, DMSecondaryUsers and/or DMGroupobjects. Returns a DMTransaction object whose -isSuccessful method can be used totest for success.

    - (DMTransaction *)removeGroupNamed: (NSString *)name;

    Removes the DMGroup with the given name from .Mac. Returns a DMTransactionobject whose -isSuccessful method can be used to test for success.

  • 8/14/2019 DMKit 2 0 API

    20/55

    20

    DMSecondaryUser(Conforms to DMCredential, DMPrincipal, DMTransactionGenerator)

    Factories and Initers

    + (DMSecondaryUser *)secondaryUserWithName: (NSString *)name password: (NSString *)password owner: (NSString *)memberName applicationID: (NSString *)creatorCode;Returns an autoreleased instance of DMSecondaryUser keyed to a specific applicationsidentification string. The secondary user is owned by the .Mac member with the givenmember name. Pass the unique 4-character application identifier obtained fromhttp://developer.apple.com/datatype/creatorcode.html.

    - (DMSecondaryUser *)initWithName: (NSString *)name password: (NSString *)password owner: (NSString *)memberName applicationID: (NSString *)creatorCode;

    Returns a newly initialized DMSecondaryUser object keyed to a specific applicationsidentification string. The secondary user is owned by the .Mac member with the givenmember name. Pass the unique 4-character application identifier obtained fromhttp://developer.apple.com/datatype/creatorcode.html.

  • 8/14/2019 DMKit 2 0 API

    21/55

    21

    DMGroup(Conforms to DMPrincipal, DMTransactionGenerator)

    A DMGroup is owned by a .Mac member and can only be created using aDMMemberAccount object.

    Convenience API

    - (NSString *)name;

    Returns the name of the .Mac member-owned group represented by this DMGroupobject.

    - (NSString *)owner;Returns the name of the .Mac member who owns this group.

    Managing group members

    - (DMTransaction *)addMembers: (NSArray *)members;Adds members to the given .Mac member-owned group. If the group already exists, thenthe identified principals are added as members. If the group does not already exist, thiscall fails. The members argument is an NSArray of principal ID strings that identifyprincipals corresponding to DMMemberAccounts, DMSecondaryUsers and/or otherDMGroup objects. Returns a DMTransaction object whose -isSuccessful method can beused to test for success.

    - (DMTransaction *)removeMembers: (NSArray *)members;

    Removes members from the given .Mac member-owned group. The members argumentis an NSArray of principal ID strings that identify principals corresponding toDMMemberAccounts, DMSecondaryUsers and/or other DMGroup objects. Returns aDMTransaction object whose -isSuccessful method can be used to test for success.

    - (DMTransaction *)members;

    Lists all members of the given .Mac member-owned group. Returns a DMTransactionobject whose -isSuccessful method can be used to test for success and whose -resultmethod, upon success, returns an NSArray of principal ID strings that identify principalscorresponding to DMMemberAccounts, DMSecondaryUsers and/or other DMGroup

    objects.

  • 8/14/2019 DMKit 2 0 API

    22/55

    22

    DMPrincipal (Formal Protocol)

    The DMPrincipal protocol is implemented by DMMemberAccount, DMSecondaryUserand DMGroup. [Note: When calling +principalIDWithName:andOwner: for aDMMemberAccount, the name and owner strings are the same.]

    + (NSString *)principalIDWithName: (NSString *)name andOwner: (NSString *)memberName;Returns a principal ID string identifying the principal with the given nameand owner (the owner is the name of the .Mac member that owns the given principal).This class method is useful when the caller needs to obtain a principle ID representing aDMMemberAccount, DMSecondaryUser or DMGroup without creating an instance ofone of those classes.

    - (NSString *)principalID;

    This method is implemented by DMMemberAccount, DMSecondaryUser or DMGroup

    and returns the appropriate principal ID string.

  • 8/14/2019 DMKit 2 0 API

    23/55

    23

    Security and Access Control

    The DMSecurity protocol is implemented by DMiDiskSession, DMMessagePublisherand DMMessageSubscriber and allows the owner of a .Mac resource to apply ACLs tothat resource. (Examples of how to use the DMSecurity methods for each of thesethree .Mac session classes can be found within each of their respective API sections inthis document.) This section describes the DMSecurity protocol in detail, along with theDMUtilities class, which provides assistance in parsing principal ID strings returned byDMSecurity methods.

    DMSecurity (Formal Protocol)

    The DMSecurity protocol is used to get and set access privileges for securable entities(such as DMTopics and NSStrings paths representing iDisk resources). Access is grantedto principals corresponding to DMMemberAccounts, DMSecondaryUsers andDMGroups. [Principals are represented by principal IDs, which can be obtained bycalling the +principalIDWithName:andOwner method on a DMMemberAccount,DMSecondaryUser or DMGroup object. If you already have an instance of one of theseobjects you can call its principalID instance method instead.]

    Reading access privileges

    - (DMTransaction *)accessToEntity: (id)entity forPrincipal: (NSString *)principalID;Retrieves access privileges set on the specified entity for a given principal. Takes anentity (valid entities include DMTopics and NSString paths representing iDisk resources)and also takes a principal ID string that corresponds to a DMMemberAccount,DMSecondaryUser or DMGroup. Returns a DMTransaction object whose -isSuccessfulmethod can be used to test for success and whose -result method, upon success, returnsan NSArray of privilege strings. (Valid privilege strings are defined in the Constants

  • 8/14/2019 DMKit 2 0 API

    24/55

    24

    section of this document and include kDMRead, kDMWrite, kDMModify andkDMReadChildren.)

    - (DMTransaction *)accessToEntity: (id)entity forPrincipals: (NSArray *)principalIDs;Retrieves access privileges set on the specified entity for a list of principals (valid entities

    include DMTopics and NSString paths representing iDisk resources). Returns aDMTransaction object whose -isSuccessful method can be used to test for success andwhose -result method, upon success, returns an NSDictionary, where each key in thedictionary is a principal ID string corresponding to an NSArray value that contains a setof privilege strings for the given principal. (Valid privilege strings are defined in theConstants section of this document and include kDMRead, kDMWrite, kDMModifyand kDMReadChildren.)

    Setting access privileges

    - (DMTransaction *)setAccess: (NSArray *)access toEntity: (id)entity forPrincipals: (NSArray *)principals;Sets access privileges on the specified entity for the identified principal(s). The accessargument is an NSArray of privilege strings. (Valid privilege strings are defined in theConstants section of this document and include kDMRead, kDMWrite, kDMModifyand kDMReadChildren.) Any privilege not included in the access array will be denied.When the specified entity has children (such as a directory on iDisk) any direct or indirectchild will inherit the given privileges unless different access is explicitly set on that child.

    If the access privileges array is nil, this method will remove all access for the given

    principals. The entity argument is either a DMTopic object or an NSString pathrepresenting an iDisk resource. The principals argument is an NSArray of principal IDstrings that identify the unique principals corresponding to DMMemberAccounts,DMSecondaryUsers and/or DMGroups. Returns a DMTransaction object whose -isSuccessful method can be used to test for success.

    Resetting access to an entitys children

    - (DMTransaction *)resetAccessToChildrenOfEntity: (id)entity;

    This method removes access privileges explicitly set on the children of the specified

    entity. Returns a DMTransaction object whose -isSuccessful method can be used to testfor success.

  • 8/14/2019 DMKit 2 0 API

    25/55

    25

    DMUtilities

    - (NSDictionary *)principalPropertiesFromPrincipalID: (NSString *)principalID;This utility method is used to parse a principal ID string returned by a DMPrincipalmethod. This method returns a dictionary with values for the following keys:

    kDMPrincipalName, kDMPrincipalOwner and kDMPrincipalType. ThekDMPrincipalOwner key corresponds to the name of the .Mac member who owns thegiven principal (this is the same as the principal name if the principal represents aDMMemberAccount) and the kDMPrincipalType key corresponds to one of thefollowing: kDMMemberAccount, kDMSecondaryUser or kDMGroup. (These constantsare defined in the Constants section of this document.)

  • 8/14/2019 DMKit 2 0 API

    26/55

    26

    Transferring Data with iDisk

    At the core of the DotMac Kit is an implementation of an open standards-basedWebDAV client (RFC #2518). This allows DMiDiskSession objects to directly interactwith the .Mac iDisk service, which is also based on WebDAV.

    Built on top of the DMiDiskSession class, which includes everything a user of thisframework needs to manipulate data on an iDisk, is a convenience category calledDMiDiskFileManager, which has an API and functionality representing a subset of that ofNSFileManager. DMiDiskFileManager is a wrapper around DMiDiskSessionsWebDAV-based calls, and facilitates synchronous iDisk access through an API which willbe familiar to many developers. However, direct use of DMiDiskSession is therecommended mode of communication with the iDisk, since it is more efficient, allowsasynchronous calls, and will be the class which gets updated in future framework releasesas enhanced WebDAV-based functionality is added. [Note: DMiDiskSession objects arein asynchronous mode by default.]

    Supported iDisk operations include:

    Asynchronous and Synchronous Data Retrieval: GET Downloads the entire specified object. GET If Modified Since Downloads the entire specified object, but only if it has a modification date more recent than the date supplied. GET Range Downloads only the specified range of an object. GET Range If Modified Since Downloads the specified range of an object if it has a modification date more recent than the date supplied.Asynchronous and Synchronous Data Upload: PUT Uploads the entire specified object.

    PUT Range Uploads the supplied data replacing the specified range within an existing object.Asynchronous and Synchronous File Maintenance & General: LOCK Locks a specified object on the iDisk server so that only this client can write to the object. RELOCK Renews a previously acquired lock. UNLOCK Releases a previously acquired lock. PROPFIND (Collection) Returns the contents of the given collection (directory). PROPFIND (File) Returns the properties of a specific file. MKCOL Creates a directory at the specified location on the iDisk server.

    MOVE Moves a file or directory to a specified location on the iDisk server. COPY Creates a copy of a file or directory at a specified location on the iDisk server. DELETE Deletes a file or directory at the specified location on the iDisk server. [Note: Unlike file system delete operations, iDisk delete operations will successfully delete directories that contain files.]

  • 8/14/2019 DMKit 2 0 API

    27/55

    27

    DMiDiskSession(Conforms to DMSecurity, DMTransactionGenerator)

    DMiDiskSession is a thread-safe class which facilitates interactions with iDisk.

    Please note: All server-side paths passed as arguments to DMiDiskSession methods

    should start with a forward slash, omitting the iDisk account name at the beginning ofthe pathfor example, if uploading a local file to a users Public folder, the secondpath passed to the putLocalFileAtPath:toPath: method would be of the format /Public/.

    Factories and initers

    + iDiskSessionWithCredentials: (id )credentials;This method returns an auto-released iDisk session instance that can be used to performI/O transactions with the .Mac iDisk servers. It takes an object that conforms to theDMCredential protocol--the returned session will be used to access the iDisk owned bythe .Mac member with the given credentials.

  • 8/14/2019 DMKit 2 0 API

    28/55

    28

    + iDiskSessionWithCredentials: (id )credentials andOwner: (NSString *)memberName;This method returns an auto-released iDisk session instance that can be used to performI/O transactions with the .Mac iDisk servers. It takes an object that conforms to theDMCredential protocol and also takes the name of the .Mac member whose iDisk is to beaccessed using the provided credentials.

    - initWithCredentials: (id )credentials;

    This method will return an iDisk session instance that can be used to perform I/Otransactions with the .Mac iDisk servers. It takes an object that conforms to theDMCredential protocol--the returned session will be used to access the iDisk owned bythe .Mac member with the given credentials.

    - initWithCredentials: (id )credentials andOwner: (NSString *)memberName;This method returns an auto-released iDisk session instance that can be used to perform

    I/O transactions with the .Mac iDisk servers. It takes an object that conforms to theDMCredential protocol and also takes the name of the .Mac member whose iDisk is to beaccessed using the provided credentials.

    Convenience API

    - (id )credentials;

    Returns the DMCredential-conforming object containing the credentials used to accessthis sessions iDisk.

    - (NSString *)owner;

    Returns the name of the .Mac member who owns the iDisk being accessed by thissession.

    Getting the storage quota

    - (DMTransaction *)quotaAttributes;

    Use this method to get the users iDisk quota value along with the amount of storagespace that is currently used. The returned DMTransaction objects result method returns

    an NSDictionary containing two NSNumber values, which can be retrieved using thefollowing key constants:

    Key Constant Corresponding Value Type

    kDMiDiskQuotaInBytes NSNumber (bytes)

    kDMiDiskSpaceUsedInBytes NSNumber (bytes)

  • 8/14/2019 DMKit 2 0 API

    29/55

  • 8/14/2019 DMKit 2 0 API

    30/55

    30

    Uploading data

    - (DMTransaction *)putData: (NSData *)data

    toPath: (NSString *)destinationPath;

    This method places the contents of the data argument into the resource at the locationspecified by the destination path. [Note: Call will fail if any sublevels of destinationPath(excluding the object itself) do not exist, and the call may return nil if an invalid data

    argument is passed.]Returns a DMTransaction object that can be used to get the result of the transaction,status, payload, and many other pieces of information about the actual transaction.

    - (DMTransaction *)putData: (NSData *)data

    toPath: (NSString *)destinationPath

    withByteRange: (NSRange)byteRange;

    This method places the contents of the data argument into the resource at the locationspecified by the byteRange argument. The NSRange object, passed as the byteRangeargument, should have its location set as the index of the first byte to be written to and itslength should be set as the total number of bytes, including the first byte. If the end of thespecified range is beyond the end of the file, then the length of the resource is extended toaccommodate all of the bytes. [Note: Call will fail if any sublevels of destinationPath(excluding the object itself) do not exist, and the call may return nil if an invalid data

    argument is passed.]Returns a DMTransaction object that can be used to get the result of the transaction,status, payload, and many other pieces of information about the actual transaction.- (DMTransaction *)putLocalFileAtPath: (NSString *)localPath

    toPath: (NSString *)destinationPath;

    This method places the contents of a local file into a new server-side file at the givendestination path. If the localPath parameter refers to a symlink, the symlink will not bepreservedrather, the resource it references will be uploaded. [Note: Call will fail if allsublevels of destinationPath (excluding the object itself) do not already exist, and the callmay return nil if an invalid localPath argument is passed.]

    Returns a DMTransaction object that can be used to get the result of the transaction,status, payload, and many other pieces of information about the actualtransaction.

    Creating collections (directories)

    - (DMTransaction *)makeCollectionAtPath: (NSString *)thePath;

    This method creates a collection (directory) at the location specified in thePath. If any ofthe levels above the one being created does not exist, then the create will fail.Returns a DMTransaction object that can be used to get the result of the transaction,status, payload, and many other pieces of information about the actual transaction.

  • 8/14/2019 DMKit 2 0 API

    31/55

    31

    Moving and Copying resources

    - (DMTransaction *)moveResourceAtPath: (NSString *)sourcePath

    toPath: (NSString *)destinationPath;

    Moves the resource identified by sourcePath if it is not locked by another client and theaccount who owns the credentials used has write access to destinationPath. This methodwill overwrite the resource at destinationPath if that resource is not locked by anotherclient.Returns a DMTransaction object that can be used to get the result of the transaction,status, payload, and many other pieces of information about the actual transaction.

    - (DMTransaction *)copyResourceAtPath: (NSString *)sourcePath

    toPath: (NSString *)destinationPath;

    Copies the resource identified by sourcePath if the account who owns the credentials usedhas write access to destinationPath. This method will overwrite the resource atdestinationPath if that resource is not locked by another client.Returns a DMTransaction object that can be used to get the result of the transaction,status, payload, and many other pieces of information about the actual transaction.

    Deleting resources

    - (DMTransaction *)deleteResourceAtPath: (NSString *)thePath;

    Deletes the resource referenced by thePath if it is not locked by another client and theaccount who owns the credentials used has write access to thePath. If the delete requestfails because the specified resource or its parent is locked, the returned DMTransactionobjects result method will return an NSArray of NSStrings representing the exact uriswhich are currently locked.[Note: Unlike on most file systems, a non-empty collection (directory) can be deleted.Issuing a delete targeted at a collection will delete the collection and all of it contentswithout warning (assuming you have the correct access privileges).]Returns a DMTransaction object that can be used to get the result of the transaction,status, payload, and many other pieces of information about the actual transaction.

    Locking resources

    - (DMTransaction *)lockResourceAtPath: (NSString *)thePath;

    Locks the resource referenced by thePath so that only this session can execute writeoperations (e.g., PUT, DELETE) on that resource. The iDisk server reserves the right togrant a lock duration/timeout that differs from the requested lock durationwhen thismethod is successful, the returned DMTransaction objects result method will return anNSDictionary containing an NSNumber value (accessible using the kDMLockTimeoutkey) which is the lock timeout that was granted by the server. The lock will expire afterthe time specified by the granted lock timeout (in seconds) has passed. If the lock requestfails because the specified resource or its parent is already locked, the returned

  • 8/14/2019 DMKit 2 0 API

    32/55

    32

    DMTransaction objects result method will return an NSArray of NSStrings representingthe exact uris which are currently locked. To maintain a lock, issue a relock request onthe same resource before the original lock has expired. [Note: The lock created is acooperative, write lock.]Returns a DMTransaction object that can be used to get the result of the transaction,status, payload, and many other pieces of information about the actual transaction.

    - (DMTransaction *)lockResourceAtPath: (NSString *)thePath

    withDuration: (NSTimeInterval)lockDuration;

    Locks the resource referenced by thePath so that only this session can execute writeoperations (e.g., PUT, DELETE) on that resource. The iDisk server reserves the right togrant a lock duration/timeout that differs from the requested lock durationwhen thismethod is successful, the returned DMTransaction objects result method will return anNSDictionary containing an NSNumber value (accessible using the kDMLockTimeoutkey) which is the lock timeout that was granted by the server. The lock will expire afterthe time specified by the granted lock timeout (in seconds) has passed. If the lock requestfails because the specified resource or its parent is already locked, the returnedDMTransaction objects result method will return an NSArray of NSStrings representingthe exact uris which are currently locked. To maintain a lock, issue a relock request onthe same resource before the original lock has expired. [Note: The lock created is acooperative, write lock.]Returns a DMTransaction object that can be used to get the result of the transaction,status, payload, and many other pieces of information about the actual transaction.

    - (DMTransaction *)relockResourceAtPath: (NSString *)thePath;

    Refreshes the lock on the resource referenced by thePath. The iDisk server reserves theright to grant a lock duration/timeout that differs from the requested lock durationwhenthis method is successful, the returned DMTransaction objects result method will returnan NSDictionary containing an NSNumber value (accessible using the kDMLockTimeoutkey) which is the lock timeout that was granted by the server. Once refreshed, the lockwill expire after the time specified by the granted lock timeout (in seconds) has passed.Attempting to relock a resource that is not locked will always fail. If the relock requestfails because the specified resource or its parent was originally locked by another client,the returned DMTransaction objects result method will return an NSArray of NSStringsrepresenting the exact uris which are currently locked. [Note: The lock created is acooperative, write lock.]Returns a DMTransaction object that can be used to get the result of the transaction,status, payload, and many other pieces of information about the actual transaction.

    - (DMTransaction *)relockResourceAtPath: (NSString *)thePath

    withDuration: (NSTimeInterval)lockDuration;

    Refreshes the lock on the resource referenced by thePath. The iDisk server reserves theright to grant a lock duration/timeout that differs from the requested lock durationwhenthis method is successful, the returned DMTransaction objects result method will return

  • 8/14/2019 DMKit 2 0 API

    33/55

    33

    an NSDictionary containing an NSNumber value (accessible using the kDMLockTimeoutkey) which is the lock timeout that was granted by the server. Once refreshed, the lockwill expire after the time specified by the granted lock timeout (in seconds) has passed.Attempting to relock a resource that is not locked will always fail. If the relock requestfails because the specified resource or its parent was originally locked by another client,the returned DMTransaction objects result method will return an NSArray of NSStringsrepresenting the exact uris which are currently locked. [Note: The lock created is acooperative, write lock.]Returns a DMTransaction object that can be used to get the result of the transaction,status, payload, and many other pieces of information about the actual transaction.

    - (DMTransaction *)unlockResourceAtPath: (NSString *)thePath;

    Releases any lock on the resource referenced by thePath. Attempting to unlock aresource that is not locked will fail.Returns a DMTransaction object that can be used to get the result of the transaction,status, payload, and many other pieces of information about the actual transaction.

    - (void)setDefaultLockDuration: (NSTimeInterval)lockDuration;

    This method sets the default lock duration, in seconds, used by all lock-relatedDMiDiskSession methods that do not specify a transaction-specific lock duration of theirown. If this method is not called, the default lock duration is 5 minutes, given in seconds.

    - (NSTimeInterval)defaultLockDuration;

    Returns the default lock duration set for this DMiDiskSession instance. If no default lockduration has been set for this instance using the setDefaultLockDuration: method, anNSTimeInterval representing 5 minutes, given in seconds, is returned.

    Getting info about objects and collections

    - (BOOL)resourceExistsAtPath: (NSString *)thePath;

    A method which always operates synchronously, resourceExistsAtPath: returns YES if the

    resource specified by thePath exists on the iDisk server, and returns NO otherwise. [Note:

    To check for the existence of a resource asynchronously, use the basicAttributesAtPath:method.]

    - (DMTransaction *)basicAttributesAtPath: (NSString *)thePath;

    Performs a lightweight access against a single file or collection (directory) resourcereferenced by thePath. Use this method when only basic information such as the lastmodified date or content length is needed, as it is lighter weight than anextendedAttributesAtPath: call. If a resource exists at thePath and the transaction issuccessful, the returned DMTransaction objects result method returns an NSDictionary.That NSDictionary contains resource attributes whose values, if present and applicable,can be retrieved using the following NSString key constants:

  • 8/14/2019 DMKit 2 0 API

    34/55

    34

    Key Corresponding Value Type

    kDMContentLength NSNumber (bytes)

    kDMLastModified NSDate

    [Note: kDMContentLength is not returned for collections.]Returns a DMTransaction object that can be used to get the result of the transaction,status, payload, and many other pieces of information about the actual transaction.

    - (DMTransaction *)extendedAttributesAtPath: (NSString*)thePath;

    This method provides the attributes of the file or collection (directory) resource specifiedby thePath. If a resource exists at thePath and the request is successful, the returnedDMTransaction objects result method returns an NSDictionary. That NSDictionarycontains resource attributes whose values, if present and applicable, can be retrievedusing the following NSString key constants:

    Key Corresponding Value Type

    kDMContentLength NSNumber (bytes)kDMLastModified NSDate

    kDMURI NSString

    kDMDisplayName NSString

    kDMContentType NSString

    kDMIsCollection NSNumber (Boolean)

    kDMIsLocked NSNumber (Boolean)

    kDMLockOwner NSString

    kDMLockToken NSStringkDMLockTimeout NSNumber (seconds)

    [Note: kDMContentLength is not returned for collections.]Returns a DMTransaction object that can be used to get the result of the transaction,status, payload, and many other pieces of information about the actual transaction.

    - (DMTransaction *)listCollectionAtPath: (NSString *)thePath;

    This method retrieves the contents of a collection (directory) on the server.DMiDiskSession will issue a WebDAV PROPFIND with a depth of 1 against the targetpath. The collection contents retrieved by this method are shallow and therefore do notinclude the contents of any subdirectories. If the request is successful, the returnedDMTransaction objects result method returns an NSArray of NSDictionaries. Eachdictionary contained in that array has the same format as the resource attribute dictionarythat is retrieved after calling DMiDiskSessions extendedAttributesAtPath: method.

  • 8/14/2019 DMKit 2 0 API

    35/55

    35

    DMiDiskFileManager (Category of DMiDiskSession)

    Please note: All server-side paths passed as arguments to DMiDiskFileManagercategory methods should start with a forward slash, omitting the iDisk account name atthe beginning of the pathfor example, if uploading a local file to a users Public

    folder, the path passed to the createFileAtPath:contents:attributes: method would be ofthe format /Public/.

    - (BOOL)createDirectoryAtPath:(NSString *)path

    attributes:(NSDictionary *);

    This method will create a new directory at the given remote path. It has the same usageas the corresponding method of NSFileManager. However, it does not support the settingof attributes and if a non-nil attributes argument is passed to this method, it will beignored.

    - (BOOL)createFileAtPath:(NSString *)path contents:(NSData *)contentsattributes:(NSDictionary *)attributes;

    This method creates a remote file atpaththat containscontents, behavior which matchesthe style of the corresponding method of NSFileManager. However, it does not supportthe setting of attributes and if a non-nil attributes argument is passed to this method, itwill be ignored.

    - (BOOL)copyPath:(NSString *)source

    toPath:(NSString *)destinationhandler:(id)handler;

    This method will create a copy of the source resource at the given destination path, butwill not overwrite an existing resource. Each path argument can be either a local or aremote pathpassing a local source path and remote destination path leads to an uploadof a local resource, while passing a remote source path and local destination path leads toa download of a remote resource. If two remote paths are provided as arguments, thismethod issues a single, server-side COPY request. This method has usage similar to thatof the corresponding method of NSFileManager. However, it does not support the usageof a callback handler and if a non-nil handler argument is passed to this method, it will beignored. In the case of an upload or download, only the data forks of files and directories

    are copied. In the case of an upload, local symlinks are not preservedwhen a symlinkis encountered, the resource it references will be uploaded. [Note: If two local paths areprovided as arguments, this method calls NSFileManagers copyPath:toPath:handler:method with whatever handler argument was provided.]

  • 8/14/2019 DMKit 2 0 API

    36/55

    36

    - (BOOL)movePath:(NSString *)source toPath:(NSString *)destinationhandler:(id)handler;

    This method will move the source resource to the given destination path, but will notoverwrite an existing resource. Each path argument can be either a local or a remotepathpassing a local source path and remote destination path leads to an upload of alocal resource, while passing a remote source path and local destination path leads to a

    download of a remote resource. If two remote paths are provided as arguments, thismethod issues a single, server-side MOVE request. This method has usage similar to thatof the corresponding method of NSFileManager. However, it does not support the usageof a callback handler and if a non-nil handler argument is passed to this method, it will beignored. In the case of an upload or download, only the data forks of files and directoriesare moved. In the case of an upload, local symlinks are not preservedwhen a symlinkis encountered, the resource it references will be uploaded. [Note: If two local paths areprovided as arguments, this method calls NSFileManagers movePath:toPath:handler:method with whatever handler argument was provided.]

    - (BOOL)removeFileAtPath:(NSString *)path handler:(id)handler;

    This method will remove the resource at the given remote path and has the same usage asthe corresponding method of NSFileManager. However, it does not support the usage ofa callback handler and if a non-nil handler argument is passed to this method, it will beignored.- (NSData *)contentsAtPath:(NSString *)path;

    Returns the contents of the remote file specified inpath as an NSData object. Ifpath

    specifies a directory, or if some other error occurs, this method returnsnil.[Note: Only the data fork of the given file is returned.]

    - (BOOL)fileExistsAtPath:(NSString *)path;

    ReturnsYESif the remote file specified inpath exists, orNOif it does not.

    - (BOOL)fileExistsAtPath:(NSString *)path isDirectory:(BOOL *)

    isDirectory;

    Returns whether the remote file specified inpath exists. If you want to determine ifpathis a directory, specify the address of a Boolean variable for isDirectory, which will be set

    to YESifpath is a directory, and toNOotherwise.- (NSArray *)directoryContentsAtPath:(NSString *)path;

    Searches the contents of the remote directory specified bypath and returns an array ofstrings identifying the directories and files (including symbolic links) contained inpath.The search is shallow and therefore does not return the contents of any subdirectories.

    Returnsnilif the directory specified atpath does not exist or there is some other erroraccessing it. Returns an empty array if the directory exists but has no contents.

  • 8/14/2019 DMKit 2 0 API

    37/55

    37

    Using DMSecurity on DMiDiskSession

    Examples of setting access rights on iDisk resources:

    1) Grant read/modify access to a shared file for a secondary user:

    NSArray *accessRights = [NSArray arrayWithObjects: kDMRead, kDMModify, nil];

    NSString *principalID = [DMSecondaryUser principalIDWithName:@chris andOwner:@scott];DMTransaction *trans = [myiDiskSession setAccess:accessRights

    toEntity:@/Documents/Group Project/To-Do.txtforPrincipals:[NSArray arrayWithObject:principalID]];

    2) Turn a folder on iDisk into a drop box:

    DMTransaction *trans = [myiDiskSession setAccess: [NSArray arrayWithObject:kDMModify]toEntity:@/Documents/Homework Assignments

    forPrincipals:principalIDs];

    3) Grant read access to a shared folder such that any resource it contains can be

    accessed, but the contents of the folder cannot be listed:

    NSArray *accessRights = [NSArray arrayWithObject: kDMReadChildren];

    DMTransaction *trans = [myiDiskSession setAccess:accessRightstoEntity:@/Documents/Calendars

    forPrincipals:principalIDs];

  • 8/14/2019 DMKit 2 0 API

    38/55

    38

    Using Store-and-forward Messaging

  • 8/14/2019 DMKit 2 0 API

    39/55

    39

    DMMessagePublisher(Conforms to DMSecurity, DMTransactionGenerator)

    The DMMessagePublisher session object is used to publish DMMessages to DMTopicsand is thread-safe. The .Mac member credential held by the DMMessagePublishersession represents the member who will be publishing messages to topics. The

    publishing member can publish messages to topics that it itself owns or to topics ownedby other .Mac members. The DMMessagePublisher session conforms to the DMSecurityprotocol and DMTopics are considered securable entities that can be passed toDMSecurity methods for this session. [Note: Only .Mac members can publish orsubscribe to messages. Currently, secondary users cannot.]

    Factories and Initers

    + messagePublisherWithCredentials:(DMMemberAccount *)credentials;

    Returns a new, autoreleased DMMessagePublisher session that will use the provided

    objects credentials when publishing DMMessages or otherwise accessing or modifyingDMTopics. The publishing member can publish messages to topics that it itself owns orto topics owned by other .Mac members.

    - initMessagePublisherWithCredentials: (DMMemberAccount *)credentials;Returns a newly initialized DMMessagePublisher session that will use the providedobjects credentials when publishing DMMessages or otherwise accessing or modifyingDMTopics. The publishing member can publish messages to topics that it itself owns orto topics owned by other .Mac members.

    Convenience API

    - (DMMemberAccount *)credentials;

    Returns the .Mac member object containing the credentials set for thisDMMessagePublisher session. These credentials are used to determine which topics canhave messages published to them or be otherwise modified using this session.

    Creating and Removing topics

    - (DMTransaction *)createTopicNamed: (NSString *)name;Adds a new, empty DMTopic to .Mac. The new topic will be owned by the .Mac memberspecified by this DMMessagePublishers credentials. Returns a DMTransaction objectwhose -isSuccessful method can be used to test for success.

    - (DMTransaction *)removeTopicNamed: (NSString *)name;

    Removes the named DMTopic from .Mac, including all of the messages it contains. Atopic can be removed only by its owner, using the same application that originally created

  • 8/14/2019 DMKit 2 0 API

    40/55

    40

    it. Therefore, the .Mac member name specified by this DMMessagePublisherscredentials must be the owner of the topic and the calling application must be the sameapplication used to originally create the topic. Returns a DMTransaction object whose-isSuccessful method can be used to test for success.

    Working with existing topics

    - (DMTopic *)topicNamed: (NSString *)name;

    Returns an autoreleased DMTopic instance with the provided name. The returned topic'sowner will be the .Mac member name specified by this DMMessagePublisherscredentials and the topics application ID will be set to the calling applications creatorcode. This method is used to obtain a DMTopic object that represents an existing topicon .Mac. The credentials set for this DMMessagePublisher instance will be used toaccess or modify the topic represented by the returned DMTopic object. To publishmessages to a topic or to list the messages in a topic, a DMTopic object is required. Ifyou are trying to obtain a DMTopic object that represents a topic not owned by thisDMMessagePublisher's credentials, use either the -topicNamed:andOwnedBy: method orthe topicNamed:andOwnedBy:withApplicationID: method, as described below.

    - (DMTopic *)topicNamed: (NSString *)name andOwnedBy: (NSString *)memberName;Returns an autoreleased DMTopic instance with the provided name and owner, where theowner is the name of the .Mac member who hosts the given topic. The returned topic'sapplication ID will be set to the calling applications creator code. This method is used toobtain a DMTopic object that represents an existing topic on .Mac. The credentials setfor this DMMessagePublisher instance will be used to access or modify the topicrepresented by the returned DMTopic object. To publish messages to a topic or to list the

    messages in a topic, a DMTopic object is required. If you are trying to obtain a DMTopicobject that represents a topic that was created by an application different from the callingapplication, use the -topicNamed:andOwnedBy:withApplicationID: method, as describedbelow.

    - (DMTopic *)topicNamed: (NSString *)name andOwnedBy: (NSString *)memberName withApplicationID: (NSString *)creatorCode; Returns an autoreleased DMTopic instance with the provided name, owner andapplication ID, where the owner is the name of the .Mac member who hosts the given

    topic and the application ID is the creator code of the application that originally createdthe topic. This method is used to obtain a DMTopic object that represents an existingtopic on .Mac. The credentials set for this DMMessagePublisher instance will be used toaccess or modify the topic represented by the returned DMTopic object. To publishmessages to a topic or to list the messages in a topic, a DMTopic object is required.

  • 8/14/2019 DMKit 2 0 API

    41/55

    41

    - (DMTransaction *)topics;

    Lists the topics that this DMMessagePublisher can publish messages to or removemessages from. Each topic listed may be owned by this session's .Mac membercredentials or by another .Mac member. Returns a DMTransaction object whose-isSuccessful method can be used to test for success and whose -result method, uponsuccess, returns an NSArray of all accessible DMTopic objects.

    Publishing a message to a topic

    - (DMTransaction *)publishMessage: (DMMessage *)message toTopic: (DMTopic *)topic;Publishes a new DMMessage to a DMTopic that already exists on .Mac (an existing topicwill have been previously created on .Mac by the topics owner usingDMMessagePublishers -createTopicNamed: method). The default time-to-live for anewly published DMMessage is 7 days. This default can be overridden using thesessions -setDefaultTimeToLive: method. Time-to-live can also be set on a message-by-message basis using DMMessages -setTimeToLive: method. This method returns a

    DMTransaction object whose -isSuccessful method can be used to test for success.[Note: If .Mac is too busy to handle the message publication request, kDMServiceBusywill be returned by the transactions -errorType method, and publication should be retriedlater. If the given DMMessage has already been published to .Mac, kDMResourceExistswill be returned by the transactions -errorType method.]

    Time-to-live defaults for newly published messages

    - (NSTimeInterval)defaultTimeToLive;

    Returns the default time-to-live that will be used by all DMMessages published by this

    session. The default time-to-live value is 7 days. Returns an NSTimeInterval (precisionin seconds).

    - (int)setDefaultTimeToLive: (NSTimeInterval)defaultTTL;

    Sets the default time-to-live that will be used by all DMMessages published by thissession. The default time-to-live value cannot exceed 30 days. Takes an NSTimeInterval(precision in seconds). If the provided ttl value not in the valid range,kDMInvalidParameter will be returned; otherwise, this method returns kDMSuccess.

  • 8/14/2019 DMKit 2 0 API

    42/55

    42

    Using DMSecurity on DMMessagePublisher:

    Grant another .Mac member read/write access to a DMTopic:

    NSArray *accessRights = [NSArray arrayWithObjects: kDMRead, kDMWrite, nil];

    //Note: For a DMMemberAccount, the name and owner are the same.

    NSString *principalID = [DMMemberAccount principalIDWithName:@george andOwner:@george];DMTransaction *trans = [myMessagePublisher setAccess:accessRights

    toEntity:myTopicforPrincipals:[NSArray arrayWithObject:principalID]];

    When a .Mac member is granted access to a topic, an invitation to that member is

    automatically generated, which can be retrieved using DMMessageSubscribersinvitation-related methods. [Note: If only read access is granted on a DMTopic, it

    means that the invitee will not be able to publish messages to the topic, only receivethem.]

  • 8/14/2019 DMKit 2 0 API

    43/55

    43

    DMMessageSubscriber(Conforms to DMSecurity, DMTransactionGenerator)

    The thread-safe DMMessageSubscriber session object is used to subscribe to specifictopics and to access new messages in topics of interest. The .Mac credentials held by theDMMessageSubscriber session represent the subscriber. The subscriber can subscribe to

    topics that it itself owns and to accessible topics owned by other .Mac members. [Note:Only .Mac members can publish or subscribe to messages. Currently, secondary userscannot.]

    Factories and Initers

    + messageSubscriberWithCredentials: (DMMemberAccount *)credentials;Returns a new, autoreleased DMMessageSubscriber session that will use the providedobjects credentials when subscribing to DMTopics or accessing a DMTopics messages.The provided .Mac member credentials can be used to subscribe to accessible topicsowned by any .Mac member.

    - initMessageSubscriberWithCredentials: (DMMemberAccount *)credentials;Returns a newly initialized DMMessageSubscriber session that will use the providedobjects credentials when subscribing to DMTopics or accessing a DMTopics messages.The provided .Mac member credentials can be used to subscribe to accessible topicsowned by any .Mac member.

    Convenience API

    - (DMMemberAccount *)credentials;

    Returns the .Mac member object containing the credentials set for thisDMMessagePublisher session. These credentials are used to determine which topics canbe subscribed to using this session.

    Working with existing topics

    - (DMTopic *)topicNamed: (NSString *)name;

    Returns an autoreleased DMTopic instance with the provided name. The returned topic'sowner will be the .Mac member name specified by this DMMessageSubscriberscredentials and the topics application ID will be set to the calling applications creatorcode. This method is used to obtain a DMTopic object that represents an existing topicon .Mac. The credentials set for this DMMessageSubscriber instance will be used toaccess the topic represented by the returned DMTopic object. To access messages in atopic, a DMTopic object is required. If you are trying to obtain a DMTopic object that

  • 8/14/2019 DMKit 2 0 API

    44/55

    44

    represents a topic not owned by this DMMessageSubscriber's credentials, use either the-topicNamed:andOwnedBy: method or the-topicNamed:andOwnedBy:withApplicationID: method, as described below.

    - (DMTopic *)topicNamed: (NSString *)name andOwnedBy: (NSString *)memberName;Returns an autoreleased DMTopic instance with the provided name and owner, where theowner is the name of the .Mac member who hosts the given topic. The returned topic'sapplication ID will be set to the calling applications creator code. This method is used toobtain a DMTopic object that represents an existing topic on .Mac. The credentials setfor this DMMessageSubscriber instance will be used to access the topic represented bythe returned DMTopic object. To access messages in a topic, a DMTopic object isrequired. If you are trying to obtain a DMTopic object that represents a topic that wascreated by an application different from the calling application, use the-topicNamed:andOwnedBy:withApplicationID: method, as described below.

    - (DMTopic *)topicNamed: (NSString *)name andOwnedBy: (NSString *)memberName withApplicationID: (NSString *)creatorCode;Returns an autoreleased DMTopic instance with the provided name, owner andapplication ID, where the owner is the name of the .Mac member who hosts the giventopic and the application ID is the creator code of the application that originally createdthe given topic. This method is used to obtain a DMTopic object that represents anexisting topic on .Mac. The credentials set for this DMMessageSubscriber instance willbe used to access the topic represented by the returned DMTopic object. To accessmessages in a topic, a DMTopic object is required.

    Managing subscriptions to topics

    - (DMTransaction *)subscribeToTopic: (DMTopic *)topic;

    Creates a persistent subscription to the given topic. This subscription is specific to thissession's .Mac member credentials, the machine and local OS X user that the callingapplication is running under and the calling application itself. As an argument, thismethod takes a DMTopic to which this session's .Mac member credentials have access.Calling this method creates an entry for the given subscription in the local userpreferences, which will cause the subscription to be reactivated every time the callingapplication runs and creates a DMMessageSubscriber object. Therefore,

    -subscribeToTopic: only needs to be called once for a given topic by an application.Calling -unsubscribeFromTopic: removes the persistent subscription from thepreferences. This method returns a DMTransaction object whose -isSuccessful methodcan be used to test for success.

  • 8/14/2019 DMKit 2 0 API

    45/55

    45

    - (DMTransaction *)unsubscribeFromTopic: (DMTopic *)topic;

    Removes an existing subscription to the given topic. Removes a subscription specific tothe .Mac member for this session, the machine and local OS X user that the callingapplication is running under and the calling application itself. Calling this method deletesthe entry for the given subscription from the local user preferences. As an argument, thismethod takes a DMTopic object to which this session's .Mac member credentials haveaccess. Returns a DMTransaction object whose -isSuccessful method can be used to testfor success.

    - (NSArray *)subscribedTopics;

    Lists the topics to which this session's .Mac member has subscribed (where thesubscription was originally started on this machine for the current OS X user andthe .Mac member credentials set for this session). Each topic listed may be owned byany .Mac member. Returns an NSArray of all DMTopic objects for which subscriptionsexist.

    Setting the subscription delegate

    - (void)setSubscriptionDelegate: (id)delegate;

    Sets the delegate object for this session that will receive callbacks regarding topics ofinterest. The callbacks relate either to changes to subscribed topics or to new topicinvitations sent by other .Mac members. The object passed in this method's delegateparameter must conform to the informal DMSubscriptionDelegate protocol. Delegatesreceive their messages on the same run loop originally used in calling this setSubscriptionDelegate: method.

    - (id)subscriptionDelegate;Retrieves the delegate object for this session that is set to receive callbacks regardingtopics of interest. The callbacks relate either to changes to subscribed topics or to newtopic invitations sent by other .Mac members. Returns a delegate object conforming tothe informal DMSubscriptionDelegate protocol if a subscription delegate has been set forthis session.

  • 8/14/2019 DMKit 2 0 API

    46/55

    46

    Launching apps when a topic changes

    The following methods allow an application or tool to be launched automatically whentopics of interest change. A launched application can find out what new messages areavailable for the changed topics by setting up its own DMMessageSubscriber session.The changes that caused the application to be launched will trigger an appropriatecallback on any subscription delegate that the launched application creates at startup.[Note: The following methods related to registering an app for launching can only beused when the credentials set for this DMMessageSubscriber session are the same asthose credentials found in the .Mac System Preferences panel.]

    - (void)addLaunchableAppForTopics: (NSArray *)topics withBundleIdentifier: (NSString *)bundleID arguments: (NSString *)args options: (DMAutoLaunchOptions)options;This method egisters a bundled application that will be launched when any of thespecified DMTopics change (the topics parameter is an NSArray of DMTopics). You can

    have a single application that launches on changes of multiple topics. The specifiedbundle identifier will be used to resolve the application's path for launchingif thebundle identifier is nil, the calling applications bundle identifier will be used. You canspecify launch arguments in the args parameter that will be passed in unchanged to theapplication when it is launched. Possible values for the options parameter are describedin the Constants section of this document.

    - (void)addLaunchableToolForTopics: (NSArray *)topics withPath: (NSString *)fullPath arguments: (NSString *)args options: (DMAutoLaunchOptions)options;This method registers a tool that will be launched when any of the given DMTopicschange (the topics parameter is an NSArray of DMTopics). You can have a single toolthat launches on changes of multiple topics. The path parameter is a fully-qualified pathto the tool. You can specify launch arguments in the args parameter that will be passed inunchanged to the tool when it is launched. Possible values for the options parameter aredescribed in the Constants section of this document.

    - (void)removeLaunchableAppForTopics: (NSArray *)topics withBundleIdentifier: (NSString *)bundleID; This method removes the identified launchable application for the specified topic(s). Thetopics argument is an NSArray of DMTopic objects for which the given app should nolonger be launched. The bundle identifier argument is the identifier of the application thatwas previously added for the given topicsif the bundle identifier is nil, the callingapplications bundle identifier will be used.

  • 8/14/2019 DMKit 2 0 API

    47/55

    47

    - (void)removeLaunchableToolForTopics: (NSArray *)topics withPath: (NSString *)fullPath; Removes the launchable tool for the specified topic(s). The topics argument is anNSArray of DMTopic objects for which the given tool should no longer be launched.The path argument is a fully-qualified path to the tool that was previously added for thegiven topics.

    - (void)removeLaunchablesForTopics: (NSArray *)topics;Removes all launchable applications and tools for the specified topic(s). Takes anNSArray of DMTopic objects for which all applications and tools should no longer belaunched.

    Handling topic invitations

    - (DMTransaction *)invitationsForTopics;

    Lists all unsubscribed DMTopics owned by other .Mac members to which the .Mac

    member for this session has been invited to subscribe. Returns a DMTransaction objectwhose -isSuccessful method can be used to test for success and whose -result method,upon success, returns an NSArray of DMTopic objects. To be notified upon receipt ofnew invitations immediately, register a subscription delegate that implements the -invitationsReceivedForTopics: method.[Note: An invitation for a topic is automatically sent to a .Mac member when thatmember is granted access to the topic using the DMSecurity protocol methodsimplemented by the DMMessagePublisher session.]

    Using DMSecurity on DMMessageSubscriber:

    Find out what privileges a .Mac member has for a given DMTopic:

    NSArray *accessRights;

    //Note: For a DMMemberAccount, the name and owner are the same.

    NSString *myPrincipalID = [DMMemberAccount principalIDWithName:@ryan andOwner:@ryan];DMTransaction *trans = [myMessageSubscriber accessToEntity:theTopic

    forPrincipal:myPrincipalID];

    //Assuming transaction was done synchronously.

    if ( [trans isSuccessful] ) { accessRights = (NSArray *)[trans result];}

  • 8/14/2019 DMKit 2 0 API

    48/55

    48

    DMSubscriptionDelegate (Informal Protocol)

    - (void)topicsHaveChanged: (NSArray *)topics;

    This method is called when new messages are published to topics of interestthat is,topics to which the active DMMessageSubscriber sessions .Mac member is subscribed.The method takes an NSArray of DMTopic objects. [Note: After receiving this delegate

    message, clients can call a DMTopics -newMessages method to retrieve all new, unseenmessages.]

    - (void)invitationsReceivedForTopics: (NSArray *)topics;

    This method is called when new invitations to subscribe to another .Mac members topicsare received. Only new invitations that have not yet been seen by the currentcombination of .Mac subscriber, running application and local OS X user account arereturned. [Note: An invitation to subscribe to a topic is automatically sent to theinvited .Mac member when that member is granted access to the topic by the topicsowner using DMSecurity protocol methods implemented by the DMMessagePublisher

    class.]

  • 8/14/2019 DMKit 2 0 API

    49/55

    49

    DMTopic(Conforms to DMTransactionGenerator)

    DMTopics have DMMessages published into them using a DMMessagePublisher session.Users of a DMMessageSubscriber session can subscribe to a DMTopic object in order tobe informed when new messages are published to it. DMTopic objects can only becreated using the factory methods of a DMMessagePublisher or a DMMessageSubscribersession, and they inherit the credentials of their parent message session. A topicsnamespace is scoped to its owner (the hosting .Mac member) and the application thatcreated it.

    A DMTopic object can be passed to DMSecurity protocol methods that take an 'entity'argument, in order to set access privileges on the given topic. When a .Mac member isgranted access to a DMTopic, an invitation is automatically generated and can beaccessed using a DMMessageSubscriber session.

    Convenience API

    - (NSString *)name;

    Returns the name of the topic.

    - (NSString *)owner;

    Returns the name of the .Mac member who owns and hosts the topic.

    - (NSString *)applicationID;Returns the creator code of the application that created the topic.

    - (DMMemberAccount *)credentials;Returns the .Mac member object containing the credentials that will be used to access ormodify this DMTopic object. The returned credentials are the same credentials held bythe DMMessagePublisher or DMMessageSubscriber instance that was used to get areference to this DMTopic.

    - (DMTransaction *)exists;

    The returned DMTransaction objects result method returns an NSNumber, whose

    Boolean value can be retrieved using NSNumbers boolValue method. This value will beYES if the DMTopic exists and NO otherwise.

    [Note: If an error is encountered that prevents the existence check, the returnedDMTransactions -errorType method can be used to identify the error.]

  • 8/14/2019 DMKit 2 0 API

    50/55

    50

    Retrieving messages from a topic

    - (NSArray *)newMessages;

    Returns all DMMessages in this DMTopic that have not yet been accessed by the caller.(The caller is defined as a combination of the .Mac credentials set for the session thatcreated this DMTopic, the machine and local OS X user that the calling application isrunning under and the calling application itself.) This method will most often be calledafter a DMMessageSubscriber sessions subscription delegate is informed of a change inthis DMTopic. Returns an NSArray of DMMessages ordered by publication time,starting with the earliest.

    - (NSArray *)messages;Returns all DMMessages found in this DMTopic on .Mac, as an NSArray ofDMMessages. Messages are ordered by publication time, starting with the earliest.

    - (DMMessage *)messageWithID: (NSString *)messageID;

    Retrieves a DMMessage using its globally unique identifier. Returns a DMMessage if theprovided message identifier is valid, and nil otherwise.

    - (DMMessage *)newestMessage;

    Returns the most recent DMMessage in the topic, based on publication time.

    - (DMMessage *)oldestMessage;

    Returns the oldest DMMessage in the topic, based on publication time.

    Removing messages from a topic

    - (DMTransaction *)removeMessageWithID: (NSString *)messageID;

    Removes the identified DMMessage from this DMTopic on .Mac. Returns aDMTransaction object whose -isSuccessful method can be used to test for success.This method can only be called if the .Mac credentials being used have write access tothe given topic.

    - (DMTransaction *)removeMessages;

    Removes all DMMessages from this DMTopic on .Mac. Returns a DMTransactionobject whose -isSuccessful method can be used to test for success. This method can onlybe called if the .Mac credentials being used have write access to the given topic.

  • 8/14/2019 DMKit 2 0 API

    51/55

    51

    Resetting the time-to-live of a published message- (DMTransaction *)resetTimeToLive: (NSTimeInterval)ttl forMessageWithID: (NSString *)messageID;Resets the time-to-live value of the DMMessage specified by given identifier. Returns aDMTransaction object whose -isSuccessful method can be used to test for success. Theprovided time-to-live value, an NSTimeInterval with precision in seconds, cannot be

    greater than 30 days. This method can only be called if the .Mac credentials being usedhave write access to the given topic.

    Controlling auto-arrival of message payloads

    - (void)setIsAutoArrivalEnabledForMessagePayloads: (BOOL)isEnabled;This method sets whether future messages received for the topic should have theirpayloads downloaded automatically to the local message cache before any callbacks aremade on a DMMessageSubscribers subscription delegate. When automatic downloading

    (or auto-arrival) of payl