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.

443 lines
14 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 (
  19. Thread,
  20. Lock
  21. )
  22. from wx import CallAfter
  23. from wx.lib.pubsub import setuparg1
  24. from wx.lib.pubsub import pub as Publisher
  25. from .parsers import OptionsParser
  26. from .updatemanager import UpdateThread
  27. from .downloaders import YoutubeDLDownloader
  28. from .utils import (
  29. YOUTUBEDL_BIN,
  30. os_path_exists
  31. )
  32. MANAGER_PUB_TOPIC = 'dlmanager'
  33. WORKER_PUB_TOPIC = 'dlworker'
  34. class DownloadManager(Thread):
  35. """Manages the download process.
  36. Attributes:
  37. WAIT_TIME (float): Time in seconds to sleep.
  38. Args:
  39. urls_list (list): Python list that contains multiple dictionaries
  40. with the url to download and the corresponding row(index) in
  41. which the worker should send the download process information.
  42. opt_manager (optionsmanager.OptionsManager): Object responsible for
  43. managing the youtubedlg options.
  44. log_manager (logmanager.LogManager): Object responsible for writing
  45. errors to the log.
  46. """
  47. WAIT_TIME = 0.1
  48. def __init__(self, urls_list, opt_manager, log_manager=None):
  49. super(DownloadManager, self).__init__()
  50. self.opt_manager = opt_manager
  51. self.log_manager = log_manager
  52. self.urls_list = urls_list
  53. self._time_it_took = 0
  54. self._successful = 0
  55. self._running = True
  56. # Init the custom workers thread pool
  57. log_lock = None if log_manager is None else Lock()
  58. wparams = (opt_manager, self._youtubedl_path(), log_manager, log_lock)
  59. self._workers = [Worker(*wparams) for i in xrange(opt_manager.options['workers_number'])]
  60. self.start()
  61. @property
  62. def successful(self):
  63. """Returns number of successful downloads. """
  64. return self._successful
  65. @property
  66. def time_it_took(self):
  67. """Returns time(seconds) it took for the download process
  68. to complete. """
  69. return self._time_it_took
  70. def run(self):
  71. self._check_youtubedl()
  72. self._time_it_took = time.time()
  73. while self._running:
  74. for worker in self._workers:
  75. if worker.available() and self.urls_list:
  76. worker.download(self.urls_list.pop(0))
  77. time.sleep(self.WAIT_TIME)
  78. if not self.urls_list and self._jobs_done():
  79. break
  80. self._talk_to_gui('report_active')
  81. # Close all the workers
  82. for worker in self._workers:
  83. worker.close()
  84. # Join and collect
  85. for worker in self._workers:
  86. worker.join()
  87. self._successful += worker.successful
  88. self._time_it_took = time.time() - self._time_it_took
  89. if not self._running:
  90. self._talk_to_gui('closed')
  91. else:
  92. self._talk_to_gui('finished')
  93. def active(self):
  94. """Returns number of active items.
  95. Note:
  96. active_items = (workers that work) + (items waiting in the url_list).
  97. """
  98. counter = 0
  99. for worker in self._workers:
  100. if not worker.available():
  101. counter += 1
  102. counter += len(self.urls_list)
  103. return counter
  104. def stop_downloads(self):
  105. """Stop the download process. Also send 'closing'
  106. signal back to the GUI.
  107. Note:
  108. It does NOT kill the workers thats the job of the
  109. clean up task in the run() method.
  110. """
  111. self._talk_to_gui('closing')
  112. self._running = False
  113. def add_url(self, url):
  114. """Add given url to the urls_list.
  115. Args:
  116. url (dict): Python dictionary that contains two keys.
  117. The url and the index of the corresponding row in which
  118. the worker should send back the information about the
  119. download process.
  120. """
  121. self.urls_list.append(url)
  122. def send_to_worker(self, data):
  123. """Send data to the Workers.
  124. Args:
  125. data (dict): Python dictionary that holds the 'index'
  126. which is used to identify the Worker thread and the data which
  127. can be any of the Worker's class valid data. For a list of valid
  128. data keys see __init__() under the Worker class.
  129. """
  130. if 'index' in data:
  131. for worker in self._workers:
  132. if worker.has_index(data['index']):
  133. worker.update_data(data)
  134. def _talk_to_gui(self, data):
  135. """Send data back to the GUI using wxCallAfter and wxPublisher.
  136. Args:
  137. data (string): Unique signal string that informs the GUI for the
  138. download process.
  139. Note:
  140. DownloadManager supports 4 signals.
  141. 1) closing: The download process is closing.
  142. 2) closed: The download process has closed.
  143. 3) finished: The download process was completed normally.
  144. 4) report_active: Signal the gui to read the number of active
  145. downloads using the active() method.
  146. """
  147. CallAfter(Publisher.sendMessage, MANAGER_PUB_TOPIC, data)
  148. def _check_youtubedl(self):
  149. """Check if youtube-dl binary exists. If not try to download it. """
  150. if not os_path_exists(self._youtubedl_path()):
  151. UpdateThread(self.opt_manager.options['youtubedl_path'], True).join()
  152. def _jobs_done(self):
  153. """Returns True if the workers have finished their jobs else False. """
  154. for worker in self._workers:
  155. if not worker.available():
  156. return False
  157. return True
  158. def _youtubedl_path(self):
  159. """Returns the path to youtube-dl binary. """
  160. path = self.opt_manager.options['youtubedl_path']
  161. path = os.path.join(path, YOUTUBEDL_BIN)
  162. return path
  163. class Worker(Thread):
  164. """Simple worker which downloads the given url using a downloader
  165. from the downloaders.py module.
  166. Attributes:
  167. WAIT_TIME (float): Time in seconds to sleep.
  168. Args:
  169. opt_manager (optionsmanager.OptionsManager): Check DownloadManager
  170. description.
  171. youtubedl (string): Absolute path to youtube-dl binary.
  172. log_manager (logmanager.LogManager): Check DownloadManager
  173. description.
  174. log_lock (threading.Lock): Synchronization lock for the log_manager.
  175. If the log_manager is set (not None) then the caller has to make
  176. sure that the log_lock is also set.
  177. Note:
  178. For available data keys see self._data under the __init__() method.
  179. """
  180. WAIT_TIME = 0.1
  181. def __init__(self, opt_manager, youtubedl, log_manager=None, log_lock=None):
  182. super(Worker, self).__init__()
  183. self.opt_manager = opt_manager
  184. self.log_manager = log_manager
  185. self.log_lock = log_lock
  186. self._downloader = YoutubeDLDownloader(youtubedl, self._data_hook, self._log_data)
  187. self._options_parser = OptionsParser()
  188. self._successful = 0
  189. self._running = True
  190. self._wait_for_reply = False
  191. self._data = {
  192. 'playlist_index': None,
  193. 'playlist_size': None,
  194. 'new_filename': None,
  195. 'extension': None,
  196. 'filesize': None,
  197. 'filename': None,
  198. 'percent': None,
  199. 'status': None,
  200. 'index': None,
  201. 'speed': None,
  202. 'path': None,
  203. 'eta': None,
  204. 'url': None
  205. }
  206. self.start()
  207. def run(self):
  208. while self._running:
  209. if self._data['url'] is not None:
  210. options = self._options_parser.parse(self.opt_manager.options)
  211. ret_code = self._downloader.download(self._data['url'], options)
  212. if (ret_code == YoutubeDLDownloader.OK or
  213. ret_code == YoutubeDLDownloader.ALREADY):
  214. self._successful += 1
  215. # Ask GUI for name updates
  216. self._talk_to_gui('receive', {'source': 'filename', 'dest': 'new_filename'})
  217. # Wait until you get a reply
  218. while self._wait_for_reply:
  219. time.sleep(self.WAIT_TIME)
  220. self._reset()
  221. time.sleep(self.WAIT_TIME)
  222. # Call the destructor function of YoutubeDLDownloader object
  223. self._downloader.close()
  224. def download(self, item):
  225. """Download given item.
  226. Args:
  227. item (dict): Python dictionary that contains two keys.
  228. The url and the index of the corresponding row in which
  229. the worker should send back the information about the
  230. download process.
  231. """
  232. self._data['url'] = item['url']
  233. self._data['index'] = item['index']
  234. def stop_download(self):
  235. """Stop the download process of the worker. """
  236. self._downloader.stop()
  237. def close(self):
  238. """Kill the worker after stopping the download process. """
  239. self._running = False
  240. self._downloader.stop()
  241. def available(self):
  242. """Return True if the worker has no job else False. """
  243. return self._data['url'] is None
  244. def has_index(self, index):
  245. """Return True if index is equal to self._data['index'] else False. """
  246. return self._data['index'] == index
  247. def update_data(self, data):
  248. """Update self._data from the given data. """
  249. if self._wait_for_reply:
  250. # Update data only if a receive request has been issued
  251. for key in data:
  252. self._data[key] = data[key]
  253. self._wait_for_reply = False
  254. @property
  255. def successful(self):
  256. """Return the number of successful downloads for current worker. """
  257. return self._successful
  258. def _reset(self):
  259. """Reset self._data back to the original state. """
  260. for key in self._data:
  261. self._data[key] = None
  262. def _log_data(self, data):
  263. """Callback method for self._downloader.
  264. This method is used to write the given data in a synchronized way
  265. to the log file using the self.log_manager and the self.log_lock.
  266. Args:
  267. data (string): String to write to the log file.
  268. """
  269. if self.log_manager is not None:
  270. self.log_lock.acquire()
  271. self.log_manager.log(data)
  272. self.log_lock.release()
  273. def _data_hook(self, data):
  274. """Callback method for self._downloader.
  275. This method updates self._data and sends the updates back to the
  276. GUI using the self._talk_to_gui() method.
  277. Args:
  278. data (dict): Python dictionary which contains information
  279. about the download process. For more info see the
  280. extract_data() function under the downloaders.py module.
  281. """
  282. # Temp dictionary which holds the updates
  283. temp_dict = {}
  284. # Update each key
  285. for key in data:
  286. if self._data[key] != data[key]:
  287. self._data[key] = data[key]
  288. temp_dict[key] = data[key]
  289. # Build the playlist status if there is an update
  290. if self._data['playlist_index'] is not None:
  291. if 'status' in temp_dict or 'playlist_index' in temp_dict:
  292. temp_dict['status'] = '{status} {index}/{size}'.format(
  293. status=self._data['status'],
  294. index=self._data['playlist_index'],
  295. size=self._data['playlist_size']
  296. )
  297. if len(temp_dict):
  298. self._talk_to_gui('send', temp_dict)
  299. def _talk_to_gui(self, signal, data):
  300. """Communicate with the GUI using wxCallAfter and wxPublisher.
  301. Send/Ask data to/from the GUI. Note that if the signal is 'receive'
  302. then the Worker will wait until it receives a reply from the GUI.
  303. Args:
  304. signal (string): Unique string that informs the GUI about the
  305. communication procedure.
  306. data (dict): Python dictionary which holds the data to be sent
  307. back to the GUI. If the signal is 'send' then the dictionary
  308. contains the updates for the GUI (e.g. percentage, eta). If
  309. the signal is 'receive' then the dictionary contains exactly
  310. three keys. The 'index' (row) from which we want to retrieve
  311. the data, the 'source' which identifies a column in the
  312. wxListCtrl widget and the 'dest' which tells the wxListCtrl
  313. under which key to store the retrieved data.
  314. Note:
  315. Worker class supports 2 signals.
  316. 1) send: The Worker sends data back to the GUI
  317. (e.g. Send status updates).
  318. 2) receive: The Worker asks data from the GUI
  319. (e.g. Receive the name of a file).
  320. Structure:
  321. ('send', {'index': <item_row>, data_to_send*})
  322. ('receive', {'index': <item_row>, 'source': 'source_key', 'dest': 'destination_key'})
  323. """
  324. data['index'] = self._data['index']
  325. if signal == 'receive':
  326. self._wait_for_reply = True
  327. CallAfter(Publisher.sendMessage, WORKER_PUB_TOPIC, (signal, data))