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.

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