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.

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