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.

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