libaria2.rst 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. .. default-domain:: cpp
  2. .. highlight:: cpp
  3. libaria2: C++ library interface to aria2
  4. ========================================
  5. .. Warning::
  6. The API has not been frozen yet. It will be changed on the course of
  7. the development.
  8. The libaria2 is a C++ library and offers the core functionality of
  9. aria2. The library takes care of all networking and downloading stuff,
  10. so its usage is very straight forward right now. See the following
  11. Tutorial section to see how to use API.
  12. Tutorial
  13. --------
  14. This section is a step by step guide to create a program to download
  15. files using libaria2. The complete source is located at
  16. *libaria2ex.cc* in *examples* directory.
  17. The *libaria2ex* program takes one or more URIs and downloads each of
  18. them in parallel. The usage is::
  19. Usage: libaria2ex URI [URI...]
  20. Download given URIs in parallel in the current directory.
  21. The source code uses C++11 features, so C++11 enabled compiler is
  22. required. GCC 4.7 works well here.
  23. OK, let's look into the source code. First, include aria2.h header
  24. file::
  25. #include <aria2/aria2.h>
  26. Skip to the ``main()`` function. After checking command-line
  27. arguments, we initialize libaria2::
  28. aria2::libraryInit();
  29. And create aria2 session object::
  30. aria2::Session* session;
  31. // Create default configuration. The libaria2 takes care of signal
  32. // handling.
  33. aria2::SessionConfig config;
  34. // Add event callback
  35. config.downloadEventCallback = downloadEventCallback;
  36. session = aria2::sessionNew(aria2::KeyVals(), config);
  37. :type:`Session` ``session`` is an aria2 session object. You need this
  38. object through out the download process. Please keep in mind that only
  39. one :type:`Session` object can be allowed per process due to the heavy
  40. use of static objects in aria2 code base. :type:`Session` object is
  41. not safe for concurrent accesses from multiple threads. It must be
  42. used from one thread at a time. In general, libaria2 is not entirely
  43. thread-safe. :type:`SessionConfig` ``config`` holds configuration for
  44. the session object. The constructor initializes it with the default
  45. values. In this setup, :member:`SessionConfig::keepRunning` is
  46. ``false`` which means :func:`run()` returns when all downloads are
  47. processed, just like aria2c utility without RPC enabled. And
  48. :member:`SessionConfig::useSignalHandler` is ``true``, which means
  49. libaria2 will setup signal handlers and catches certain signals to
  50. halt download process gracefully. We also setup event handler callback
  51. function ``downloadEventCallback``. It will be called when an event
  52. occurred such as download is started, completed, etc. In this example
  53. program, we handle 2 events: download completion and error. For each
  54. event, we print the GID of the download and several other
  55. information::
  56. int downloadEventCallback(aria2::Session* session, aria2::DownloadEvent event,
  57. const aria2::A2Gid& gid, void* userData)
  58. {
  59. switch(event) {
  60. case aria2::EVENT_ON_DOWNLOAD_COMPLETE:
  61. std::cerr << "COMPLETE";
  62. break;
  63. case aria2::EVENT_ON_DOWNLOAD_ERROR:
  64. std::cerr << "ERROR";
  65. break;
  66. default:
  67. return 0;
  68. }
  69. std::cerr << " [" << aria2::gidToHex(gid) << "] ";
  70. ...
  71. }
  72. The ``userData`` object is specified by
  73. :member:`SessionConfig::userData`. In this example, we don't specify
  74. it, so it is ``nullptr``.
  75. The first argument to :func:`sessionNew()` is ``aria2::KeyVals()``.
  76. This type is used in API to specify vector of key/value pairs, mostly
  77. representing aria2 options. For example, specify an option
  78. ``file-allocation`` to ``none``::
  79. aria2::KeyVals options;
  80. options.push_back(std::pair<std::string, std::string> ("file-allocation", "none"));
  81. The first argument of :func:`sessionNew()` is analogous to the
  82. command-line argument to aria2c program. In the example program, we
  83. provide no options, so just pass empty vector.
  84. After the creation of session object, let's add downloads given in the
  85. command-line::
  86. // Add download item to session
  87. for(int i = 1; i < argc; ++i) {
  88. std::vector<std::string> uris = {argv[i]};
  89. aria2::KeyVals options;
  90. rv = aria2::addUri(session, nullptr, uris, options);
  91. if(rv < 0) {
  92. std::cerr << "Failed to add download " << uris[0] << std::endl;
  93. }
  94. }
  95. We iterate command-line arguments and add each of them as a separate
  96. download. :func:`addUri()` can take one or more URIs to download
  97. several sources, just like aria2c does, but in this example, we just
  98. give just one URI. We provide no particular option for the download,
  99. so pass the empty vector as options. The second argument of
  100. :func:`addUri()` takes a pointer to :type:`A2Gid`. If it is not
  101. ``NULL``, the function assigns the GID of the new download to it. In
  102. this example code, we have no interest for it, so just pass
  103. ``nullptr``.
  104. We have set up everything at this stage. So let's start download. To
  105. perform the download, call :func:`run()` repeatedly until it returns
  106. the value other than ``1``::
  107. for(;;) {
  108. rv = aria2::run(session, aria2::RUN_ONCE);
  109. if(rv != 1) {
  110. break;
  111. }
  112. ...
  113. }
  114. Here, we call :func:`run()` with :c:macro:`RUN_ONCE`. It means
  115. :func:`run()` returns after one event polling and its action handling
  116. or polling timeout (which is approximately 1 second). If :func:`run()`
  117. returns ``1``, it means the download is in progress and the
  118. application must call it again. If it returns ``0``, then no download
  119. is left (or it is stopped by signal handler or :func:`shutdown()`).
  120. If the function catches error, it returns ``-1``. The good point of
  121. using :c:macro:`RUN_ONCE` is that the application can use libaria2 API
  122. when :func:`run()` returns. In the example program, we print the
  123. progress of the download in every no less than 500 millisecond::
  124. // Print progress information once per 500ms
  125. if(count >= 500) {
  126. start = now;
  127. aria2::GlobalStat gstat = aria2::getGlobalStat(session);
  128. std::cerr << "Overall #Active:" << gstat.numActive
  129. << " #waiting:" << gstat.numWaiting
  130. << " D:" << gstat.downloadSpeed/1024 << "KiB/s"
  131. << " U:"<< gstat.uploadSpeed/1024 << "KiB/s " << std::endl;
  132. std::vector<aria2::A2Gid> gids = aria2::getActiveDownload(session);
  133. for(const auto& gid : gids) {
  134. aria2::DownloadHandle* dh = aria2::getDownloadHandle(session, gid);
  135. if(dh) {
  136. std::cerr << " [" << aria2::gidToHex(gid) << "] "
  137. << dh->getCompletedLength() << "/"
  138. << dh->getTotalLength() << "("
  139. << (dh->getTotalLength() > 0 ?
  140. (100*dh->getCompletedLength()/dh->getTotalLength())
  141. : 0) << "%)"
  142. << " D:"
  143. << dh->getDownloadSpeed()/1024 << "KiB/s, U:"
  144. << dh->getUploadSpeed()/1024 << "KiB/s"
  145. << std::endl;
  146. aria2::deleteDownloadHandle(dh);
  147. }
  148. }
  149. }
  150. We first call :func:`getGlobalStat()` function to get global
  151. statistics of the downloads. Then, call :func:`getActiveDownload()`
  152. function to get the vector of active download's GID. For each GID, we
  153. retrieve :class:`DownloadHandle` object using
  154. :func:`getDownloadHandle` function and get detailed information.
  155. Please don't forget to delete :class:`DownloadHandle` after the use
  156. and before the next call of :func:`run()`. Keep in mind that the life
  157. time of :class:`DownloadHandle` object is before the next call of
  158. :func:`run()` function.
  159. After the loop, finalize download calling :func:`sessionFinal()`
  160. function and call :func:`libraryDeinit()` to release resources for the
  161. library::
  162. rv = aria2::sessionFinal(session);
  163. aria2::libraryDeinit();
  164. return rv;
  165. Calling :func:`sessionFinal()` is important because it performs
  166. post-download action, including saving sessions and destroys session
  167. object. So failing to call this function will lead to lose the
  168. download progress and memory leak. The :func:`sessionFinal()` returns
  169. the code defined in :ref:`exit-status`. aria2c program also returns
  170. the same value as exist status, so do the same in this tiny example
  171. program.
  172. See also *libaria2wx.cc* which uses wx GUI component as UI and use
  173. background thread to run download.
  174. API Reference
  175. -------------
  176. To use the API function, include ``aria2/aria2.h``::
  177. #include <aria2/aria2.h>
  178. All enums, types and functions are under ``aria2`` namespace. To link
  179. with libaria2, use linker flag ``-laria2``.
  180. .. include:: libaria2api