You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

325 lines
9.4 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. #!/usr/bin/env python2
  2. # -*- coding: utf-8 -*-
  3. """Youtubedlg module for managing the download process.
  4. This module is responsible for managing the download process
  5. and update the GUI interface.
  6. Attributes:
  7. MANAGER_PUB_TOPIC (string): wxPublisher subscription topic of the
  8. DownloadManager thread.
  9. WORKER_PUB_TOPIC (string): wxPublisher subscription topic of the
  10. Worker thread.
  11. Note:
  12. It's not the actual module that downloads the urls
  13. thats the job of the 'downloaders' module.
  14. """
  15. from __future__ import unicode_literals
  16. import time
  17. import os.path
  18. from threading import Thread
  19. from wx import CallAfter
  20. from wx.lib.pubsub import setuparg1
  21. from wx.lib.pubsub import pub as Publisher
  22. from .parsers import OptionsParser
  23. from .updatemanager import UpdateThread
  24. from .downloaders import YoutubeDLDownloader
  25. from .utils import YOUTUBEDL_BIN
  26. MANAGER_PUB_TOPIC = 'dlmanager'
  27. WORKER_PUB_TOPIC = 'dlworker'
  28. class DownloadManager(Thread):
  29. """Manages the download process.
  30. Attributes:
  31. WAIT_TIME (float): Time in seconds to sleep.
  32. Args:
  33. urls_list (list): Python list that contains multiple dictionaries
  34. with the url to download and the corresponding row(index) in
  35. which the worker should send the download process information.
  36. opt_manager (optionsmanager.OptionsManager): Object responsible for
  37. managing the youtubedlg options.
  38. log_manager (logmanager.LogManager): Object responsible for writing
  39. errors to the log.
  40. """
  41. WAIT_TIME = 0.1
  42. def __init__(self, urls_list, opt_manager, log_manager=None):
  43. super(DownloadManager, self).__init__()
  44. self.opt_manager = opt_manager
  45. self.log_manager = log_manager
  46. self.urls_list = urls_list
  47. self._time_it_took = 0
  48. self._successful = 0
  49. self._running = True
  50. self._workers = self._init_workers(opt_manager.options['workers_number'])
  51. self.start()
  52. @property
  53. def successful(self):
  54. """Returns number of successful downloads. """
  55. return self._successful
  56. @property
  57. def time_it_took(self):
  58. """Returns time(seconds) it took for the download process
  59. to complete. """
  60. return self._time_it_took
  61. def increase_succ(self):
  62. """Increase number of successful downloads. """
  63. self._successful += 1
  64. def run(self):
  65. self._check_youtubedl()
  66. self._time_it_took = time.time()
  67. while self._running:
  68. for worker in self._workers:
  69. if worker.available() and self.urls_list:
  70. worker.download(self.urls_list.pop(0))
  71. time.sleep(self.WAIT_TIME)
  72. if not self.urls_list and self._jobs_done():
  73. break
  74. # Close all the workers
  75. for worker in self._workers:
  76. worker.close()
  77. worker.join()
  78. self._time_it_took = time.time() - self._time_it_took
  79. if not self._running:
  80. self._talk_to_gui('closed')
  81. else:
  82. self._talk_to_gui('finished')
  83. def active(self):
  84. """Returns number of active items.
  85. Note:
  86. active_items = (workers that work) + (items waiting in the url_list).
  87. """
  88. counter = 0
  89. for worker in self._workers:
  90. if not worker.available():
  91. counter += 1
  92. counter += len(self.urls_list)
  93. return counter
  94. def stop_downloads(self):
  95. """Stop the download process. Also send 'closing'
  96. signal back to the GUI.
  97. Note:
  98. It does NOT kill the workers thats the job of the
  99. clean up task in the run() method.
  100. """
  101. self._talk_to_gui('closing')
  102. self._running = False
  103. for worker in self._workers:
  104. worker.stop_download()
  105. def add_url(self, url):
  106. """Add given url to the urls_list.
  107. Args:
  108. url (dictionary): Python dictionary that contains two keys.
  109. The url and the index of the corresponding row in which
  110. the worker should send back the information about the
  111. download process.
  112. """
  113. self.urls_list.append(url)
  114. def _talk_to_gui(self, data):
  115. """Send data back to the GUI using wxCallAfter and wxPublisher.
  116. Args:
  117. data (string): Unique signal string that informs the GUI for the
  118. download process.
  119. Note:
  120. DownloadManager supports 3 signals.
  121. 1) closing: The download process is closing.
  122. 2) closed: The download process has closed.
  123. 3) finished: The download process was completed normally.
  124. """
  125. CallAfter(Publisher.sendMessage, MANAGER_PUB_TOPIC, data)
  126. def _check_youtubedl(self):
  127. """Check if youtube-dl binary exists. If not try to download it. """
  128. if not os.path.exists(self._youtubedl_path()):
  129. UpdateThread(self.opt_manager.options['youtubedl_path'], True).join()
  130. def _jobs_done(self):
  131. """Returns True if the workers have finished their jobs else False. """
  132. for worker in self._workers:
  133. if not worker.available():
  134. return False
  135. return True
  136. def _youtubedl_path(self):
  137. """Returns the path to youtube-dl binary. """
  138. path = self.opt_manager.options['youtubedl_path']
  139. path = os.path.join(path, YOUTUBEDL_BIN)
  140. return path
  141. def _init_workers(self, workers_number):
  142. """Initialize the custom thread pool.
  143. Returns:
  144. Python list that contains the workers.
  145. """
  146. youtubedl = self._youtubedl_path()
  147. return [Worker(self.opt_manager, youtubedl, self.increase_succ, self.log_manager) for i in xrange(workers_number)]
  148. class Worker(Thread):
  149. """Simple worker which downloads the given url using a downloader
  150. from the 'downloaders' module.
  151. Attributes:
  152. WAIT_TIME (float): Time in seconds to sleep.
  153. Args:
  154. opt_manager (optionsmanager.OptionsManager): Check DownloadManager
  155. description.
  156. youtubedl (string): Absolute path to youtube-dl binary.
  157. increase_succ (DownloadManager.increase_succ() method): Callback to
  158. increase the number of successful downloads.
  159. log_manager (logmanager.LogManager): Check DownloadManager
  160. description.
  161. """
  162. WAIT_TIME = 0.1
  163. def __init__(self, opt_manager, youtubedl, increase_succ, log_manager=None):
  164. super(Worker, self).__init__()
  165. self.increase_succ = increase_succ
  166. self.opt_manager = opt_manager
  167. self._downloader = YoutubeDLDownloader(youtubedl, self._data_hook, log_manager)
  168. self._options_parser = OptionsParser()
  169. self._running = True
  170. self._url = None
  171. self._index = -1
  172. self.start()
  173. def run(self):
  174. while self._running:
  175. if self._url is not None:
  176. options = self._options_parser.parse(self.opt_manager.options)
  177. ret_code = self._downloader.download(self._url, options)
  178. if (ret_code == YoutubeDLDownloader.OK or
  179. ret_code == YoutubeDLDownloader.ALREADY):
  180. self.increase_succ()
  181. # Reset url value
  182. self._url = None
  183. time.sleep(self.WAIT_TIME)
  184. def download(self, item):
  185. """Download given item.
  186. Args:
  187. item (dictionary): Python dictionary that contains two keys.
  188. The url and the index of the corresponding row in which
  189. the worker should send back the information about the
  190. download process.
  191. """
  192. self._url = item['url']
  193. self._index = item['index']
  194. def stop_download(self):
  195. """Stop the download process of the worker. """
  196. self._downloader.stop()
  197. def close(self):
  198. """Kill the worker after stopping the download process. """
  199. self._running = False
  200. self._downloader.stop()
  201. def available(self):
  202. """Return True if the worker has no job else False. """
  203. return self._url is None
  204. def _data_hook(self, data):
  205. """Callback method to be used with the YoutubeDLDownloader object.
  206. This method takes the data from the downloader, merges the
  207. playlist_info with the current status(if any) and sends the
  208. data back to the GUI using the self._talk_to_gui method.
  209. Args:
  210. data (dictionary): Python dictionary which contains information
  211. about the download process. (See YoutubeDLDownloader class).
  212. """
  213. if data['status'] is not None and data['playlist_index'] is not None:
  214. playlist_info = ' '
  215. playlist_info += data['playlist_index']
  216. playlist_info += '/'
  217. playlist_info += data['playlist_size']
  218. data['status'] += playlist_info
  219. self._talk_to_gui(data)
  220. def _talk_to_gui(self, data):
  221. """Send data back to the GUI after inserting the index. """
  222. data['index'] = self._index
  223. CallAfter(Publisher.sendMessage, WORKER_PUB_TOPIC, data)
  224. if __name__ == '__main__':
  225. """Direct call of the module for testing.
  226. Raises:
  227. ValueError: Attempted relative import in non-package
  228. Note:
  229. Before you run the tests change relative imports else an exceptions
  230. will be raised. You need to change relative imports on all the modules
  231. you are gonna use.
  232. """
  233. print "No tests available"