Users of 64-bit AutoHotkey will need to have ComSurrogate running in the background.
It provides the following methods:
Spoiler
moved, copied, or deleted. Folders can be created.
- GetAppKeys - Automates the generation of all of the application and authorization keys.
- GetAccessTokens() - Gets the access tokens needed for the api calls.
- GetAccountInfo() - Retrieves information about the user's account.
- GetCopyReference() - Creates and returns a copy_ref to a file.
- GetDelta() - A way to keep up with changes to files and folders in a user's Dropbox.
- GetFile() - Downloads a file.
- GetMediaLink() - Returns a link directly to a file.
- GetMetadata() - Retrieves file and folder metadata. Simular to a directory listing.
- GetRevisions() - Obtains metadata for the previous revisions of a file.
- GetShareLink() - Creates and returns a Dropbox preview link to files or folders
- PutFile() - Uploads a file.
- RestoreFile() - Restores a file path to a previous revision.
- Search() - Search for files and folders
- GetThumbnail() - Gets a thumbnail for an image.
- UploadChunk() - Uploads large files to Dropbox in mulitple chunks.
- UploadCommit() - Completes an upload initiated by the UploadChunk() method.
moved, copied, or deleted. Folders can be created.
- Copy() - Copies a file or folder to a new location.
- Move() - Moves a file or folder to a new location.
- Delete() - Deletes a file or folder.
- CreateFolder() - Creates a folder.
Requires: HttpRequest() by VxE
Reference: REST API Reference
Class:
Spoiler
/* Class DBox Allows direction manipulation of Dropbox files and folders © 2013 Robert Ryan Help reference: https://www.dropbox.com/developers/core/docs Most methods set this.LastResponse to the last HTTP response code received. This is usually 200 if the operation succeeded. See the help reference for what other values might mean. This is useful for troubleshooting. Members: AppKey - Obtained when you register your app with Dropbox AppSecret - Obtained when you register your app with Dropbox AccessLevel - Chosen when you register your app with Dropbox OauthToken - Authorization token from GetAuthorizationTokens() and GetAccessTokens() OauthTokenSecret - Authorization token from GetAuthorizationTokens() and GetAccessTokens() LastResponse - The last HTTP response code received. Methods: GetAppKeys - Automates the generation of all of the application and authorization keys. GetAccessTokens() - Gets the access tokens needed for the api calls. GetAccountInfo() - Retrieves information about the user's account. GetCopyReference() - Creates and returns a copy_ref to a file. GetDelta() - A way to keep up with changes to files and folders in a user's Dropbox. GetFile() - Downloads a file. GetMediaLink() - Returns a link directly to a file. GetMetadata() - Retrieves file and folder metadata. Simular to a directory listing. GetRevisions() - Obtains metadata for the previous revisions of a file. GetShareLink() - Creates and returns a Dropbox preview link to files or folders PutFile() - Uploads a file. RestoreFile() - Restores a file path to a previous revision. Search() - Search for files and folders GetThumbnail() - Gets a thumbnail for an image. UploadChunk() - Uploads large files to Dropbox in mulitple chunks. UploadCommit() - Completes an upload initiated by the UploadChunk() method. The various fileops calls provide the standard file operations. Files and folders can be moved, copied, or deleted. Folders can be created. Copy() - Copies a file or folder to a new location. Move() - Moves a file or folder to a new location. Delete() - Deletes a file or folder. CreateFolder() - Creates a folder. */ #Include <HttpRequest> class DBox { static APP_CREATE_URL := "https://www.dropbox.com/developers/apps/create" static REQUEST_TOKEN_URL := "https://api.dropbox.com/1/oauth/request_token" static USER_AUTH_URL := "https://www2.dropbox.com/1/oauth/authorize" static ACCESS_TOKEN_URL := "https://api.dropbox.com/1/oauth/access_token" static INFO_URL := "https://api.dropbox.com/1/account/info" static DELTA_URL := "https://api.dropbox.com/1/delta" static METADATA_URL := "https://api.dropbox.com/1/metadata" static DOWNLOAD_URL := "https://api-content.dropbox.com/1/files" static UPLOAD_URL := "https://api-content.dropbox.com/1/files_put" static CHUNKED_UPLOAD_URL := "https://api-content.dropbox.com/1/chunked_upload" static CHUNKED_UPLOAD_COMMIT_URL := "https://api-content.dropbox.com/1/commit_chunked_upload" static REV_URL := "https://api.dropbox.com/1/revisions" static RESTORE_URL := "https://api.dropbox.com/1/restore" static SEARCH_URL := "https://api.dropbox.com/1/search" static SHARES_URL := "https://api.dropbox.com/1/shares" static MEDIA_URL := "https://api.dropbox.com/1/media" static COPY_REFERENCE_URL := "https://api.dropbox.com/1/copy_ref" static THUMBNAIL_URL := "https://api-content.dropbox.com/1/thumbnails" static COPY_URL := "https://api.dropbox.com/1/fileops/copy" static DELETE_URL := "https://api.dropbox.com/1/fileops/delete" static MOVE_URL := "https://api.dropbox.com/1/fileops/move" static MKDIR_URL := "https://api.dropbox.com/1/fileops/create_folder" /**************************************************************************************** Method: __new(AppKey := "", AppSecret := "", AccessLevel := "sandbox", OauthToken := "", OauthTokenSecret := "") Stores the application and authorization keys in the object Parameters: AppKey - The App Key (See Remarks) AppSecret - The App Secret (See Remarks) AccessLevel - This is either "sandbox", if you chose a folder as the root directory, or "dropbox", if you chose to access the entire Dropbox. OauthToken - This is obtained by a previous call to GetAuthorizationTokens() or GetAccessTokens() OauthTokenSecret - This is obtained by a previous call to GetAuthorizationTokens() or GetAccessTokens() Remarks: Obtain an AppKey and AppSecret by going to https://www.dropbox.com/developers/apps/create. Be sure to select the Core API and the correct access level. This only needs to be done once for each application, because the keys never expire. Be sure to SAVE THE TOKENS for later use! Use the GetAppKeys() method for a automated approach to geting these keys. Returns: Nothing */ __New(AppKey := "", AppSecret := "", AccessLevel := "sandbox", OauthToken := "", OauthTokenSecret := "") { this.AppKey := AppKey , this.AppSecret := AppSecret , this.AccessLevel := AccessLevel , this.OauthToken := OauthToken , this.OauthTokenSecret := OauthTokenSecret } /**************************************************************************************** Method: GetAppKeys(UserEmail, UserPassword, AccessLevel, AppName) Automates the generation of all of the application and authorization keys. Parameters: UserEmail - The email address used to log in to the users account. UserPassword - The password used to log in to the users account. AccessLevel - Should be one of the folowing strings: folder - The app will be restricted to a single folder dropbox - The app will have access to the entire dropbox text - Entire dropbox, but restricted to text files document - Entire dropbox, but restricted to document files image - Entire dropbox, but restricted to image files video - Entire dropbox, but restricted to video files audio - Entire dropbox, but restricted to audio files Any other string has the same effect as "folder" AppName - This is the name you want for the app in the App Console. A random number will be appended to the name to ensure that it is unique. For "folder" apps this will also be the name (without the random number) of the folder that is created in the Dropbox/Apps folder. Returns: On success: ErrorLevel is set to 0, true is returned and this.AppKey, this.AppSecret, this.AccessLevel, this.OauthToken and this.OauthTokenSecret are added to the object. On failure: ErrorLevel is set to a message indicating what failed and false is returned. Applications should check ErrorLevel to determine which keys, if any, were generated. */ GetAppKeys(UserEmail, UserPassword, AccessLevel, AppName) { static FileTypes := "text,document,image,video,audio,dropbox" try { BlockInput On if AccessLevel not in %FileTypes% AccessLevel := "sandbox" wb := ComObjCreate("InternetExplorer.Application") wb.Visible := true wb.Navigate(DBox.APP_CREATE_URL) IELoad(wb) if WinActive("Dropbox - Sign in") { wb.Document.all.login_email.Value := UserEmail wb.Document.all.login_password.Value := UserPassword wb.Document.all.login_submit_dummy.Click() IELoad(wb) } ; At the app creation screen now wb.Document.all.app_type[1].Click() ; Select Core API wb.Document.all.data_type[0].Click() ; Select files and datastores wb.Document.all.access_type[AccessLevel = "sandbox" ? 0 : 1].Click() ; Select access type if (AccessLevel <> "sandbox") { wb.Document.all.file_access[AccessLevel = "dropbox" ? 1 : 0].Click() ; Specific file types? if (AccessLevel <> "dropbox") { Index := 0 Loop Parse, FileTypes, `, { if (AccessLevel = A_LoopField) break ++Index } wb.Document.all.file_types[Index].Click() ; Select proper type } } wb.Document.all.name.value := AppName . Rand(0x7FFFFFFF) ; Unique App name InputArray := wb.Document.GetElementsByTagName("input") Index := 0 Loop % InputArray.Length { if (InputArray[Index].value = "Create app") break ++Index } InputArray[Index].Click() ; Click Create App IELoad(wb) ; App created, change folder name if needed if (AccessLevel = "sandbox") { InputArray := wb.Document.GetElementsByTagName("input") Index := 0 Loop % InputArray.Length { if (InputArray[Index].value = "Change") break ++Index } InputArray[Index].Click() wb.Document.all.folder.value := AppName Index := 0 Loop % InputArray.Length { if (InputArray[Index].value = "Save") break ++Index } InputArray[Index].Click() } ; Extract the App Key and the App Secret from the page InputArray := wb.Document.GetElementsByTagName("div") Index := 0 Loop % InputArray.Length { if (InputArray[Index].InnerText = "App key") break ++Index } this.AppKey := InputArray[Index + 1].InnerText this.AppSecret := InputArray[Index + 3].InnerText this.AccessLevel := (AccessLevel = "sandbox") ? "sandbox" : "dropbox" ; Get request tokens InOutData := "" . "oauth_consumer_key=" this.AppKey . "&oauth_signature_method=PLAINTEXT&oauth_signature=" this.AppSecret . "%26&oauth_timestamp=" TimeStamp() "&oauth_nonce=" Rand(0x7FFFFFFF) HTTPRequest(DBox.REQUEST_TOKEN_URL, InOutData, InOutHeader, "Charset: UTF-8") if RegExMatch(InOutData , "oauth_token_secret=(?P<token_secret>[^&]+)&oauth_token=(?P<token>.+)" , oauth_) { this.OauthToken := oauth_token this.OauthTokenSecret := oauth_token_secret } else { throw "Failed to get request tokens" } ; Get user authorization wb.Navigate(DBox.USER_AUTH_URL "?oauth_token=" this.OauthToken) IELoad(wb) wb.Document.all.allow_access.Click() IELoad(wb) wb.Quit() BlockInput Off ; Get access tokens InOutData := "" . "oauth_consumer_key=" this.AppKey . "&oauth_token=" this.OauthToken "&oauth_signature_method=PLAINTEXT" . "&oauth_signature=" this.AppSecret "%26" this.OauthTokenSecret . "&oauth_timestamp=" TimeStamp() "&oauth_nonce=" Rand(0x7FFFFFFF) HTTPRequest(DBox.ACCESS_TOKEN_URL, InOutData, "", "Charset: UTF-8") if RegExMatch(InOutData , "oauth_token_secret=(?P<token_secret>[^&]+)" . "&oauth_token=(?P<token>[^&]+)&uid=(?P<user_id>.+)", oauth_) { this.OauthToken := oauth_token this.OauthTokenSecret := oauth_token_secret this.UserId := oauth_user_id } else { throw "Failed to get access tokens" } errorlevel := 0 return true } ; Something went wrong :( catch e { wb.Quit() BlockInput Off ErrorLevel := IsObject(e) ? e.What : e return false } } /**************************************************************************************** Method: GetAccessTokens(UserEmail, UserPassword) Gets the access tokens needed for the api calls. Before calling this method valid values for this.AppKey, this.AppSecret and this.AccessLevel should be stored in the object via the new method. Parameters: UserEmail - The email address used to log in to the users account. UserPassword - The password used to log in to the users account. Returns: On success: ErrorLevel is set to 0, true is returned. Also this.OauthToken and this.OauthTokenSecret are added to the object. On failure: ErrorLevel is set to a message indicating what failed and false is returned. */ GetAccessTokens(UserEmail, UserPassword) { try { ; Get request tokens InOutData := "" . "oauth_consumer_key=" this.AppKey . "&oauth_signature_method=PLAINTEXT&oauth_signature=" this.AppSecret . "%26&oauth_timestamp=" TimeStamp() "&oauth_nonce=" Rand(0x7FFFFFFF) HTTPRequest(DBox.REQUEST_TOKEN_URL, InOutData, InOutHeader, "Charset: UTF-8") if RegExMatch(InOutData , "oauth_token_secret=(?P<token_secret>[^&]+)&oauth_token=(?P<token>.+)" , oauth_) { this.OauthToken := oauth_token this.OauthTokenSecret := oauth_token_secret } else { throw "Failed to get request tokens" } ; Get user authorization BlockInput On wb := ComObjCreate("InternetExplorer.Application") wb.Visible := true wb.Navigate(DBox.USER_AUTH_URL "?oauth_token=" this.OauthToken) IELoad(wb) if WinActive("Dropbox - Sign in") { wb.Document.all.login_email.Value := UserEmail wb.Document.all.login_password.Value := UserPassword wb.Document.all.login_submit_dummy.Click() IELoad(wb) } wb.Document.all.allow_access.Click() ; Throws Exception if login failed IELoad(wb) wb.Quit() BlockInput Off ; Get access tokens InOutData := "" . "oauth_consumer_key=" this.AppKey . "&oauth_token=" this.OauthToken "&oauth_signature_method=PLAINTEXT" . "&oauth_signature=" this.AppSecret "%26" this.OauthTokenSecret . "&oauth_timestamp=" TimeStamp() "&oauth_nonce=" Rand(0x7FFFFFFF) HTTPRequest(DBox.ACCESS_TOKEN_URL, InOutData, "", "Charset: UTF-8") if RegExMatch(InOutData , "oauth_token_secret=(?P<token_secret>[^&]+)" . "&oauth_token=(?P<token>[^&]+)&uid=(?P<user_id>.+)", oauth_) { this.OauthToken := oauth_token this.OauthTokenSecret := oauth_token_secret this.UserId := oauth_user_id } else { throw "Failed to get access tokens" } errorlevel := 0 return true } ; Something went wrong :( catch e { wb.Quit() BlockInput Off ErrorLevel := IsObject(e) ? e.What : e return false } } /**************************************************************************************** Method: GetAccountInfo(locale := "en") Retrieves information about the user's account. Parameters: Locale - Optional. Use to specify language settings for user error messages and other language specific text Returns: An object containing User account information. */ GetAccountInfo(Locale := "en") { URL := DBox.INFO_URL "?locale=" Locale . this.__Signature() HTTPRequest(URL, InOutData, InOutHeader) RegExMatch(InOutHeader, "HTTP/\d\.\d\h\K\d{3}", Response) this.LastResponse := Response return ParseJson(InOutData) } /**************************************************************************************** Method: GetDelta(Cursor := "", Locale := "en") A way to keep up with changes to files and folders in a user's Dropbox. Periodically call GetDelta() to get a list of "delta entries", which are instructions on how to update your local state to match the server's state. Parameters: Cursor - A string that is used to keep track of the current state. On the first call, leave this blank to receive the entire initial state. On subsequent calls pass in this value to return delta entries that have been recorded since the cursor was returned. Locale - The metadata returned will have its size field translated based on the given locale. Returns: An object with four fields: entries - An object containing a list of "delta entries" See the Help reference.. reset - If true, clear your local state before processing the delta entries. reset is always true on the initial call to GetDelta() (i.e. when no cursor is passed in). Otherwise, it is true in rare situations, such as after server or account maintenance, or if a user deletes their app folder. cursor - A string that encodes the latest information that has been returned. On the next call to GetDelta(), pass in this value. has_more - If true, then there are more entries available; you can call GetDelta() again immediately to retrieve those entries. If 'false', then wait for at least five minutes (preferably longer) before checking again. */ GetDelta(Cursor := "", Locale := "en") { InOutData := "cursor=" Cursor "&locale=" Locale . this.__Signature() HTTPRequest(DBox.DELTA_URL, InOutData, InOutHeader, "Charset: UTF-8") RegExMatch(InOutHeader, "HTTP/\d\.\d\h\K\d{3}", Response) this.LastResponse := Response return ParseJson(InOutData) } /**************************************************************************************** Method: GetFile(Source, Destination, Rev := "") Downloads a file. Parameters: Source - The path to the file you want to retrieve. This is relative to the app folder or the Dropbox root depending on the AccessLevel. This should NOT point to a folder. Destination - The path and file name to download to. This is reative to A_WorkingDir unless a full path is specified. This should NOT point to a folder. Rev - The revision of the file to retrieve. This defaults to the most recent revision. Returns: An object containing the files metadata. See the help reference. */ GetFile(Source, Destination, Rev := "") { URL := DBox.DOWNLOAD_URL "/" this.AccessLevel "/" Source "?rev=" Rev . this.__Signature() HTTPRequest(URL, InOutData, InOutHeader, "SaveAs: " Destination) RegExMatch(InOutHeader, "HTTP/\d\.\d\h\K\d{3}", Response) RegExMatch(InOutHeader, "x-dropbox-metadata:\h\K{[^}]+}", Metadata) this.LastResponse := Response return ParseJson(Metadata) } /**************************************************************************************** Method: GetMetadata(Path := "", List := true, Hash := "", IncludeDeleted := false , Rev := "", FileLimit := "", Locale := "en") Retrieves file and folder metadata. See the help reference. Parameters: Path - The path to the file or folder. List - The strings true and false are valid values. true is the default. If true, the folder's metadata will include a contents field with a list of metadata entries for the contents of the folder. If false, the contents field will be omitted. Hash - Each call to GetMetadata() on a folder will return a hash field, generated by hashing all of the metadata contained in that response. On later calls to GetMetadata(), you should provide that value via this parameter so that if nothing has changed, the previous result can be returned rather than downloading the full, potentially very large, folder listing. This parameter is ignored if the specified path is associated with a file or if list=false. A folder shared between two users will have the same hash for each user. IncludeDeleted - Only applicable when list is true. If this parameter is set to true, then the metadata will include the metadata of deleted children. Note that the target of the metadata call is always returned even when it has been deleted regardless of this flag. Rev - If you include a particular revision number, then only the metadata for that revision will be returned. FileLimit - Default is 10,000 (max is 25,000). When listing a folder, the service won't report listings containing more than the specified amount of files and will instead respond with a 406 (Not Acceptable) status response. Locale - The metadata returned will have its size field translated based on the given locale. Returns: An object containing the metadata for the file or folder at the given <path>. If <path> represents a folder and the list parameter is true, the object will also include a sub-object containing the metadata for the folder's contents. */ GetMetadata(Path := "", List := true, Hash := "", IncludeDeleted := false , Rev := "", FileLimit := 10000, Locale := "en") { static Metadata := {} URL := DBox.METADATA_URL "/" this.AccessLevel "/" Path . "?list=" List "&hash=" Hash "&include_deleted=" IncludeDeleted . "&rev=" Rev "&file_limit=" FileLimit "&locale=" Locale . this.__Signature() HTTPRequest(URL, InOutData, InOutHeader) RegExMatch(InOutHeader, "HTTP/\d\.\d\h\K\d{3}", Response) this.LastResponse := Response if (Response = 200) { if Metadata.HasKey(Hash) Metadata.Remove(Hash, "") Obj := ParseJson(InOutData) return Metadata[Obj.Hash] := Obj } else if (Response = 304) ; Folder unchanged return Metadata[Hash] else return ParseJson(InOutData) } /**************************************************************************************** Method: GetRevisions(Path, RevLimit := 10, Locale := "en") Obtains metadata for the previous revisions of a file. Only revisions up to thirty days old are available (or more if the Dropbox user has Packrat). You can use the revision number in conjunction with the Restore() method to revert the file to its previous state. Parameters: Path - The path to the file. This is relative to the app folder or the Dropbox root depending on the AccessLevel. This parameter should NOT point to a folder. RevLimit - Default is 10. Max is 1,000. When listing a file, the service won't report listings containing more than the amount specified and will instead respond with a 406 (Not Acceptable) status response. Locale - The metadata returned on successful upload will have its size field translated based on the given locale. Returns: An object containing metadata for the files revisions. See the Help reference. */ GetRevisions(Path, RevLimit := 10, Locale := "en") { URL := DBox.REV_URL "/" this.AccessLevel "/" Path . "?rev_limit=" RevLimit "&locale=" Locale . this.__Signature() HTTPRequest(URL, InOutData, InOutHeader) RegExMatch(InOutHeader, "HTTP/\d\.\d\h\K\d{3}", Response) this.LastResponse := Response return ParseJson(InOutData) } /**************************************************************************************** Method: PutFile(Source, Destination, OverWrite := true, ParentRev := "", Locale := "en") Uploads a file. Parameters: Source - The path and file name to upload. This is reative to A_WorkingDir unless a full path is specified. This should NOT point to a folder. Destination - The path to the file you want to write to. This is relative to the app folder or the Dropbox root depending on the AccessLevel. This parameter should NOT point to a folder. OverWrite - This value, either true (default) or false, determines what happens when there's already a file at the specified path. If true, the existing file will be overwritten by the new one. If false, the new file will be automatically renamed (for example, test.txt might be automatically renamed to test (1).txt). The new name can be obtained from the returned metadata. ParentRev - The revision of the file you're editing. If ParentRev matches the latest version of the file on the user's Dropbox, that file will be replaced. Otherwise, the new file will be automatically renamed (for example, test.txt might be automatically renamed to test (conflicted copy).txt). If you specify a revision that doesn't exist, the file won't save (error 400). Get the most recent rev by performing a call to /metadata. Locale - The metadata returned on successful upload will have its size field translated based on the given locale. Returns: An object containing the metadata for the uploaded file. See the Help reference. */ PutFile(Source, Destination, OverWrite := true, ParentRev := "", Locale := "en") { URL := DBox.UPLOAD_URL "/" this.AccessLevel "/" Destination . "?overwrite=" OverWrite "&parent_rev=" ParentRev "&locale=" Locale . this.__Signature() FileGetSize FileSize, %Source% SplitPath Source, , , FileExt RegRead MimeType, HKCR, .%FileExt%, Content Type InOutHeader := "content-length: " FileSize "`ncontent-Type: " MimeType HTTPRequest(URL, InOutData, InOutHeader, "Upload: " Source "`nMethod: PUT`nCharset: UTF-8") RegExMatch(InOutHeader, "HTTP/\d\.\d\h\K\d{3}", Response) this.LastResponse := Response return ParseJson(InOutData) } /**************************************************************************************** Method: RestoreFile(Path, Rev, Locale := "en") Restores a file path to a previous revision. Unlike downloading a file at a given revision and then re-uploading it, this call is atomic. It also saves a bunch of bandwidth. Parameters: Path - The path to the file. This is relative to the app folder or the Dropbox root depending on the AccessLevel. This parameter should NOT point to a folder. Rev - The revision of the file to restore. Locale - The metadata returned on successful upload will have its size field translated based on the given locale. Returns: An object containing the metadata of the restored file. See the Help reference. */ RestoreFile(Path, Rev, Locale := "en") { InOutData := "rev=" Rev "&locale=" Locale . this.__Signature() HTTPRequest(DBox.RESTORE_URL "/" this.AccessLevel "/" Path, InOutData, InOutHeader, "Charset: UTF-8") RegExMatch(InOutHeader, "HTTP/\d\.\d\h\K\d{3}", Response) this.LastResponse := Response return ParseJson(InOutData) } /**************************************************************************************** Method: Search(Query, Path := "", FileLimit := 1000, IncludeDeleted := false, Locale := "en") Returns metadata for all files and folders whose filename contains the given search string as a substring. Searches are limited to the folder path and its sub-folder hierarchy provided in the call. Parameters: Query - The search string. Must be at least three characters long. Path - The path to the folder you want to search from. FileLimit - The maximum and default value is 1,000. No more than FileLimit search results will be returned. IncludeDeleted - If this parameter is set to true, then files and folders that have been deleted will also be included in the search. Locale - The metadata returned on successful upload will have its size field translated based on the given locale. Returns: An object containing metadata entries for any matching files and folders. See the Help reference. */ Search(Query, Path := "", FileLimit := 1000, IncludeDeleted := false, Locale := "en") { InOutData := "query=" Query "&file_limit=" FileLimit "&include_deleted=" IncludeDeleted . "&locale=" Locale . this.__Signature() HTTPRequest(DBox.SEARCH_URL "/" this.AccessLevel "/" Path, InOutData, InOutHeader, "Charset: UTF-8") RegExMatch(InOutHeader, "HTTP/\d\.\d\h\K\d{3}", Response) this.LastResponse := Response return ParseJson(InOutData) } /**************************************************************************************** Method: GetShareLink(Path := "", ShortUrl := true, Locale := "en") Creates and returns a Dropbox link to files or folders users can use to view a preview of the file in a web browser. Parameters: Path - The path to the file or folder you want to link to. ShortUrl - When true (default), the url returned will be shortened using the Dropbox url shortener. If false, the url will link directly to the file's preview page. Locale - Use to specify language settings for user error messages and other language specific text. Returns: An object containing: url - A Dropbox link to the given path. The link can be used publicly and directs to a preview page of the file. expires - The link's expiration date. All links are currently set to expire far enough in the future so that expiration is effectively not an issue. */ GetShareLink(Path := "", ShortUrl := true, Locale := "en") { InOutData := "short_url=" ShortUrl . "&locale=" Locale . this.__Signature() HTTPRequest(DBox.SHARES_URL "/" this.AccessLevel "/" Path, InOutData, InOutHeader, "Charset: UTF-8") RegExMatch(InOutHeader, "HTTP/\d\.\d\h\K\d{3}", Response) this.LastResponse := Response return ParseJson(InOutData) } /**************************************************************************************** Method: GetMediaLink(Path := "", Locale := "en") Returns a link directly to a file. Similar to Share(). The difference is that this bypasses the Dropbox webserver, used to provide a preview of the file, so that you can effectively stream the contents of your media. Parameters: Path - The path to the file or folder you want to link to. Locale - Use to specify language settings for user error messages and other language specific text. Returns: An object containing: url - A Dropbox link that serves the media directly. expires - The link's expiration date. The Media() link expires after four hours, allotting enough time to stream files, but not enough to leave a connection open indefinitely. */ GetMediaLink(Path := "", Locale := "en") { InOutData := "locale=" Locale . this.__Signature() HTTPRequest(DBox.MEDIA_URL "/" this.AccessLevel "/" Path, InOutData, InOutHeader, "Charset: UTF-8") RegExMatch(InOutHeader, "HTTP/\d\.\d\h\K\d{3}", Response) this.LastResponse := Response return ParseJson(InOutData) } /**************************************************************************************** Method: GetCopyReference(Path) Creates and returns a copy_ref to a file. This reference string can be used to copy that file to another user's Dropbox by passing it in as the FromCopyRef parameter on FileCopy(). Parameters: Path - The path to the file you want a copy_ref to refer to. Returns: An object containing: copy_ref - A copy_ref to the specified file. expires - The copy_ref's expiration date. All links are currently set to expire far enough in the future so that expiration is effectively not an issue. */ GetCopyReference(Path) { URL := DBox.COPY_REFERENCE_URL "/" this.AccessLevel "/" Path "?" SubStr(this.__Signature(), 2) HTTPRequest(URL, InOutData, InOutHeader) RegExMatch(InOutHeader, "HTTP/\d\.\d\h\K\d{3}", Response) this.LastResponse := Response return ParseJson(InOutData) } /**************************************************************************************** Method: GetThumbnail(Source, Destination, Format := "jpeg", Size := "s") Gets a thumbnail for an image. Parameters: Source - The path to the image file you want to thumbnail. This is relative to the app folder or the Dropbox root depending on the AccessLevel. This should NOT point to a folder. Destination - The path and file name to download to. This is reative to A_WorkingDir unless a full path is specified. This should NOT point to a folder. Format - jpeg (default) or png. For images that are photos, jpeg should be preferred, while png is better for screenshots and digital art. Size - One of the following values (default: s): value dimensions (px) xs 32x32 s 64x64 m 128x128 l 640x480 xl 1024x768 Returns: An object containing the files metadata. See the help reference. */ GetThumbnail(Source, Destination, Format := "jpeg", Size := "s") { URL := DBox.THUMBNAIL_URL "/" this.AccessLevel "/" Source . "?format=" Format "&size=" Size . this.__Signature() HTTPRequest(URL, InOutData, InOutHeader, "SaveAs: " Destination) RegExMatch(InOutHeader, "HTTP/\d\.\d\h\K\d{3}", Response) RegExMatch(InOutHeader, "x-dropbox-metadata:\h\K{[^}]+}", Metadata) this.LastResponse := Response return ParseJson(Metadata) } /**************************************************************************************** Method: UploadChunk(Chunk, ChunkSize, UploadId := "", Offset := "") Uploads large files to Dropbox in mulitple chunks. Also has the ability to resume if the upload is interrupted. This allows for uploads larger than PutFile()'s maximum of 150 MB. Parameters: Chunk - A binary chunk of data from the file being uploaded. If resuming, the chunk should begin at the number of bytes into the file that equals the offset. ChunkSize - The size of Chunk in bytes. UploadId - The unique ID of the in-progress upload on the server. If left blank, the server will create a new upload session. Offset - The byte offset of this chunk, relative to the beginning of the full file. The server will verify that this matches the offset it expects. If it does not, the server will return an error with the expected offset. Remarks: For files smaller than 150MB use PutFile(), due to it's simpler interface and greater speed. Returns: An object with the following members: upload_id - The unique id for this upload. offset - the expected byte offset for the next Chunk. expires - The expiration time for this upload. */ UploadChunk(Chunk, ChunkSize, UploadId := "", Offset := "") { if (UploadId = "") URL := DBox.CHUNKED_UPLOAD_URL "?" SubStr(this.__Signature(), 2) else URL := DBox.CHUNKED_UPLOAD_URL "?upload_id=" UploadId "&offset=" Offset . this.__Signature() InOutHeader := "content-length: " ChunkSize "`ncontent-Type: application/octet-stream" InOutData := Chunk HTTPRequest(URL, InOutData, InOutHeader, "Method: PUT") RegExMatch(InOutHeader, "HTTP/\d\.\d\h\K\d{3}", Response) this.LastResponse := Response return ParseJson(InOutData) } /**************************************************************************************** Method: UploadCommit(Destination, UploadId, OverWrite := true, ParentRev := "", Locale := "en") Completes an upload initiated by the UploadChunk() method. Saves a file uploaded via UploadChunk() to a user's Dropbox. Parameters: Destination - The path to the file you want to write to. This is relative to the app folder or the Dropbox root depending on the AccessLevel. This parameter should NOT point to a folder. OverWrite - This value, either true (default) or false, determines what happens when there's already a file at the specified path. If true, the existing file will be overwritten by the new one. If false, the new file will be automatically renamed (for example, test.txt might be automatically renamed to test (1).txt). The new name can be obtained from the returned metadata. ParentRev - The revision of the file you're editing. If ParentRev matches the latest version of the file on the user's Dropbox, that file will be replaced. Otherwise, the new file will be automatically renamed (for example, test.txt might be automatically renamed to test (conflicted copy).txt). If you specify a revision that doesn't exist, the file won't save (error 400). Get the most recent rev by performing a call to /metadata. Locale - The metadata returned on successful upload will have its size field translated based on the given locale. Returns: An object containing the metadata for the uploaded file. See the Help reference. */ UploadCommit(Destination, UploadId, OverWrite := true, ParentRev := "", Locale := "en") { InOutData := "upload_id=" UploadId "&overwrite=" OverWrite "&parent_rev=" ParentRev "&locale=" Locale . this.__Signature() HTTPRequest(DBox.CHUNKED_UPLOAD_COMMIT_URL "/" this.AccessLevel "/" Destination, InOutData, InOutHeader, "Charset: UTF-8") RegExMatch(InOutHeader, "HTTP/\d\.\d\h\K\d{3}", Response) this.LastResponse := Response return ParseJson(InOutData) } /**************************************************************************************** Method: Copy(Source, Destination, FromCopyRef := "", Locale := "en") Copies a file or folder to a new location. Parameters: Source - Specifies the file or folder to be copied from relative to root. Destination - Specifies the destination path, including the new name for the file or folder, relative to root. FromCopyRef - Specifies a copy_ref generated from a previous GetCopyReference() call. Must be used instead of the from_path parameter. Locale - The metadata returned on successful upload will have its size field translated based on the given locale. Returns: An object containing the metadata for the uploaded file. See the Help reference. */ Copy(Source, Destination, FromCopyRef := "", Locale := "en") { InOutData := "root=" this.AccessLevel . (FromCopyRef = "" ? "&from_path=" Source : "&from_copy_ref=" FromCopyRef) . "&to_path=" Destination "&locale=" Locale . this.__Signature() HTTPRequest(DBox.COPY_URL, InOutData, InOutHeader, "Charset: UTF-8") RegExMatch(InOutHeader, "HTTP/\d\.\d\h\K\d{3}", Response) this.LastResponse := Response return ParseJson(InOutData) } /**************************************************************************************** Method: CreateFolder(Path, Locale := "en") Creates a folder. Parameters: Path - The path to the new folder to create relative to root. Locale - The metadata returned on successful upload will have its size field translated based on the given locale. Remarks: For files smaller than 150MB use PutFile(), due to it's simpler interface and greater speed.⌐ Returns: An object containing the metadata for the new folder. See the Help reference. */ CreateFolder(Path, Locale := "en") { InOutData := "root=" this.AccessLevel "&path=" Path . this.__Signature() HTTPRequest(DBox.MKDIR_URL, InOutData, InOutHeader, "Charset: UTF-8") RegExMatch(InOutHeader, "HTTP/\d\.\d\h\K\d{3}", Response) this.LastResponse := Response return ParseJson(InOutData) } /**************************************************************************************** Method: Delete(Path, Locale := "en") Deletes a file or folder. Parameters: Path - The path to the file or folder to be deleted. Locale - The metadata returned on successful upload will have its size field translated based on the given locale. Returns: An object containing the metadata for the deleted file or folder. See the Help reference. */ Delete(Path, Locale := "en") { InOutData := "root=" this.AccessLevel "&path=" Path . this.__Signature() HTTPRequest(DBox.DELETE_URL, InOutData, InOutHeader, "Charset: UTF-8") RegExMatch(InOutHeader, "HTTP/\d\.\d\h\K\d{3}", Response) this.LastResponse := Response return ParseJson(InOutData) } /**************************************************************************************** Method: Move(Source, Destination, Locale := "en") Moves a file or folder to a new location. Parameters: Source - Specifies the file or folder to be moved from relative to root. Destination - Specifies the destination path, including the new name for the file or folder, relative to root. Locale - The metadata returned on successful upload will have its size field translated based on the given locale. Returns: An object containing the metadata for the moved file or folder. See the Help reference. */ Move(Source, Destination, Locale := "en") { InOutData := "root=" this.AccessLevel . "&from_path=" Source . "&to_path=" Destination . "&locale=" Locale . this.__Signature() HTTPRequest(DBox.MOVE_URL, InOutData, InOutHeader, "Charset: UTF-8") RegExMatch(InOutHeader, "HTTP/\d\.\d\h\K\d{3}", Response) this.LastResponse := Response return ParseJson(InOutData) } /**************************************************************************************** Method: __Signature() A private method used to sign most of the API calls. Parameters: None Returns: A string containing a unique, valid signature. */ __Signature() { return "&oauth_consumer_key=" this.AppKey . "&oauth_token=" this.OauthToken "&oauth_signature_method=PLAINTEXT" . "&oauth_signature=" this.AppSecret "%26" this.OauthTokenSecret . "&oauth_timestamp=" TimeStamp() "&oauth_nonce=" Rand(0x7FFFFFFF) } } /**************************************************************************************** * * End of Class DBox Definition * **************************************************************************************** */ /**************************************************************************************** Function: IELoad(wb) Waits for a Internet Explorer page to load Parameters: wb - Pointer to the Internet Explorer COM object Returns: Nothing */ IELoad(wb) { If !wb return while not wb.busy Sleep 100 while wb.busy Sleep 100 while wb.Document.Readystate <> "Complete" Sleep 100 } /**************************************************************************************** Function: TimeStamp() A UNIX time stamp Parameters: None Returns: The number of seconds since midnight January 1, 1970 */ TimeStamp() { Time := A_Now EnvSub, Time, 197001010000, S ; 1970-Jan-01 return Time } /**************************************************************************************** Function: Rand(a := 0.0, b := 1) A flexible pseudo-random number function written by VxE Parameters: See Remarks Remarks: Rand() ; - A random float between 0.0 and 1.0 (many uses) Rand(6) ; - A random integer between 1 and 6 (die roll) Rand("") ; - New random seed (selected randomly) Rand("", 12345) ; - New random seed (set explicitly) Rand(50, 100) ; - Random integer between 50 and 100 (typical use) Returns: The pseudo-random number. */ Rand(a := 0.0, b := 1) { if (a = "") Random, , % r := (b = 1) ? Rand(0, 0xFFFFFFFF) : b else Random r, a, b return r } /**************************************************************************************** Function: ParseJson(jsonStr) Converts a JSON string into an AutoHotkey object Parameters: jsonstr - the JSON string to convert Remarks: Originally by Getfree, http://www.autohotkey.com/board/topic/93300-what-format-to-store-settings-in/#entry588268 Returns: The AutoHotkey object. */ ParseJson(jsonStr){ if A_PtrSize = 8 SC := ComCreateObj32("ScriptControl") else SC := ComObjCreate("ScriptControl") SC.Language := "JScript" ComObjError(false) jsCode = ( function arrangeForAhkTraversing(obj){ if(obj instanceof Array){ for(var i=0 ; i<obj.length ; ++i) obj[i] = arrangeForAhkTraversing(obj[i]) ; return ['array',obj] ; }else if(obj instanceof Object){ var keys = [], values = [] ; for(var key in obj){ keys.push(key) ; values.push(arrangeForAhkTraversing(obj[key])) ; } return ['object',[keys,values]] ; }else return [typeof obj,obj] ; } ) SC.ExecuteStatement(jsCode "; obj=" jsonStr) return convertJScriptObjToAhks( SC.Eval("arrangeForAhkTraversing(obj)") ) } convertJScriptObjToAhks(jsObj){ if(jsObj[0]="object"){ obj := {}, keys := jsObj[1][0], values := jsObj[1][1] loop % keys.length obj[keys[A_INDEX-1]] := convertJScriptObjToAhks( values[A_INDEX-1] ) return obj }else if(jsObj[0]="array"){ array := [] loop % jsObj[1].length array.insert(convertJScriptObjToAhks( jsObj[1][A_INDEX-1] )) return array }else return jsObj[1] } ComCreateObj32(ProgIDorCLSID) { static _sur := A_PtrSize = 8 ? ComObjActive("Ahk.ComSurrogate.32") : "" return A_PtrSize = 8 ? _sur.ObjCreate(ProgIDorCLSID) : ComObjCreate(ProgIDorCLSID) }
Change Log:
- 7-12-2013: Changed the GetUserAuthorization() method so that it is more flexible.
- 7-13-2013: GetAccessTokens() was not setting this.LastResponse. Fixed
- 7-14-2013: Class was not working on 64-bit windows. My sincere thanks to BlackHolyman for providing the code to solve this and to fincs for writing ComSurrogate.
- 8-1-2013:
- Added the GetAppKeys() method which automates the generation of all of the application and authorization keys.
- Removed the GetAuthorizationTokens() and GetUserAuthorization() methods and merged their functionallity into the GetAccessTokens() method.
- 8-20-2013: BUGFIX: In many cases, the GetMetadata() method was ignoring the hash parameter.
Edited by rbrtryn, 21 August 2013 - 04:43 AM.