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.

688 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
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
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 responsible for the main app window. """
  4. from __future__ import unicode_literals
  5. import gettext
  6. from os import name as os_name
  7. import wx
  8. from wx.lib.pubsub import setuparg1
  9. from wx.lib.pubsub import pub as Publisher
  10. from wx.lib.mixins.listctrl import ListCtrlAutoWidthMixin
  11. from .optionsframe import OptionsFrame
  12. from .updatemanager import (
  13. UPDATE_PUB_TOPIC,
  14. UpdateThread
  15. )
  16. from .downloadmanager import (
  17. MANAGER_PUB_TOPIC,
  18. WORKER_PUB_TOPIC,
  19. DownloadManager
  20. )
  21. from .utils import (
  22. get_icon_file,
  23. shutdown_sys,
  24. get_time,
  25. open_dir
  26. )
  27. from .info import (
  28. __appname__
  29. )
  30. class MainFrame(wx.Frame):
  31. """Main window class.
  32. This class is responsible for creating the main app window
  33. and binding the events.
  34. Attributes:
  35. wxEVT_TEXT_PASTE (int): Event type code for the wx.EVT_TEXT_PASTE
  36. BUTTONS_SIZE (tuple): Buttons size (width, height).
  37. BUTTONS_SPACE (tuple): Space between buttons (width, height).
  38. SIZE_20 (int): Constant size number.
  39. SIZE_10 (int): Constant size number.
  40. SIZE_5 (int): Constant size number.
  41. Labels area (strings): Strings for the widgets labels.
  42. STATUSLIST_COLUMNS (dict): Python dictionary which holds informations
  43. about the wxListCtrl columns. For more informations read the
  44. comments above the STATUSLIST_COLUMNS declaration.
  45. Args:
  46. opt_manager (optionsmanager.OptionsManager): Object responsible for
  47. handling the settings.
  48. log_manager (logmanager.LogManager): Object responsible for handling
  49. the log stuff.
  50. parent (wx.Window): Frame parent.
  51. """
  52. wxEVT_TEXT_PASTE = 'wxClipboardTextEvent'
  53. BUTTONS_SIZE = (-1, 30)
  54. BUTTONS_SPACE = (80, -1)
  55. SIZE_20 = 20
  56. SIZE_10 = 10
  57. SIZE_5 = 5
  58. # Labels area
  59. URLS_LABEL = _("URLs")
  60. DOWNLOAD_LABEL = _("Download")
  61. UPDATE_LABEL = _("Update")
  62. OPTIONS_LABEL = _("Options")
  63. ERROR_LABEL = _("Error")
  64. STOP_LABEL = _("Stop")
  65. INFO_LABEL = _("Info")
  66. WELCOME_MSG = _("Welcome")
  67. SUCC_REPORT_MSG = _("Successfully downloaded {0} url(s) in {1} "
  68. "day(s) {2} hour(s) {3} minute(s) {4} second(s)")
  69. DL_COMPLETED_MSG = _("Downloads completed")
  70. URL_REPORT_MSG = _("Downloading {0} url(s)")
  71. CLOSING_MSG = _("Stopping downloads")
  72. CLOSED_MSG = _("Downloads stopped")
  73. PROVIDE_URL_MSG = _("You need to provide at least one url")
  74. DOWNLOAD_STARTED = _("Downloads started")
  75. UPDATING_MSG = _("Downloading latest youtube-dl. Please wait...")
  76. UPDATE_ERR_MSG = _("Youtube-dl download failed [{0}]")
  77. UPDATE_SUCC_MSG = _("Youtube-dl downloaded correctly")
  78. OPEN_DIR_ERR = _("Unable to open directory: '{dir}'. "
  79. "The specified path does not exist")
  80. SHUTDOWN_ERR = _("Error while shutting down. "
  81. "Make sure you typed the correct password")
  82. SHUTDOWN_MSG = _("Shutting down system")
  83. VIDEO_LABEL = _("Title")
  84. EXTENSION_LABEL = _("Extension")
  85. SIZE_LABEL = _("Size")
  86. PERCENT_LABEL = _("Percent")
  87. ETA_LABEL = _("ETA")
  88. SPEED_LABEL = _("Speed")
  89. STATUS_LABEL = _("Status")
  90. #################################
  91. # STATUSLIST_COLUMNS
  92. #
  93. # Dictionary which contains the columns for the wxListCtrl widget.
  94. # Each key represents a column and holds informations about itself.
  95. # Structure informations:
  96. # column_key: (column_number, column_label, minimum_width, is_resizable)
  97. #
  98. STATUSLIST_COLUMNS = {
  99. 'filename': (0, VIDEO_LABEL, 150, True),
  100. 'extension': (1, EXTENSION_LABEL, 60, False),
  101. 'filesize': (2, SIZE_LABEL, 80, False),
  102. 'percent': (3, PERCENT_LABEL, 65, False),
  103. 'eta': (4, ETA_LABEL, 45, False),
  104. 'speed': (5, SPEED_LABEL, 90, False),
  105. 'status': (6, STATUS_LABEL, 160, False)
  106. }
  107. def __init__(self, opt_manager, log_manager, parent=None):
  108. wx.Frame.__init__(self, parent, title=__appname__, size=opt_manager.options['main_win_size'])
  109. self.opt_manager = opt_manager
  110. self.log_manager = log_manager
  111. self.download_manager = None
  112. self.update_thread = None
  113. self.app_icon = get_icon_file()
  114. self.Center()
  115. # Create the app icon
  116. if self.app_icon is not None:
  117. self.app_icon = wx.Icon(self.app_icon, wx.BITMAP_TYPE_PNG)
  118. self.SetIcon(self.app_icon)
  119. # Create options frame
  120. self._options_frame = OptionsFrame(self)
  121. # Create components
  122. self._panel = wx.Panel(self)
  123. self._url_text = self._create_statictext(self.URLS_LABEL)
  124. self._url_list = self._create_textctrl(wx.TE_MULTILINE | wx.TE_DONTWRAP, self._on_urllist_edit)
  125. self._download_btn = self._create_button(self.DOWNLOAD_LABEL, self._on_download)
  126. self._update_btn = self._create_button(self.UPDATE_LABEL, self._on_update)
  127. self._options_btn = self._create_button(self.OPTIONS_LABEL, self._on_options)
  128. self._status_list = ListCtrl(self.STATUSLIST_COLUMNS,
  129. parent=self._panel,
  130. style=wx.LC_REPORT | wx.LC_HRULES | wx.LC_VRULES)
  131. self._status_bar = self._create_statictext(self.WELCOME_MSG)
  132. self._set_buttons_width()
  133. # Bind extra events
  134. self.Bind(wx.EVT_CLOSE, self._on_close)
  135. self._set_sizers()
  136. # Set threads wxCallAfter handlers using subscribe
  137. self._set_publisher(self._update_handler, UPDATE_PUB_TOPIC)
  138. self._set_publisher(self._download_worker_handler, WORKER_PUB_TOPIC)
  139. self._set_publisher(self._download_manager_handler, MANAGER_PUB_TOPIC)
  140. def _set_publisher(self, handler, topic):
  141. """Sets a handler for the given topic.
  142. Args:
  143. handler (function): Can be any function with one parameter
  144. the message that the caller sends.
  145. topic (string): Can be any string that identifies the caller.
  146. You can bind multiple handlers on the same topic or
  147. multiple topics on the same handler.
  148. """
  149. Publisher.subscribe(handler, topic)
  150. def _set_buttons_width(self):
  151. """Re-adjust buttons size on runtime so that all buttons
  152. look the same. """
  153. widths = [
  154. self._download_btn.GetSize()[0],
  155. self._update_btn.GetSize()[0],
  156. self._options_btn.GetSize()[0],
  157. ]
  158. max_width = -1
  159. for item in widths:
  160. if item > max_width:
  161. max_width = item
  162. self._download_btn.SetMinSize((max_width, self.BUTTONS_SIZE[1]))
  163. self._update_btn.SetMinSize((max_width, self.BUTTONS_SIZE[1]))
  164. self._options_btn.SetMinSize((max_width, self.BUTTONS_SIZE[1]))
  165. self._panel.Layout()
  166. def _create_statictext(self, label):
  167. statictext = wx.StaticText(self._panel, label=label)
  168. return statictext
  169. def _create_textctrl(self, style=None, event_handler=None):
  170. if style is None:
  171. textctrl = wx.TextCtrl(self._panel)
  172. else:
  173. textctrl = wx.TextCtrl(self._panel, style=style)
  174. if event_handler is not None:
  175. textctrl.Bind(wx.EVT_TEXT_PASTE, event_handler)
  176. textctrl.Bind(wx.EVT_MIDDLE_DOWN, event_handler)
  177. if os_name == 'nt':
  178. # Enable CTRL+A on Windows
  179. def win_ctrla_eventhandler(event):
  180. if event.GetKeyCode() == wx.WXK_CONTROL_A:
  181. event.GetEventObject().SelectAll()
  182. event.Skip()
  183. textctrl.Bind(wx.EVT_CHAR, win_ctrla_eventhandler)
  184. return textctrl
  185. def _create_button(self, label, event_handler=None):
  186. btn = wx.Button(self._panel, label=label, size=self.BUTTONS_SIZE)
  187. if event_handler is not None:
  188. btn.Bind(wx.EVT_BUTTON, event_handler)
  189. return btn
  190. def _create_popup(self, text, title, style):
  191. wx.MessageBox(text, title, style)
  192. def _set_sizers(self):
  193. """Sets the sizers of the main window. """
  194. hor_sizer = wx.BoxSizer(wx.HORIZONTAL)
  195. vertical_sizer = wx.BoxSizer(wx.VERTICAL)
  196. vertical_sizer.AddSpacer(self.SIZE_10)
  197. vertical_sizer.Add(self._url_text)
  198. vertical_sizer.Add(self._url_list, 1, wx.EXPAND)
  199. vertical_sizer.AddSpacer(self.SIZE_10)
  200. buttons_sizer = wx.BoxSizer(wx.HORIZONTAL)
  201. buttons_sizer.Add(self._download_btn)
  202. buttons_sizer.Add(self.BUTTONS_SPACE, 1)
  203. buttons_sizer.Add(self._update_btn)
  204. buttons_sizer.Add(self.BUTTONS_SPACE, 1)
  205. buttons_sizer.Add(self._options_btn)
  206. vertical_sizer.Add(buttons_sizer, flag=wx.ALIGN_CENTER_HORIZONTAL)
  207. vertical_sizer.AddSpacer(self.SIZE_10)
  208. vertical_sizer.Add(self._status_list, 2, wx.EXPAND)
  209. vertical_sizer.AddSpacer(self.SIZE_5)
  210. vertical_sizer.Add(self._status_bar)
  211. vertical_sizer.AddSpacer(self.SIZE_5)
  212. hor_sizer.Add(vertical_sizer, 1, wx.EXPAND | wx.LEFT | wx.RIGHT, border=self.SIZE_20)
  213. self._panel.SetSizer(hor_sizer)
  214. def _update_youtubedl(self):
  215. """Update youtube-dl binary to the latest version. """
  216. self._update_btn.Disable()
  217. self._download_btn.Disable()
  218. self.update_thread = UpdateThread(self.opt_manager.options['youtubedl_path'])
  219. def _status_bar_write(self, msg):
  220. """Display msg in the status bar. """
  221. self._status_bar.SetLabel(msg)
  222. def _reset_widgets(self):
  223. """Resets GUI widgets after update or download process. """
  224. self._download_btn.SetLabel(self.DOWNLOAD_LABEL)
  225. self._download_btn.Enable()
  226. self._update_btn.Enable()
  227. def _print_stats(self):
  228. """Display download stats in the status bar. """
  229. suc_downloads = self.download_manager.successful
  230. dtime = get_time(self.download_manager.time_it_took)
  231. msg = self.SUCC_REPORT_MSG.format(suc_downloads,
  232. dtime['days'],
  233. dtime['hours'],
  234. dtime['minutes'],
  235. dtime['seconds'])
  236. self._status_bar_write(msg)
  237. def _after_download(self):
  238. """Run tasks after download process has been completed.
  239. Note:
  240. Here you can add any tasks you want to run after the
  241. download process has been completed.
  242. """
  243. if self.opt_manager.options['shutdown']:
  244. self.opt_manager.save_to_file()
  245. success = shutdown_sys(self.opt_manager.options['sudo_password'])
  246. if success:
  247. self._status_bar_write(self.SHUTDOWN_MSG)
  248. else:
  249. self._status_bar_write(self.SHUTDOWN_ERR)
  250. else:
  251. self._create_popup(self.DL_COMPLETED_MSG, self.INFO_LABEL, wx.OK | wx.ICON_INFORMATION)
  252. if self.opt_manager.options['open_dl_dir']:
  253. success = open_dir(self.opt_manager.options['save_path'])
  254. if not success:
  255. self._status_bar_write(self.OPEN_DIR_ERR.format(dir=self.opt_manager.options['save_path']))
  256. def _download_worker_handler(self, msg):
  257. """downloadmanager.Worker thread handler.
  258. Handles messages from the Worker thread.
  259. Args:
  260. See downloadmanager.Worker _talk_to_gui() method.
  261. """
  262. signal, data = msg.data
  263. if signal == 'send':
  264. self._status_list.write(data)
  265. if signal == 'receive':
  266. self.download_manager.send_to_worker(self._status_list.get(data))
  267. def _download_manager_handler(self, msg):
  268. """downloadmanager.DownloadManager thread handler.
  269. Handles messages from the DownloadManager thread.
  270. Args:
  271. See downloadmanager.DownloadManager _talk_to_gui() method.
  272. """
  273. data = msg.data
  274. if data == 'finished':
  275. self._print_stats()
  276. self._reset_widgets()
  277. self.download_manager = None
  278. self._after_download()
  279. elif data == 'closed':
  280. self._status_bar_write(self.CLOSED_MSG)
  281. self._reset_widgets()
  282. self.download_manager = None
  283. elif data == 'closing':
  284. self._status_bar_write(self.CLOSING_MSG)
  285. elif data == 'report_active':
  286. # Report number of urls been downloaded
  287. msg = self.URL_REPORT_MSG.format(self.download_manager.active())
  288. self._status_bar_write(msg)
  289. def _update_handler(self, msg):
  290. """updatemanager.UpdateThread thread handler.
  291. Handles messages from the UpdateThread thread.
  292. Args:
  293. See updatemanager.UpdateThread _talk_to_gui() method.
  294. """
  295. data = msg.data
  296. if data[0] == 'download':
  297. self._status_bar_write(self.UPDATING_MSG)
  298. elif data[0] == 'error':
  299. self._status_bar_write(self.UPDATE_ERR_MSG.format(data[1]))
  300. elif data[0] == 'correct':
  301. self._status_bar_write(self.UPDATE_SUCC_MSG)
  302. else:
  303. self._reset_widgets()
  304. self.update_thread = None
  305. def _get_urls(self):
  306. """Returns urls list. """
  307. return self._url_list.GetValue().split('\n')
  308. def _start_download(self):
  309. """Handles pre-download tasks & starts the download process. """
  310. self._status_list.clear()
  311. self._status_list.load_urls(self._get_urls())
  312. if self._status_list.is_empty():
  313. self._create_popup(self.PROVIDE_URL_MSG,
  314. self.ERROR_LABEL,
  315. wx.OK | wx.ICON_EXCLAMATION)
  316. else:
  317. self.download_manager = DownloadManager(self._status_list.get_items(),
  318. self.opt_manager,
  319. self.log_manager)
  320. self._status_bar_write(self.DOWNLOAD_STARTED)
  321. self._download_btn.SetLabel(self.STOP_LABEL)
  322. self._update_btn.Disable()
  323. def _paste_from_clipboard(self):
  324. """Paste the content of the clipboard to the self._url_list widget.
  325. It also adds a new line at the end of the data if not exist.
  326. """
  327. if not wx.TheClipboard.IsOpened():
  328. if wx.TheClipboard.Open():
  329. if wx.TheClipboard.IsSupported(wx.DataFormat(wx.DF_TEXT)):
  330. data = wx.TextDataObject()
  331. wx.TheClipboard.GetData(data)
  332. data = data.GetText()
  333. if data[-1] != '\n':
  334. data += '\n'
  335. self._url_list.WriteText(data)
  336. wx.TheClipboard.Close()
  337. def _on_urllist_edit(self, event):
  338. """Event handler of the self._url_list widget.
  339. This method is triggered when the users pastes text into
  340. the URLs list either by using CTRL+V or by using the middle
  341. click of the mouse.
  342. """
  343. if event.ClassName == self.wxEVT_TEXT_PASTE:
  344. self._paste_from_clipboard()
  345. else:
  346. wx.TheClipboard.UsePrimarySelection(True)
  347. self._paste_from_clipboard()
  348. wx.TheClipboard.UsePrimarySelection(False)
  349. # Dynamically add urls after download process has started
  350. if self.download_manager is not None:
  351. self._status_list.load_urls(self._get_urls(), self.download_manager.add_url)
  352. def _on_download(self, event):
  353. """Event handler of the self._download_btn widget.
  354. This method is used when the download-stop button is pressed to
  355. start or stop the download process.
  356. """
  357. if self.download_manager is None:
  358. self._start_download()
  359. else:
  360. self.download_manager.stop_downloads()
  361. def _on_update(self, event):
  362. """Event handler of the self._update_btn widget.
  363. This method is used when the update button is pressed to start
  364. the update process.
  365. Note:
  366. Currently there is not way to stop the update process.
  367. """
  368. self._update_youtubedl()
  369. def _on_options(self, event):
  370. """Event handler of the self._options_btn widget.
  371. This method is used when the options button is pressed to show
  372. the options window.
  373. """
  374. self._options_frame.load_all_options()
  375. self._options_frame.Show()
  376. def _on_close(self, event):
  377. """Event handler for the wx.EVT_CLOSE event.
  378. This method is used when the user tries to close the program
  379. to save the options and make sure that the download & update
  380. processes are not running.
  381. """
  382. if self.download_manager is not None:
  383. self.download_manager.stop_downloads()
  384. self.download_manager.join()
  385. if self.update_thread is not None:
  386. self.update_thread.join()
  387. # Store main-options frame size
  388. self.opt_manager.options['main_win_size'] = self.GetSize()
  389. self.opt_manager.options['opts_win_size'] = self._options_frame.GetSize()
  390. self._options_frame.save_all_options()
  391. self.opt_manager.save_to_file()
  392. self.Destroy()
  393. class ListCtrl(wx.ListCtrl, ListCtrlAutoWidthMixin):
  394. """Custom ListCtrl widget.
  395. Args:
  396. columns (dict): See MainFrame class STATUSLIST_COLUMNS attribute.
  397. """
  398. def __init__(self, columns, *args, **kwargs):
  399. wx.ListCtrl.__init__(self, *args, **kwargs)
  400. ListCtrlAutoWidthMixin.__init__(self)
  401. self.columns = columns
  402. self._list_index = 0
  403. self._url_list = set()
  404. self._set_columns()
  405. def get(self, data):
  406. """Return data from ListCtrl.
  407. Args:
  408. data (dict): Dictionary which contains three keys. The 'index'
  409. that identifies the current row, the 'source' which identifies
  410. a column in the wxListCtrl and the 'dest' which tells
  411. wxListCtrl under which key to store the retrieved value. For
  412. more informations see the _talk_to_gui() method under
  413. downloadmanager.py Worker class.
  414. Returns:
  415. A dictionary which holds the 'index' (row) and the data from the
  416. given row-column combination.
  417. Example:
  418. args: data = {'index': 0, 'source': 'filename', 'dest': 'new_filename'}
  419. The wxListCtrl will store the value from the 'filename' column
  420. into a new dictionary with a key value 'new_filename'.
  421. return: {'index': 0, 'new_filename': 'The filename retrieved'}
  422. """
  423. value = None
  424. # If the source column exists
  425. if data['source'] in self.columns:
  426. value = self.GetItemText(data['index'], self.columns[data['source']][0])
  427. return {'index': data['index'], data['dest']: value}
  428. def write(self, data):
  429. """Write data on ListCtrl row-column.
  430. Args:
  431. data (dict): Dictionary that contains the data to be
  432. written on the ListCtrl. In order for this method to
  433. write the given data there must be an 'index' key that
  434. identifies the current row. For a valid data dictionary see
  435. Worker class __init__() method under downloadmanager.py module.
  436. """
  437. for key in data:
  438. if key in self.columns:
  439. self._write_data(data['index'], self.columns[key][0], data[key])
  440. def load_urls(self, url_list, func=None):
  441. """Load URLs from the url_list on the ListCtrl widget.
  442. Args:
  443. url_list (list): List of strings that contains the URLs to add.
  444. func (function): Callback function. It's used to add the URLs
  445. on the download_manager.
  446. """
  447. for url in url_list:
  448. url = url.replace(' ', '')
  449. if url and not self.has_url(url):
  450. self.add_url(url)
  451. if func is not None:
  452. # Custom hack to add url into download_manager
  453. item = self._get_item(self._list_index - 1)
  454. func(item)
  455. def has_url(self, url):
  456. """Returns True if the url is aleady in the ListCtrl else False.
  457. Args:
  458. url (string): URL string.
  459. """
  460. return url in self._url_list
  461. def add_url(self, url):
  462. """Adds the given url in the ListCtrl.
  463. Args:
  464. url (string): URL string.
  465. """
  466. self.InsertStringItem(self._list_index, url)
  467. self._url_list.add(url)
  468. self._list_index += 1
  469. def clear(self):
  470. """Clear the ListCtrl widget & reset self._list_index and
  471. self._url_list. """
  472. self.DeleteAllItems()
  473. self._list_index = 0
  474. self._url_list = set()
  475. def is_empty(self):
  476. """Returns True if the list is empty else False. """
  477. return self._list_index == 0
  478. def get_items(self):
  479. """Returns a list of items inside the ListCtrl.
  480. Returns:
  481. List of dictionaries that contains the 'url' and the
  482. 'index'(row) for each item of the ListCtrl.
  483. """
  484. items = []
  485. for row in xrange(self._list_index):
  486. item = self._get_item(row)
  487. items.append(item)
  488. return items
  489. def _write_data(self, row, column, data):
  490. """Write data on row-column. """
  491. if isinstance(data, basestring):
  492. self.SetStringItem(row, column, data)
  493. def _get_item(self, index):
  494. """Returns the corresponding ListCtrl item for the given index.
  495. Args:
  496. index (int): Index that identifies the row of the item.
  497. Index must be smaller than the self._list_index.
  498. Returns:
  499. Dictionary that contains the URL string of the row and the
  500. row number(index).
  501. """
  502. item = self.GetItem(itemId=index, col=0)
  503. data = dict(url=item.GetText(), index=index)
  504. return data
  505. def _set_columns(self):
  506. """Initializes ListCtrl columns.
  507. See MainFrame STATUSLIST_COLUMNS attribute for more info. """
  508. for column_item in sorted(self.columns.values()):
  509. self.InsertColumn(column_item[0], column_item[1], width=wx.LIST_AUTOSIZE_USEHEADER)
  510. # If the column width obtained from wxLIST_AUTOSIZE_USEHEADER
  511. # is smaller than the minimum allowed column width
  512. # then set the column width to the minumum allowed size
  513. if self.GetColumnWidth(column_item[0]) < column_item[2]:
  514. self.SetColumnWidth(column_item[0], column_item[2])
  515. # Set auto-resize if enabled
  516. if column_item[3]:
  517. self.setResizeColumn(column_item[0])