1**************
2MEGA API Usage
3**************
4
5.. go and use the C++ domain
6   http://sphinx-doc.org/domains.html#id1
7   see: Transferring Files
8
9
10Method/Callback Overview
11========================
12
13.. image:: ../../api/html/classMegaClient__coll__graph.png
14   :width: 100%
15   :alt: Collaboration diagramme for the MegaClient class
16
17
18Hashing a Password
19------------------
20
21Hashes a UTF-8-encoded password and stores the result in the supplied
22buffer.
23
24XXX is this really hashpw_key(const char* password, char* hash)
25
26:Method:
27    .. doxygenfunction:: MegaClient::pw_key
28       :no-link:
29
30
31Logging into an Account
32-----------------------
33
34Initiates a session login based on the user e-mail address (case
35insensitive) and the corresponding password hash.
36
37:Method:
38    .. doxygenfunction:: MegaClient::login
39       :no-link:
40       :outline:
41
42.. ``void login(const char* email, const char* hash)``
43
44:Callback:
45    ``login_result(error e)``
46
47:Error codes:
48    :``API_ENOENT``: Invalid e-mail address or password.
49    :``API_EKEY``: Private key could not be decrypted.
50
51
52Logging into an Exported Folder
53-------------------------------
54
55:Method:
56    ``void folderaccess(const char* node, const char* key)``
57
58:Callback:
59    none (does not interact with the server, proceed with
60    calling ``fetchnodes()``)
61
62
63Fetching the Session's Nodes and Users
64--------------------------------------
65
66:Method:
67    ``void fetchnodes()``
68
69:Callback:
70    ``fetchnodes_result(client, error e)``
71
72Upon successful completion, also calls `nodes_updated()``.
73
74
75Retrieving user Account Details, Quota and History
76--------------------------------------------------
77
78:Method:
79    ``void getaccountdetails(AccountDetails* result, int storage, int transfer, int pro, int transactions, int purchases, int sessions)``
80
81Updates the supplied ``AccountDetails`` structure with information on
82current storage and transfer utilization and quota, Pro status, and
83the transaction and session history. You can specify which types of
84information you are interested in by setting the related flag to a
85non-zero value.
86
87
88Changing the Logged in Account's Password
89-----------------------------------------
90
91:Method:
92    ``error changepw(const char* currentpwhash, const char* newpwhash)``
93
94:Callback:
95    ``changepw_result(error e)``
96
97:Returns:
98    :``API_EACCESS``: If no user session exists.
99
100
101Updating a Node's Attributes (with instant completion)
102------------------------------------------------------
103
104:Method:
105    ``error setattr(Node* node, const char** newattr)``
106
107:Returns:
108    :``API_EACCESS``: If node not writable..
109
110:Callback:
111    ``setattr_result(handle nodehandle, error e)``
112
113The node's current attributes are pushed to the server. The optional
114``newattr`` parameter specifies attribute deltas as
115``NULL``-terminated sequence of attribute name/attribute C-string
116pointer pairs. In ``setattr_result()``, ``nodehandle`` is the node's
117handle.
118
119
120Moving a Node to a New Parent Folder (with instant completion)
121--------------------------------------------------------------
122
123:Method:
124    ``error rename(Node* node, Node* newparent)``
125
126:Returns:
127    :``API_EACCESS``: If node's parent or newparent are not
128        ritable (with full and read/write access, respectively) or the
129        move would be between different user accounts.
130    :``API_ECIRCULAR``: If a circular linkage would result..
131
132:Callback:
133    ``rename_result(handle nodehandle, error e)``
134
135The node (along with all of its children) is moved to the new parent
136node, which must be part of the same user account as the node
137itself. You cannot move a mode to its own subtree.
138
139
140Deleting a Node Tree (with instant completion)
141----------------------------------------------
142
143:Method:
144    ``error unlink(Node* node)``
145
146:Returns:
147    :``API_EACCESS``: if the node's parent is not writable
148        (with full access)
149
150:Callback:
151    ``unlink_result(handle nodehandle, error e)``
152
153The node and all of its sub-nodes are deleted. The node's parent must
154be writable (with full access). Affected outbound shares are canceled.
155
156
157Transferring Files
158------------------
159
160Uploads and downloads are started with ``topen()``, which returns a
161*transfer descriptor* identifying the transfer. Multiple transfers can
162run in parallel, and each transfer can use multiple TCP connections in
163parallel. Efficient transfer queuing with pipelining is available.
164Uploads can be speed-limited using an absolute or a dynamic cap.
165
166Progress information is conveyed through a callback:
167
168.. cpp:function:: transfer_update(int td, m_off_t bytes, m_off_t size, dstime starttime)
169
170    Provides progress information.
171
172    .. cpp:member:: td
173
174        Identifies the transfer.
175
176    .. cpp:member:: bytes
177
178         Denotes the number of bytes transferred so far.
179
180    .. cpp:member:: size
181
182        Indicates the total transfer size.
183
184    .. cpp:member:: starttime
185
186        Is the time the transfer started.
187
188A running transfer can be aborted at any time by calling ``tclose(int
189td)``. Failure-indicating callbacks perform the ``tclose()``
190implicitly. The callback indicating a transient HTTP error,
191``transfer_error(int td, int httpcode, int count)`` will call
192``tclose()`` if the application returns a non-zero value.
193
194
195Uploading
196^^^^^^^^^
197
198:Method:
199   ``int topen(const char* localfilename, int speedlimit, int connections)``
200
201   :``speedlimit``: Maximum upload speed in bytes/second or -1 for
202       approx. 90% of the line speed.
203   :``connections``: Number of parallel connections to use (default: 3).
204
205:Returns:
206    A transfer descriptor on success.
207
208    Errors:
209
210    :``API_ETOOMANY``: If all transfer channels are busy
211    :``API_ENOENT``: If file failed to open.
212
213:Callback (completed, success):
214    ``transfer_complete(int td, handle uploadhandle, const byte* uploadtoken, const byte* filekey, SymmCipher* filekey)``
215
216:Callback (failure):
217    ``transfer_failed(int td, error e)``
218
219
220Downloading
221^^^^^^^^^^^
222
223:Method:
224    ``int topen(handle nodehandle, const byte* key, m_off_t start, m_off_t len, int c)``
225
226    :``nodehandle``: The handle of the node to download (if key is set,
227        the handle part of the exported file link).
228    :``key``: The base64-decoded key part of the exported file link if
229        set.
230    :``start`` and ``len``: Can be set to download only a slice of the file
231        (default: 0, -1 for the full file).
232    :``c``: Denotes the number of parallel TCP connections that this
233        download should employ.
234
235:Returns:
236    A transfer descriptor on success.
237
238    Errors:
239
240    :``API_ETOOMANY``: If all transfer channels are busy.
241    :``API_ENOENT``: If local file is not present.
242    :``API_EACCESS``: If attempting to download a non-file.
243
244:Callback (success on opening file for download):
245   ``topen_result(int td, string* filename, const char* fa, int pfa)``
246
247    :``td``: Identifies the transfer.
248    :``filename``: Name of the file as specified by the node
249        attribute ``'n'``.
250    :``fa``: File attributes available for this file.
251    :``pfa``: Flag that indicates whether the requesting user is
252        allowed to write file attributes (i.e., is the file's owner).
253
254:Callback (complete, succcess):
255    ``transfer_complete(int td, chunkmac_map* macs, const char* fn)``
256
257    :``td``: Identifies the transfer.
258    :``macs``: Contains the MAC hash for each file chunk.
259    :``fn``: The filename (UTF-8).
260
261:Callback (failure):
262    ``transfer_failed(int td, string& filename, error e)``
263
264:Callback (reached transfer limit):
265    ``transfer_limit(int td)``
266
267
268Transfer Queuing
269^^^^^^^^^^^^^^^^
270
271The engine maintains separate upload and download queues, ``putq`` and
272``getq``. Transfers are started by pushing transfer objects (classes
273``FilePut`` and ``FileGet`` onto these queues). You no longer need to
274call ``topen()``/``tclose()`` yourself, but you still need to process
275the transfer callbacks. A transfer is considered failed if no bytes
276were transmitted for at least ``XFERTIMEOUT`` deciseconds, in which
277case it will be aborted and repeated indefinitely with exponential
278backoff.
279
280The main benefit of using the engine-supplied transfer queuing is not
281the reduced application complexity, but the built-in overlapping
282transfer pipelining that reduces the impact of transitions between
283files on your overall throughput.
284
285
286Adding Nodes
287------------
288
289Nodes can be added as children of a parent node that you have write
290access to (at least read/write) or "dropped" into the inbox of any
291registered full account, referenced by its e-mail address or user
292handle. If adding the nodes would take the relevant account over its
293storage limit, the addition fails.
294
295File nodes can be created by either copying an existing file based on
296its node handle (private or public), or by using the handle of a
297completed upload.
298
299Folder nodes should always be created from scratch with a fresh random
300key.
301
302The ``NewNode`` structure consists of the following fields:
303
304:``nodehandle``: A random unique handle for new folder nodes or a
305    valid node handle for file copying.
306:``parenthandle``: Must be ``UNDEF`` or reference a folder nodehandle
307    in this invocation of ``putnodes()``.
308:``type``: Either ``FILENODE`` or ``FOLDERNODE``.
309:``source``: ``NEW_NODE``, ``NEW_PUBLIC`` or ``NEW_UPLOAD``.
310:``nodekey``: The AES key for this node, RSA-encrypted to the target
311    user or AES-encrypted to the session user.
312:``ctime`` and ``mtime``: The node's creation and last modification
313    times.
314:``attrstring``: The encrypted node attribute object.
315:``uploadhandle`` and ``uploadtoken``: For upload-based file creation:
316    Upload handle and token.
317
318An array of ``NewNode`` structures is passed to ``putnodes()``. This
319array may be needed after the call has already returned. Due to its
320potentially large size, is not being copied internally, so **always**
321allocate this array from the heap and free it in
322``putnodes_result()``.
323
324
325Adding Children to a Node
326^^^^^^^^^^^^^^^^^^^^^^^^^
327
328:Method:
329    ``void putnodes(handle parenthandle, NewNode* newnodes, int numnodes)``
330
331    :``parenthandle``: Handle of the new nodes' parent node.
332
333The nodes are added below the node designated by ``parenthandle``.
334
335
336Dropping Nodes into a User's Inbox
337^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
338
339:Method:
340    ``void putnodes(const char* user, NewNode* newnodes, int numnodes)``
341
342    :``user``: Recipient user's e-mail address.
343
344The call will fail if the specified address does not denote a MEGA
345account with a valid RSA key pair.
346
347
348File Attributes
349---------------
350
351File attributes can be attached to an existing file by the original
352uploader of the file only. They can also be attached to an upload
353while it is still running, ensuring that they are present at the time
354the upload completes.
355
356Existing file attributes can be bulk-fetched for a set of nodes and a
357given type. The attributes will be decrypted by the engine and fed to
358the application through a series of callbacks.
359
360
361Storing File Attributes
362^^^^^^^^^^^^^^^^^^^^^^^
363
364:Method:
365    ``void putfa(SymmCipher* filekey, handle th, fatype t, const byte* data, unsigned len)``
366
367    :``filekey``: Crypto key for the file (the attributes will be
368        padded to the cipher's block size and then CBC-encrypted using
369        that key).
370    :``th``: Target handle -- either an existing node handle or an
371        upload handle.
372    :``t``: Attribute type (e.g. 0 for a 120 x 120 pixel JPEG
373        thumbnail).
374    :``data`` and ``len``: Attribute data.
375
376:Callback:
377    ``putfa_result(handle th, fatype t, error e)``
378
379
380Retrieving File Attributes
381^^^^^^^^^^^^^^^^^^^^^^^^^^
382
383:Method:
384    ``error getfa(Node* node, fatype t, int cancel)``
385
386    Submits or cancels a file attribute retrieval request.
387
388:Returns:
389    :``API_ENOENT``: No such attribute for this node.
390
391:Callback:
392    ``int fa_failed(handle th, fatype t, int count)``
393
394    Indicates that this attribute could not be fetched for ``count``
395    times. It will be retried with exponential backoff. Returning a
396    non-zero value will cancel the retrieval for this attribute.
397
398:Callback:
399    ``int fa_complete(Node* node, fatype t, const char* data, int len)``
400
401    Passes the decrypted file attribute back to the application.
402
403
404User Contact Management
405-----------------------
406
407Users maintain a *contact list* of peers they know.
408
409:Method:
410    ``inviteContact(const char *email,
411		const char *message,
412		int action,
413		MegaRequestListener *listener = NULL)``
414    :``email``:  User by e-mail address
415
416Receiving a folder share from a user implicitly invites him or her to the
417recipient's contact list.
418
419
420Folder Sharing
421--------------
422
423Folder shares can be created with three access levels: ``RDONLY``
424(readonly), ``RDWR`` (read/write) or ``FULL`` (full - rename and
425delete allowed).
426
427To remove an existing folder share, specify ``ACCESS_UNKNOWN``.
428
429:Method:
430    ``void setshare(Node* node, const char* user, accesslevel access)``
431
432    :``node``: Must reference a folder node in the session user's own
433        trees (you cannot share a node from an inbound share).
434    :``user``: User identifier or e-mail address. If the user has a
435        MEGA account with valid RSA key pair, the share is created and
436        available instantly. Otherwise, he receives an invitation
437        e-mail, and the share is only active after he signs up and
438        successfully requested and received the share-specific AES key
439        from you.
440    :``access``: Specifies the desired new access level or share
441        removal.
442
443:Callback:
444    ``share_result(error e)``
445
446    The share request failed entirely.
447
448:Callback:
449    ``share_result(int index, error e)``
450
451     For aggregate multi-peer share requests, indicates a problem with
452     that particular peer. Currently, index is always 0, as the client
453     access engine only issues single-peer requests.
454
455
456Exporting Nodes
457---------------
458
459To enable unauthenticated access to a file or folder node, the node
460has to be exported. An existing export can be removed. Nodes in
461incoming shares cannot be exported. To decrypt the node and file data
462of an exported file node, the related node key is required. Decrypt of
463the node tree under an exported folder node occurs by way of the
464node's sharekey.
465
466:Method:
467    ``error exportnode(Node* node, int del)``
468
469:Returns:
470    :``API_EACCESS``: Node is in an inbound share.
471
472:Callback (success):
473   ``exportnode_result(handle nodehandle, handle exportedhandle)``
474
475:Callback (failure):
476    ``exportnode_result(error e)``
477
478
479Checking Session Status
480-----------------------
481
482:Method: ``int loggedin()``
483
484:Returns:
485    1 if account session exists, 0 otherwise.
486
487
488Reloading Session State
489-----------------------
490
491This method should be invoked in response to a ``reload()`` callback.
492
493:Method:
494    ``void reload()``
495
496
497Terminating User Session or Folder Login
498----------------------------------------
499
500:Method:
501   ``void logout()``
502
503
504Verifying Node access
505---------------------
506
507:Method:
508    ``int checkaccess(Node* node, accesslevel access)``
509
510:Returns:
511    1 if requested access is allowed, 0 otherwise.
512
513
514Verifying node move
515---------------------------------
516
517:Method:
518    ``error checkmove(Node* node, Node* newparent)``
519
520:Returns:
521    ``API_OK``, ``API_EACCESS`` or ``API_ECIRCULAR``
522
523
524Exponential Backoff Handling
525----------------------------
526
527To prevent infrastructure overload during network or server outages,
528all engine-initiated network actions are protected by a mechanism
529called exponential backoff - the interval between two retries doubles
530upon every failed attempt.
531
532:Callback:
533   ``notify_retry(dstime dsdelta)``
534
535    Indicates failure of the last interaction with the MEGA API
536    servers and the time in deciseconds until the next attempt. The
537    application should show the user a countdown and allow him to
538    manually trigger a new attempt.
539
540:Method:
541   ``void abortbackoff()``
542
543    Resets all exponential backoff timers and immediately retries the
544    pending operation(s).
545
546
547Asynchronous Completion Tracking
548--------------------------------
549
550Application programmers may need to keep track of which callbacks
551relate to which action.
552
553
554Asynchronous Command Tracking
555^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
556
557To make a request trackable (only those methods that can result in
558callbacks are trackable), call ``int nextreqtag()`` and record the
559returned value for later cross-reference. In every callback that
560pertains to this request, the ``restag`` member of the ``MegaClient``
561object will hold the same value.
562
563
564File Transfer Tracking
565^^^^^^^^^^^^^^^^^^^^^^
566
567File transfers are trackable by calling ``int nextreqtag()`` before
568``topen()``. The returned value can then be found in ft[td].tag in the
569``MegaClient`` object.
570
571
572Prefix and Encrypt JSON Object (for use as node attribute string)
573-----------------------------------------------------------------
574
575:Method:
576    ``makeattr(cipher, targetstring, jsonstring, length)``
577
578
579Request for new ``FileAccess`` Object
580-------------------------------------
581
582XXX check signature
583
584:Callback:
585    ``FileAccess newfile()``
586
587:Returns:
588    Application-specific ``FileAccess`` object.
589
590
591User update notification
592---------------------------------
593
594:Callback:
595    ``users_updated(User** users, unsigned count)``
596
597    Users were added or updated (users are never deleted during a
598    session).
599
600
601Node Update Notification
602------------------------
603
604:Callback:
605    ``nodes_updated(Node** nodes, unsigned count)``
606
607    Nodes were added, updated or removed.
608
609:Callback:
610   ``notify_retry(time)``
611
612    Specifies time in decisecons until the next retry.
613
614:Callback:
615    ``reload(reason)``
616
617    Possible inconsistency, reload account state.
618
619
620Error Codes
621===========
622
623.. doxygenenum:: error
624   :no-link:
625