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.

744 lines
23 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
  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. RLock,
  21. Lock
  22. )
  23. from wx import CallAfter
  24. from wx.lib.pubsub import setuparg1
  25. from wx.lib.pubsub import pub as Publisher
  26. from .parsers import OptionsParser
  27. from .updatemanager import UpdateThread
  28. from .downloaders import YoutubeDLDownloader
  29. from .utils import (
  30. YOUTUBEDL_BIN,
  31. os_path_exists,
  32. format_bytes,
  33. to_string,
  34. to_bytes
  35. )
  36. MANAGER_PUB_TOPIC = 'dlmanager'
  37. WORKER_PUB_TOPIC = 'dlworker'
  38. _SYNC_LOCK = RLock()
  39. # Decorator that adds thread synchronization to a function
  40. def synchronized(lock):
  41. def _decorator(func):
  42. def _wrapper(*args, **kwargs):
  43. lock.acquire()
  44. ret_value = func(*args, **kwargs)
  45. lock.release()
  46. return ret_value
  47. return _wrapper
  48. return _decorator
  49. class DownloadItem(object):
  50. """Object that represents a download.
  51. Attributes:
  52. STAGES (tuple): Main stages of the download item.
  53. ACTIVE_STAGES (tuple): Sub stages of the 'Active' stage.
  54. COMPLETED_STAGES (tuple): Sub stages of the 'Completed' stage.
  55. ERROR_STAGES (tuple): Sub stages of the 'Error' stage.
  56. Args:
  57. url (string): URL that corresponds to the download item.
  58. options (list): Options list to use during the download phase.
  59. """
  60. STAGES = ("Queued", "Active", "Paused", "Completed", "Error")
  61. ACTIVE_STAGES = ("Pre Processing", "Downloading", "Post Processing")
  62. COMPLETED_STAGES = ("Finished", "Warning", "Already Downloaded")
  63. ERROR_STAGES = ("Error", "Stopped", "Filesize Abort")
  64. def __init__(self, url, options):
  65. self.url = url
  66. self.options = options
  67. self.object_id = hash(url + to_string(options))
  68. self.reset()
  69. @property
  70. def stage(self):
  71. return self._stage
  72. @stage.setter
  73. def stage(self, value):
  74. if value not in self.STAGES:
  75. raise ValueError(value)
  76. if value == "Queued":
  77. self.progress_stats["status"] = value
  78. if value == "Active":
  79. self.progress_stats["status"] = self.ACTIVE_STAGES[0]
  80. if value == "Completed":
  81. self.progress_stats["status"] = self.COMPLETED_STAGES[0]
  82. if value == "Paused":
  83. self.progress_stats["status"] = value
  84. if value == "Error":
  85. self.progress_stats["status"] = self.ERROR_STAGES[0]
  86. self._stage = value
  87. def reset(self):
  88. if hasattr(self, "_stage") and self._stage == self.STAGES[1]:
  89. raise RuntimeError("Cannot reset an 'Active' item")
  90. self._stage = self.STAGES[0]
  91. self.path = ""
  92. self.filenames = []
  93. self.extensions = []
  94. self.filesizes = []
  95. self.default_values = {
  96. "filename": self.url,
  97. "extension": "-",
  98. "filesize": "-",
  99. "percent": "0%",
  100. "speed": "-",
  101. "eta": "-",
  102. "status": self.stage,
  103. "playlist_size": "",
  104. "playlist_index": ""
  105. }
  106. self.progress_stats = dict(self.default_values)
  107. def get_files(self):
  108. """Returns a list that contains all the system files bind to this object."""
  109. files = []
  110. for index, item in enumerate(self.filenames):
  111. filename = item + self.extensions[index]
  112. files.append(os.path.join(self.path, filename))
  113. return files
  114. def update_stats(self, stats_dict):
  115. """Updates the progress_stats dict from the given dictionary."""
  116. assert isinstance(stats_dict, dict)
  117. for key in stats_dict:
  118. if key in self.progress_stats:
  119. value = stats_dict[key]
  120. if not isinstance(value, basestring) or not value:
  121. self.progress_stats[key] = self.default_values[key]
  122. else:
  123. self.progress_stats[key] = value
  124. # Extract extra stuff
  125. if key == "filename":
  126. self.filenames.append(stats_dict[key])
  127. if key == "extension":
  128. self.extensions.append(stats_dict[key])
  129. if key == "path":
  130. self.path = stats_dict[key]
  131. if key == "status":
  132. self._set_stage(stats_dict[key])
  133. if "filesize" in stats_dict:
  134. if len(self.filesizes) < len(self.filenames):
  135. filesize = stats_dict["filesize"].lstrip("~") # HLS downloader etc
  136. self.filesizes.append(to_bytes(filesize))
  137. if "status" in stats_dict:
  138. # If we are post processing try to calculate the size of
  139. # the output file since youtube-dl does not
  140. if stats_dict["status"] == self.ACTIVE_STAGES[2] and not len(self.filenames) % 3:
  141. post_proc_filesize = self.filesizes[-2] + self.filesizes[-1]
  142. self.filesizes.append(post_proc_filesize)
  143. self.progress_stats["filesize"] = format_bytes(post_proc_filesize)
  144. def _set_stage(self, status):
  145. if status in self.ACTIVE_STAGES:
  146. self._stage = self.STAGES[1]
  147. if status in self.COMPLETED_STAGES:
  148. self._stage = self.STAGES[3]
  149. if status in self.ERROR_STAGES:
  150. self._stage = self.STAGES[4]
  151. def __eq__(self, other):
  152. return self.object_id == other.object_id
  153. class DownloadList(object):
  154. """List like data structure that contains DownloadItems.
  155. Args:
  156. items (list): List that contains DownloadItems.
  157. """
  158. def __init__(self, items=None):
  159. assert isinstance(items, list) or items is None
  160. if items is None:
  161. self._items_dict = {} # Speed up lookup
  162. self._items_list = [] # Keep the sequence
  163. else:
  164. self._items_list = [item.object_id for item in items]
  165. self._items_dict = {item.object_id: item for item in items}
  166. @synchronized(_SYNC_LOCK)
  167. def clear(self):
  168. """Removes all the items from the list even the 'Active' ones."""
  169. self._items_list = []
  170. self._items_dict = {}
  171. @synchronized(_SYNC_LOCK)
  172. def insert(self, item):
  173. """Inserts the given item to the list. Does not check for duplicates. """
  174. self._items_list.append(item.object_id)
  175. self._items_dict[item.object_id] = item
  176. @synchronized(_SYNC_LOCK)
  177. def remove(self, object_id):
  178. """Removes an item from the list.
  179. Removes the item with the corresponding object_id from
  180. the list if the item is not in 'Active' state.
  181. Returns:
  182. True on success else False.
  183. """
  184. if self._items_dict[object_id].stage != "Active":
  185. self._items_list.remove(object_id)
  186. del self._items_dict[object_id]
  187. return True
  188. return False
  189. @synchronized(_SYNC_LOCK)
  190. def fetch_next(self):
  191. """Returns the next queued item on the list.
  192. Returns:
  193. Next queued item or None if no other item exist.
  194. """
  195. for object_id in self._items_list:
  196. cur_item = self._items_dict[object_id]
  197. if cur_item.stage == "Queued":
  198. return cur_item
  199. return None
  200. @synchronized(_SYNC_LOCK)
  201. def move_up(self, object_id):
  202. """Moves the item with the corresponding object_id up to the list."""
  203. index = self._items_list.index(object_id)
  204. if index > 0:
  205. self._swap(index, index - 1)
  206. return True
  207. return False
  208. @synchronized(_SYNC_LOCK)
  209. def move_down(self, object_id):
  210. """Moves the item with the corresponding object_id down to the list."""
  211. index = self._items_list.index(object_id)
  212. if index < (len(self._items_list) - 1):
  213. self._swap(index, index + 1)
  214. return True
  215. return False
  216. @synchronized(_SYNC_LOCK)
  217. def get_item(self, object_id):
  218. """Returns the DownloadItem with the given object_id."""
  219. return self._items_dict[object_id]
  220. @synchronized(_SYNC_LOCK)
  221. def has_item(self, object_id):
  222. """Returns True if the given object_id is in the list else False."""
  223. return object_id in self._items_list
  224. @synchronized(_SYNC_LOCK)
  225. def get_items(self):
  226. """Returns a list with all the items."""
  227. return [self._items_dict[object_id] for object_id in self._items_list]
  228. @synchronized(_SYNC_LOCK)
  229. def change_stage(self, object_id, new_stage):
  230. """Change the stage of the item with the given object_id."""
  231. self._items_dict[object_id].stage = new_stage
  232. @synchronized(_SYNC_LOCK)
  233. def index(self, object_id):
  234. """Get the zero based index of the item with the given object_id."""
  235. if object_id in self._items_list:
  236. return self._items_list.index(object_id)
  237. return -1
  238. @synchronized(_SYNC_LOCK)
  239. def __len__(self):
  240. return len(self._items_list)
  241. def _swap(self, index1, index2):
  242. self._items_list[index1], self._items_list[index2] = self._items_list[index2], self._items_list[index1]
  243. class DownloadManager(Thread):
  244. """Manages the download process.
  245. Attributes:
  246. WAIT_TIME (float): Time in seconds to sleep.
  247. Args:
  248. download_list (DownloadList): List that contains items to download.
  249. opt_manager (optionsmanager.OptionsManager): Object responsible for
  250. managing the youtubedlg options.
  251. log_manager (logmanager.LogManager): Object responsible for writing
  252. errors to the log.
  253. """
  254. WAIT_TIME = 0.1
  255. def __init__(self, parent, download_list, opt_manager, log_manager=None):
  256. super(DownloadManager, self).__init__()
  257. self.parent = parent
  258. self.opt_manager = opt_manager
  259. self.log_manager = log_manager
  260. self.download_list = download_list
  261. self._time_it_took = 0
  262. self._successful = 0
  263. self._running = True
  264. # Init the custom workers thread pool
  265. log_lock = None if log_manager is None else Lock()
  266. wparams = (opt_manager, self._youtubedl_path(), log_manager, log_lock)
  267. self._workers = [Worker(*wparams) for _ in xrange(opt_manager.options["workers_number"])]
  268. self.start()
  269. @property
  270. def successful(self):
  271. """Returns number of successful downloads. """
  272. return self._successful
  273. @property
  274. def time_it_took(self):
  275. """Returns time(seconds) it took for the download process
  276. to complete. """
  277. return self._time_it_took
  278. def run(self):
  279. self._check_youtubedl()
  280. self._time_it_took = time.time()
  281. while self._running:
  282. item = self.download_list.fetch_next()
  283. if item is not None:
  284. worker = self._get_worker()
  285. if worker is not None:
  286. worker.download(item.url, item.options, item.object_id)
  287. self.download_list.change_stage(item.object_id, "Active")
  288. if item is None and self._jobs_done():
  289. break
  290. time.sleep(self.WAIT_TIME)
  291. # Close all the workers
  292. for worker in self._workers:
  293. worker.close()
  294. # Join and collect
  295. for worker in self._workers:
  296. worker.join()
  297. self._successful += worker.successful
  298. self._time_it_took = time.time() - self._time_it_took
  299. if not self._running:
  300. self._talk_to_gui('closed')
  301. else:
  302. self._talk_to_gui('finished')
  303. def active(self):
  304. """Returns number of active items.
  305. Note:
  306. active_items = (workers that work) + (items waiting in the url_list).
  307. """
  308. #counter = 0
  309. #for worker in self._workers:
  310. #if not worker.available():
  311. #counter += 1
  312. #counter += len(self.download_list)
  313. return len(self.download_list)
  314. def stop_downloads(self):
  315. """Stop the download process. Also send 'closing'
  316. signal back to the GUI.
  317. Note:
  318. It does NOT kill the workers thats the job of the
  319. clean up task in the run() method.
  320. """
  321. self._talk_to_gui('closing')
  322. self._running = False
  323. def add_url(self, url):
  324. """Add given url to the download_list.
  325. Args:
  326. url (dict): Python dictionary that contains two keys.
  327. The url and the index of the corresponding row in which
  328. the worker should send back the information about the
  329. download process.
  330. """
  331. self.download_list.append(url)
  332. def send_to_worker(self, data):
  333. """Send data to the Workers.
  334. Args:
  335. data (dict): Python dictionary that holds the 'index'
  336. which is used to identify the Worker thread and the data which
  337. can be any of the Worker's class valid data. For a list of valid
  338. data keys see __init__() under the Worker class.
  339. """
  340. if 'index' in data:
  341. for worker in self._workers:
  342. if worker.has_index(data['index']):
  343. worker.update_data(data)
  344. def _talk_to_gui(self, data):
  345. """Send data back to the GUI using wxCallAfter and wxPublisher.
  346. Args:
  347. data (string): Unique signal string that informs the GUI for the
  348. download process.
  349. Note:
  350. DownloadManager supports 4 signals.
  351. 1) closing: The download process is closing.
  352. 2) closed: The download process has closed.
  353. 3) finished: The download process was completed normally.
  354. 4) report_active: Signal the gui to read the number of active
  355. downloads using the active() method.
  356. """
  357. CallAfter(Publisher.sendMessage, MANAGER_PUB_TOPIC, data)
  358. def _check_youtubedl(self):
  359. """Check if youtube-dl binary exists. If not try to download it. """
  360. if not os_path_exists(self._youtubedl_path()) and self.parent.update_thread is None:
  361. self.parent.update_thread = UpdateThread(self.opt_manager.options['youtubedl_path'], True)
  362. self.parent.update_thread.join()
  363. self.parent.update_thread = None
  364. def _get_worker(self):
  365. for worker in self._workers:
  366. if worker.available():
  367. return worker
  368. return None
  369. def _jobs_done(self):
  370. """Returns True if the workers have finished their jobs else False. """
  371. for worker in self._workers:
  372. if not worker.available():
  373. return False
  374. return True
  375. def _youtubedl_path(self):
  376. """Returns the path to youtube-dl binary. """
  377. path = self.opt_manager.options['youtubedl_path']
  378. path = os.path.join(path, YOUTUBEDL_BIN)
  379. return path
  380. class Worker(Thread):
  381. """Simple worker which downloads the given url using a downloader
  382. from the downloaders.py module.
  383. Attributes:
  384. WAIT_TIME (float): Time in seconds to sleep.
  385. Args:
  386. opt_manager (optionsmanager.OptionsManager): Check DownloadManager
  387. description.
  388. youtubedl (string): Absolute path to youtube-dl binary.
  389. log_manager (logmanager.LogManager): Check DownloadManager
  390. description.
  391. log_lock (threading.Lock): Synchronization lock for the log_manager.
  392. If the log_manager is set (not None) then the caller has to make
  393. sure that the log_lock is also set.
  394. Note:
  395. For available data keys see self._data under the __init__() method.
  396. """
  397. WAIT_TIME = 0.1
  398. def __init__(self, opt_manager, youtubedl, log_manager=None, log_lock=None):
  399. super(Worker, self).__init__()
  400. self.opt_manager = opt_manager
  401. self.log_manager = log_manager
  402. self.log_lock = log_lock
  403. self._downloader = YoutubeDLDownloader(youtubedl, self._data_hook, self._log_data)
  404. self._options_parser = OptionsParser()
  405. self._successful = 0
  406. self._running = True
  407. self._options = None
  408. self._wait_for_reply = False
  409. self._data = {
  410. 'playlist_index': None,
  411. 'playlist_size': None,
  412. 'new_filename': None,
  413. 'extension': None,
  414. 'filesize': None,
  415. 'filename': None,
  416. 'percent': None,
  417. 'status': None,
  418. 'index': None,
  419. 'speed': None,
  420. 'path': None,
  421. 'eta': None,
  422. 'url': None
  423. }
  424. self.start()
  425. def run(self):
  426. while self._running:
  427. if self._data['url'] is not None:
  428. #options = self._options_parser.parse(self.opt_manager.options)
  429. ret_code = self._downloader.download(self._data['url'], self._options)
  430. if (ret_code == YoutubeDLDownloader.OK or
  431. ret_code == YoutubeDLDownloader.ALREADY or
  432. ret_code == YoutubeDLDownloader.WARNING):
  433. self._successful += 1
  434. # Ask GUI for name updates
  435. #self._talk_to_gui('receive', {'source': 'filename', 'dest': 'new_filename'})
  436. # Wait until you get a reply
  437. #while self._wait_for_reply:
  438. #time.sleep(self.WAIT_TIME)
  439. self._reset()
  440. time.sleep(self.WAIT_TIME)
  441. # Call the destructor function of YoutubeDLDownloader object
  442. self._downloader.close()
  443. def download(self, url, options, object_id):
  444. """Download given item.
  445. Args:
  446. item (dict): Python dictionary that contains two keys.
  447. The url and the index of the corresponding row in which
  448. the worker should send back the information about the
  449. download process.
  450. """
  451. self._data['url'] = url
  452. self._options = options
  453. self._data['index'] = object_id
  454. def stop_download(self):
  455. """Stop the download process of the worker. """
  456. self._downloader.stop()
  457. def close(self):
  458. """Kill the worker after stopping the download process. """
  459. self._running = False
  460. self._downloader.stop()
  461. def available(self):
  462. """Return True if the worker has no job else False. """
  463. return self._data['url'] is None
  464. def has_index(self, index):
  465. """Return True if index is equal to self._data['index'] else False. """
  466. return self._data['index'] == index
  467. def update_data(self, data):
  468. """Update self._data from the given data. """
  469. if self._wait_for_reply:
  470. # Update data only if a receive request has been issued
  471. for key in data:
  472. self._data[key] = data[key]
  473. self._wait_for_reply = False
  474. @property
  475. def successful(self):
  476. """Return the number of successful downloads for current worker. """
  477. return self._successful
  478. def _reset(self):
  479. """Reset self._data back to the original state. """
  480. for key in self._data:
  481. self._data[key] = None
  482. def _log_data(self, data):
  483. """Callback method for self._downloader.
  484. This method is used to write the given data in a synchronized way
  485. to the log file using the self.log_manager and the self.log_lock.
  486. Args:
  487. data (string): String to write to the log file.
  488. """
  489. if self.log_manager is not None:
  490. self.log_lock.acquire()
  491. self.log_manager.log(data)
  492. self.log_lock.release()
  493. def _data_hook(self, data):
  494. """Callback method for self._downloader.
  495. This method updates self._data and sends the updates back to the
  496. GUI using the self._talk_to_gui() method.
  497. Args:
  498. data (dict): Python dictionary which contains information
  499. about the download process. For more info see the
  500. extract_data() function under the downloaders.py module.
  501. """
  502. ## Temp dictionary which holds the updates
  503. #temp_dict = {}
  504. ## Update each key
  505. #for key in data:
  506. #if self._data[key] != data[key]:
  507. #self._data[key] = data[key]
  508. #temp_dict[key] = data[key]
  509. ## Build the playlist status if there is an update
  510. ## REFACTOR re-implement this on DownloadItem or ListCtrl level?
  511. ##if self._data['playlist_index'] is not None:
  512. ##if 'status' in temp_dict or 'playlist_index' in temp_dict:
  513. ##temp_dict['status'] = '{status} {index}/{size}'.format(
  514. ##status=self._data['status'],
  515. ##index=self._data['playlist_index'],
  516. ##size=self._data['playlist_size']
  517. ##)
  518. #if len(temp_dict):
  519. #self._talk_to_gui('send', temp_dict)
  520. self._talk_to_gui('send', data)
  521. def _talk_to_gui(self, signal, data):
  522. """Communicate with the GUI using wxCallAfter and wxPublisher.
  523. Send/Ask data to/from the GUI. Note that if the signal is 'receive'
  524. then the Worker will wait until it receives a reply from the GUI.
  525. Args:
  526. signal (string): Unique string that informs the GUI about the
  527. communication procedure.
  528. data (dict): Python dictionary which holds the data to be sent
  529. back to the GUI. If the signal is 'send' then the dictionary
  530. contains the updates for the GUI (e.g. percentage, eta). If
  531. the signal is 'receive' then the dictionary contains exactly
  532. three keys. The 'index' (row) from which we want to retrieve
  533. the data, the 'source' which identifies a column in the
  534. wxListCtrl widget and the 'dest' which tells the wxListCtrl
  535. under which key to store the retrieved data.
  536. Note:
  537. Worker class supports 2 signals.
  538. 1) send: The Worker sends data back to the GUI
  539. (e.g. Send status updates).
  540. 2) receive: The Worker asks data from the GUI
  541. (e.g. Receive the name of a file).
  542. Structure:
  543. ('send', {'index': <item_row>, data_to_send*})
  544. ('receive', {'index': <item_row>, 'source': 'source_key', 'dest': 'destination_key'})
  545. """
  546. data['index'] = self._data['index']
  547. if signal == 'receive':
  548. self._wait_for_reply = True
  549. CallAfter(Publisher.sendMessage, WORKER_PUB_TOPIC, (signal, data))