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.

550 lines
18 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
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. """Youtubedlg module responsible for the main app window. """
  3. import gettext
  4. import wx
  5. from wx.lib.pubsub import setuparg1
  6. from wx.lib.pubsub import pub as Publisher
  7. from wx.lib.mixins.listctrl import ListCtrlAutoWidthMixin
  8. from .optionsframe import OptionsFrame
  9. from .updatemanager import (
  10. UPDATE_PUB_TOPIC,
  11. UpdateThread
  12. )
  13. from .downloadmanager import (
  14. MANAGER_PUB_TOPIC,
  15. WORKER_PUB_TOPIC,
  16. DownloadManager
  17. )
  18. from .utils import (
  19. get_icon_file,
  20. shutdown_sys,
  21. get_time,
  22. open_dir
  23. )
  24. from .info import (
  25. __appname__
  26. )
  27. class MainFrame(wx.Frame):
  28. """Main window class.
  29. This class is responsible for creating the main app window
  30. and binding the events.
  31. Attributes:
  32. FRAME_SIZE (tuple): Frame size (width, height).
  33. BUTTONS_SIZE (tuple): Buttons size (width, height).
  34. BUTTONS_SPACE (int): Horizontal space between the buttons.
  35. SIZE_20 (int): Constant size number.
  36. SIZE_10 (int): Constant size number.
  37. SIZE_5 (int): Constant size number.
  38. Labels area (strings): Strings for the widgets labels.
  39. STATUSLIST_COLUMNS (tuple): Tuple of tuples that contains informations
  40. about the ListCtrl columns. First item is the column name. Second
  41. item is the column position. Third item is the column label.
  42. Fourth item is the column default width. Last item is a boolean
  43. flag if True the current column is resizable.
  44. Args:
  45. opt_manager (optionsmanager.OptionsManager): Object responsible for
  46. handling the settings.
  47. log_manager (logmanager.LogManager): Object responsible for handling
  48. the log stuff.
  49. parent (wx.Window): Frame parent.
  50. """
  51. FRAME_SIZE = (700, 490)
  52. BUTTONS_SIZE = (90, 30)
  53. BUTTONS_SPACE = 80
  54. SIZE_20 = 20
  55. SIZE_10 = 10
  56. SIZE_5 = 5
  57. # Labels area
  58. URLS_LABEL = _("URLs")
  59. DOWNLOAD_LABEL = _("Download")
  60. UPDATE_LABEL = _("Update")
  61. OPTIONS_LABEL = _("Options")
  62. ERROR_LABEL = _("Error")
  63. STOP_LABEL = _("Stop")
  64. INFO_LABEL = _("Info")
  65. WELCOME_MSG = _("Welcome")
  66. SUCC_REPORT_MSG = _("Successfully downloaded {0} url(s) in {1} "
  67. "day(s) {2} hour(s) {3} minute(s) {4} second(s)")
  68. DL_COMPLETED_MSG = _("Download completed")
  69. URL_REPORT_MSG = _("Downloading {0} url(s)")
  70. CLOSING_MSG = _("Stopping downloads")
  71. CLOSED_MSG = _("Downloads stopped")
  72. PROVIDE_URL_MSG = _("You need to provide at least one url")
  73. DOWNLOAD_STARTED = _("Download started")
  74. UPDATING_MSG = _("Downloading latest youtube-dl. Please wait...")
  75. UPDATE_ERR_MSG = _("Youtube-dl download failed [{0}]")
  76. UPDATE_SUCC_MSG = _("Youtube-dl downloaded correctly")
  77. VIDEO_LABEL = _("Title")
  78. SIZE_LABEL = _("Size")
  79. PERCENT_LABEL = _("Percent")
  80. ETA_LABEL = _("ETA")
  81. SPEED_LABEL = _("Speed")
  82. STATUS_LABEL = _("Status")
  83. #################################
  84. STATUSLIST_COLUMNS = (
  85. ('filename', 0, VIDEO_LABEL, 150, True),
  86. ('filesize', 1, SIZE_LABEL, 80, False),
  87. ('percent', 2, PERCENT_LABEL, 65, False),
  88. ('eta', 3, ETA_LABEL, 45, False),
  89. ('speed', 4, SPEED_LABEL, 90, False),
  90. ('status', 5, STATUS_LABEL, 160, False)
  91. )
  92. def __init__(self, opt_manager, log_manager, parent=None):
  93. wx.Frame.__init__(self, parent, title=__appname__, size=self.FRAME_SIZE)
  94. self.opt_manager = opt_manager
  95. self.log_manager = log_manager
  96. self.download_manager = None
  97. self.update_thread = None
  98. self.app_icon = get_icon_file()
  99. # Create the app icon
  100. if self.app_icon is not None:
  101. self.app_icon = wx.Icon(self.app_icon, wx.BITMAP_TYPE_PNG)
  102. self.SetIcon(self.app_icon)
  103. # Create options frame
  104. self._options_frame = OptionsFrame(self)
  105. # Create components
  106. self._panel = wx.Panel(self)
  107. self._url_text = self._create_statictext(self.URLS_LABEL)
  108. self._url_list = self._create_textctrl(wx.TE_MULTILINE | wx.TE_DONTWRAP, self._on_urllist_edit)
  109. self._download_btn = self._create_button(self.DOWNLOAD_LABEL, self._on_download)
  110. self._update_btn = self._create_button(self.UPDATE_LABEL, self._on_update)
  111. self._options_btn = self._create_button(self.OPTIONS_LABEL, self._on_options)
  112. self._status_list = ListCtrl(self.STATUSLIST_COLUMNS,
  113. parent=self._panel,
  114. style=wx.LC_REPORT | wx.LC_HRULES | wx.LC_VRULES)
  115. self._status_bar = self._create_statictext(self.WELCOME_MSG)
  116. # Bind extra events
  117. self.Bind(wx.EVT_CLOSE, self._on_close)
  118. self._set_sizers()
  119. # Set threads wxCallAfter handlers using subscribe
  120. self._set_publisher(self._update_handler, UPDATE_PUB_TOPIC)
  121. self._set_publisher(self._status_list_handler, WORKER_PUB_TOPIC)
  122. self._set_publisher(self._download_manager_handler, MANAGER_PUB_TOPIC)
  123. def _set_publisher(self, handler, topic):
  124. """Sets a handler for the given topic.
  125. Args:
  126. handler (function): Can be any function with one parameter
  127. the message that the caller sends.
  128. topic (string): Can be any string that identifies the caller.
  129. You can bind multiple handlers on the same topic or
  130. multiple topics on the same handler.
  131. """
  132. Publisher.subscribe(handler, topic)
  133. def _create_statictext(self, label):
  134. statictext = wx.StaticText(self._panel, label=label)
  135. return statictext
  136. def _create_textctrl(self, style=None, event_handler=None):
  137. if style is None:
  138. textctrl = wx.TextCtrl(self._panel)
  139. else:
  140. textctrl = wx.TextCtrl(self._panel, style=style)
  141. if event_handler is not None:
  142. textctrl.Bind(wx.EVT_TEXT, event_handler)
  143. return textctrl
  144. def _create_button(self, label, event_handler=None):
  145. btn = wx.Button(self._panel, label=label, size=self.BUTTONS_SIZE)
  146. if event_handler is not None:
  147. btn.Bind(wx.EVT_BUTTON, event_handler)
  148. return btn
  149. def _create_popup(self, text, title, style):
  150. wx.MessageBox(text, title, style)
  151. def _set_sizers(self):
  152. """Sets the sizers of the main window. """
  153. hor_sizer = wx.BoxSizer(wx.HORIZONTAL)
  154. vertical_sizer = wx.BoxSizer(wx.VERTICAL)
  155. vertical_sizer.AddSpacer(self.SIZE_10)
  156. vertical_sizer.Add(self._url_text)
  157. vertical_sizer.Add(self._url_list, 1, wx.EXPAND)
  158. vertical_sizer.AddSpacer(self.SIZE_10)
  159. buttons_sizer = wx.BoxSizer(wx.HORIZONTAL)
  160. buttons_sizer.Add(self._download_btn)
  161. buttons_sizer.Add(self._update_btn, flag=wx.LEFT | wx.RIGHT, border=self.BUTTONS_SPACE)
  162. buttons_sizer.Add(self._options_btn)
  163. vertical_sizer.Add(buttons_sizer, flag=wx.ALIGN_CENTER_HORIZONTAL)
  164. vertical_sizer.AddSpacer(self.SIZE_10)
  165. vertical_sizer.Add(self._status_list, 2, wx.EXPAND)
  166. vertical_sizer.AddSpacer(self.SIZE_5)
  167. vertical_sizer.Add(self._status_bar)
  168. vertical_sizer.AddSpacer(self.SIZE_5)
  169. hor_sizer.Add(vertical_sizer, 1, wx.EXPAND | wx.LEFT | wx.RIGHT, border=self.SIZE_20)
  170. self._panel.SetSizer(hor_sizer)
  171. def _update_youtubedl(self):
  172. """Update youtube-dl binary to the latest version. """
  173. self._update_btn.Disable()
  174. self._download_btn.Disable()
  175. self.update_thread = UpdateThread(self.opt_manager.options['youtubedl_path'])
  176. def _status_bar_write(self, msg):
  177. """Display msg in the status bar. """
  178. self._status_bar.SetLabel(msg)
  179. def _reset_widgets(self):
  180. """Resets GUI widgets after update or download process. """
  181. self._download_btn.SetLabel(self.DOWNLOAD_LABEL)
  182. self._download_btn.Enable()
  183. self._update_btn.Enable()
  184. def _print_stats(self):
  185. """Display download stats in the status bar. """
  186. suc_downloads = self.download_manager.successful
  187. dtime = get_time(self.download_manager.time_it_took)
  188. msg = self.SUCC_REPORT_MSG.format(suc_downloads,
  189. dtime['days'],
  190. dtime['hours'],
  191. dtime['minutes'],
  192. dtime['seconds'])
  193. self._status_bar_write(msg)
  194. def _after_download(self):
  195. """Run tasks after download process has been completed.
  196. Note:
  197. Here you can add any tasks you want to run after the
  198. download process has been completed.
  199. """
  200. if self.opt_manager.options['shutdown']:
  201. self.opt_manager.save_to_file()
  202. shutdown_sys(self.opt_manager.options['sudo_password'])
  203. else:
  204. self._create_popup(self.DL_COMPLETED_MSG, self.INFO_LABEL, wx.OK | wx.ICON_INFORMATION)
  205. if self.opt_manager.options['open_dl_dir']:
  206. open_dir(self.opt_manager.options['save_path'])
  207. def _status_list_handler(self, msg):
  208. """downloadmanager.Worker thread handler.
  209. Handles messages from the Worker thread.
  210. Args:
  211. See downloadmanager.Worker _talk_to_gui() method.
  212. """
  213. data = msg.data
  214. self._status_list.write(data)
  215. # Report number of urls been downloaded
  216. msg = self.URL_REPORT_MSG.format(self.download_manager.active())
  217. self._status_bar_write(msg)
  218. def _download_manager_handler(self, msg):
  219. """downloadmanager.DownloadManager thread handler.
  220. Handles messages from the DownloadManager thread.
  221. Args:
  222. See downloadmanager.DownloadManager _talk_to_gui() method.
  223. """
  224. data = msg.data
  225. if data == 'finished':
  226. self._print_stats()
  227. self._reset_widgets()
  228. self.download_manager = None
  229. self._after_download()
  230. elif data == 'closed':
  231. self._status_bar_write(self.CLOSED_MSG)
  232. self._reset_widgets()
  233. self.download_manager = None
  234. else:
  235. self._status_bar_write(self.CLOSING_MSG)
  236. def _update_handler(self, msg):
  237. """updatemanager.UpdateThread thread handler.
  238. Handles messages from the UpdateThread thread.
  239. Args:
  240. See updatemanager.UpdateThread _talk_to_gui() method.
  241. """
  242. data = msg.data
  243. if data[0] == 'download':
  244. self._status_bar_write(self.UPDATING_MSG)
  245. elif data[0] == 'error':
  246. self._status_bar_write(self.UPDATE_ERR_MSG.format(data[1]))
  247. elif data[0] == 'correct':
  248. self._status_bar_write(self.UPDATE_SUCC_MSG)
  249. else:
  250. self._reset_widgets()
  251. self.update_thread = None
  252. def _get_urls(self):
  253. """Returns urls list. """
  254. return self._url_list.GetValue().split('\n')
  255. def _start_download(self):
  256. """Handles pre-download tasks & starts the download process. """
  257. self._status_list.clear()
  258. self._status_list.load_urls(self._get_urls())
  259. if self._status_list.is_empty():
  260. self._create_popup(self.PROVIDE_URL_MSG,
  261. self.ERROR_LABEL,
  262. wx.OK | wx.ICON_EXCLAMATION)
  263. else:
  264. self.download_manager = DownloadManager(self._status_list.get_items(),
  265. self.opt_manager,
  266. self.log_manager)
  267. self._status_bar_write(self.DOWNLOAD_STARTED)
  268. self._download_btn.SetLabel(self.STOP_LABEL)
  269. self._update_btn.Disable()
  270. def _on_urllist_edit(self, event):
  271. """Event handler of the self._status_list widget.
  272. This method is used to dynamically add urls on the download_manager
  273. after the download process has started.
  274. """
  275. if self.download_manager is not None:
  276. self._status_list.load_urls(self._get_urls(), self.download_manager.add_url)
  277. def _on_download(self, event):
  278. """Event handler of the self._download_btn widget.
  279. This method is used when the download-stop button is pressed to
  280. start or stop the download process.
  281. """
  282. if self.download_manager is None:
  283. self._start_download()
  284. else:
  285. self.download_manager.stop_downloads()
  286. def _on_update(self, event):
  287. """Event handler of the self._update_btn widget.
  288. This method is used when the update button is pressed to start
  289. the update process.
  290. Note:
  291. Currently there is not way to stop the update process.
  292. """
  293. self._update_youtubedl()
  294. def _on_options(self, event):
  295. """Event handler of the self._options_btn widget.
  296. This method is used when the options button is pressed to show
  297. the optios window.
  298. """
  299. self._options_frame.load_all_options()
  300. self._options_frame.Show()
  301. def _on_close(self, event):
  302. """Event handler for the wx.EVT_CLOSE event.
  303. This method is used when the user tries to close the program
  304. to save the options and make sure that the download & update
  305. processes are not running.
  306. """
  307. if self.download_manager is not None:
  308. self.download_manager.stop_downloads()
  309. self.download_manager.join()
  310. if self.update_thread is not None:
  311. self.update_thread.join()
  312. self._options_frame.save_all_options()
  313. self.opt_manager.save_to_file()
  314. self.Destroy()
  315. class ListCtrl(wx.ListCtrl, ListCtrlAutoWidthMixin):
  316. """Custom ListCtrl widget.
  317. Args:
  318. columns (tuple): See MainFrame class STATUSLIST_COLUMNS attribute.
  319. """
  320. def __init__(self, columns, *args, **kwargs):
  321. wx.ListCtrl.__init__(self, *args, **kwargs)
  322. ListCtrlAutoWidthMixin.__init__(self)
  323. self.columns = columns
  324. self._list_index = 0
  325. self._url_list = set()
  326. self._set_columns()
  327. def write(self, data):
  328. """Write data on ListCtrl row-column.
  329. Args:
  330. data (dictionary): Dictionary that contains the data to be
  331. written on the ListCtrl. In order for this method to
  332. write the given data there must be an 'index' key that
  333. identifies the current row and a corresponding key for
  334. each item of the self.columns.
  335. Note:
  336. Income data must contain all the columns keys else a KeyError will
  337. be raised. Also there must be an 'index' key that identifies the
  338. row to write the data. For a valid data dictionary see
  339. downloaders.YoutubeDLDownloader self._data.
  340. """
  341. for column in self.columns:
  342. column_key = column[0]
  343. self._write_data(data[column_key], data['index'], column[1])
  344. def load_urls(self, url_list, func=None):
  345. """Load URLs from the url_list on the ListCtrl widget.
  346. Args:
  347. url_list (list): List of strings that contains the URLs to add.
  348. func (function): Callback function. It's used to add the URLs
  349. on the download_manager.
  350. """
  351. for url in url_list:
  352. url = url.replace(' ', '')
  353. if url and not self.has_url(url):
  354. self.add_url(url)
  355. if func is not None:
  356. # Custom hack to add url into download_manager
  357. item = self._get_item(self._list_index - 1)
  358. func(item)
  359. def has_url(self, url):
  360. """Returns True if the url is aleady in the ListCtrl else False.
  361. Args:
  362. url (string): URL string.
  363. """
  364. return url in self._url_list
  365. def add_url(self, url):
  366. """Adds the given url in the ListCtrl.
  367. Args:
  368. url (string): URL string.
  369. """
  370. self.InsertStringItem(self._list_index, url)
  371. self._url_list.add(url)
  372. self._list_index += 1
  373. def clear(self):
  374. """Clear the ListCtrl widget & reset self._list_index and
  375. self._url_list. """
  376. self.DeleteAllItems()
  377. self._list_index = 0
  378. self._url_list = set()
  379. def is_empty(self):
  380. """Returns True if the list is empty else False. """
  381. return self._list_index == 0
  382. def get_items(self):
  383. """Returns a list of items inside the ListCtrl.
  384. Returns:
  385. List of dictionaries that contains the 'url' and the
  386. 'index'(row) for each item of the ListCtrl.
  387. """
  388. items = []
  389. for row in xrange(self._list_index):
  390. item = self._get_item(row)
  391. items.append(item)
  392. return items
  393. def _write_data(self, data, row, column):
  394. """Write data on row-column. """
  395. if isinstance(data, basestring):
  396. self.SetStringItem(row, column, data)
  397. def _get_item(self, index):
  398. """Returns the corresponding ListCtrl item for the given index.
  399. Args:
  400. index (int): Index that identifies the row of the item.
  401. Index must be smaller than the self._list_index.
  402. Returns:
  403. Dictionary that contains the URL string of the row and the
  404. row number(index).
  405. """
  406. item = self.GetItem(itemId=index, col=0)
  407. data = dict(url=item.GetText(), index=index)
  408. return data
  409. def _set_columns(self):
  410. """Initializes ListCtrl columns.
  411. See MainFrame STATUSLIST_COLUMNS attribute for more info. """
  412. for column in self.columns:
  413. self.InsertColumn(column[1], column[2], width=column[3])
  414. if column[4]:
  415. self.setResizeColumn(column[1])