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.

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