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.

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