Example #1
0
    def send_files(self, filenames=None):
        # file selection
        self.file_selection = FileSelection()
        if filenames:
            for filename in filenames:
                self.file_selection.file_list.add_file(filename)

        # server status
        self.server_status = ServerStatus(self.qtapp, self.app, web,
                                          self.file_selection)
        self.server_status.server_started.connect(
            self.file_selection.server_started)
        self.server_status.server_started.connect(self.start_server)
        self.server_status.server_stopped.connect(
            self.file_selection.server_stopped)
        self.server_status.server_stopped.connect(self.stop_server)
        self.start_server_finished.connect(self.clear_message)
        self.start_server_finished.connect(
            self.server_status.start_server_finished)
        self.stop_server_finished.connect(
            self.server_status.stop_server_finished)
        self.file_selection.file_list.files_updated.connect(
            self.server_status.update)
        self.server_status.url_copied.connect(self.copy_url)
        self.starting_server_step2.connect(self.start_server_step2)

        # filesize warning
        self.filesize_warning = QtGui.QLabel()
        self.filesize_warning.setStyleSheet(
            'padding: 10px 0; font-weight: bold; color: #333333;')
        self.filesize_warning.hide()

        # downloads
        self.downloads = Downloads()

        # options
        self.options = Options(web)

        # status bar
        self.status_bar = QtGui.QStatusBar()
        self.status_bar.setSizeGripEnabled(False)

        # main layout
        self.layout = QtGui.QVBoxLayout()
        self.layout.addLayout(self.file_selection)
        self.layout.addLayout(self.server_status)
        self.layout.addWidget(self.filesize_warning)
        self.layout.addLayout(self.downloads)
        self.layout.addLayout(self.options)
        self.layout.addWidget(self.status_bar)
        self.setLayout(self.layout)
        self.show()

        # check for requests frequently
        self.timer = QtCore.QTimer()
        QtCore.QObject.connect(self.timer, QtCore.SIGNAL("timeout()"),
                               self.check_for_requests)
        self.timer.start(500)
Example #2
0
    def send_files(self, filenames=None):
        """
        Build the GUI in send files mode.
        Note that this is the only mode currently implemented.
        """
        # file selection
        self.file_selection = FileSelection()
        if filenames:
            for filename in filenames:
                self.file_selection.file_list.add_file(filename)

        # server status
        self.server_status = ServerStatus(self.qtapp, self.app, web, self.file_selection)
        self.server_status.server_started.connect(self.file_selection.server_started)
        self.server_status.server_started.connect(self.start_server)
        self.server_status.server_stopped.connect(self.file_selection.server_stopped)
        self.server_status.server_stopped.connect(self.stop_server)
        self.start_server_finished.connect(self.clear_message)
        self.start_server_finished.connect(self.server_status.start_server_finished)
        self.stop_server_finished.connect(self.server_status.stop_server_finished)
        self.file_selection.file_list.files_updated.connect(self.server_status.update)
        self.server_status.url_copied.connect(self.copy_url)
        self.starting_server_step2.connect(self.start_server_step2)

        # filesize warning
        self.filesize_warning = QtGui.QLabel()
        self.filesize_warning.setStyleSheet('padding: 10px 0; font-weight: bold; color: #333333;')
        self.filesize_warning.hide()

        # downloads
        self.downloads = Downloads()

        # options
        self.options = Options(web, self.app)

        # status bar
        self.status_bar = QtGui.QStatusBar()
        self.status_bar.setSizeGripEnabled(False)

        # main layout
        self.layout = QtGui.QVBoxLayout()
        self.layout.addLayout(self.file_selection)
        self.layout.addLayout(self.server_status)
        self.layout.addWidget(self.filesize_warning)
        self.layout.addLayout(self.downloads)
        self.layout.addLayout(self.options)
        self.layout.addWidget(self.status_bar)
        self.setLayout(self.layout)
        self.show()

        # check for requests frequently
        self.timer = QtCore.QTimer()
        QtCore.QObject.connect(self.timer, QtCore.SIGNAL("timeout()"), self.check_for_requests)
        self.timer.start(500)
Example #3
0
    def __init__(self):
        Gtk.Window.__init__(self, title="YT Downloader")
        self.current = None
        self.data = self.load_config()

        self.download_screen = Downloads()
        self.download_screen.open_folder_button.connect("clicked", self.open_folder)

        self.hbar = hb.Headerbar()
        self.hbar.hbar_download.connect("clicked", self.open_download_screen)
        self.hbar.hbar_settings.connect("clicked", self.open_settings_popup)

        self.set_titlebar(self.hbar)
        
        self.video_window = Video()
        self.video_window.download_video_button.connect("clicked", self.add_to_download_section, "video")
        self.video_window.download_audio_button.connect("clicked", self.add_to_download_section, "audio")       

        self.welcome = wl.Welcome()
        self.open_popup = self.welcome.light
        self.open_popup.get_button.connect("clicked", self.open_click)

        self.add(self.welcome)
Example #4
0
    def send_files(self, filenames=None):
        # file selection
        self.file_selection = FileSelection()
        if filenames:
            for filename in filenames:
                self.file_selection.file_list.add_file(filename)

        # server status
        self.server_status = ServerStatus(self.qtapp, self.app, web, self.file_selection)
        self.server_status.server_started.connect(self.file_selection.server_started)
        self.server_status.server_started.connect(self.start_server)
        self.server_status.server_stopped.connect(self.file_selection.server_stopped)
        self.server_status.server_stopped.connect(self.stop_server)
        self.start_server_finished.connect(self.clear_message)
        self.start_server_finished.connect(self.server_status.start_server_finished)
        self.stop_server_finished.connect(self.server_status.stop_server_finished)
        self.file_selection.file_list.files_updated.connect(self.server_status.update)
        self.server_status.url_copied.connect(self.copy_url)

        # downloads
        self.downloads = Downloads()

        # options
        self.options = Options(web)

        # status bar
        self.status_bar = QtGui.QStatusBar()
        self.status_bar.setSizeGripEnabled(False)

        # main layout
        self.layout = QtGui.QVBoxLayout()
        self.layout.addLayout(self.file_selection)
        self.layout.addLayout(self.server_status)
        self.layout.addLayout(self.downloads)
        self.layout.addLayout(self.options)
        self.layout.addWidget(self.status_bar)
        self.setLayout(self.layout)
        self.show()

        # check for requests frequently
        self.timer = QtCore.QTimer()
        QtCore.QObject.connect(self.timer, QtCore.SIGNAL("timeout()"), self.check_for_requests)
        self.timer.start(500)
Example #5
0
 def __init__(self, search, parent=None):
     QWidget.__init__(self, parent)
     # Load de l'UI
     PyQt4.uic.loadUi('ui/downloads.ui', self)
     # Ajout de la progressBar
     self.progressBar = QProgressBar()
     self.progressBar.setMinimum(0)
     self.progressBar.setMaximum(100)
     self.progressBar.hide()
     self.HLayout = QBoxLayout(QBoxLayout.LeftToRight)
     self.HLayout.addWidget(self.progress_label)
     self.HLayout.addWidget(self.progressBar)
     self.formLayout_3.addRow(self.HLayout)
     # Vars 
     TabDownloads.instance = self
     self.downloads        = Downloads()
     self.pos              = None
     self.download_looked  = None
     # Affichage custom
     #self.downloads_table.setStyleSheet(\
     #        "QTableView::item{ \
     #         border-right-style:solid; \
     #         border-width:0.5; \
     #         border-color: #9B9B9B; \
     #         }")
     # On autorise la creation de menu contextuel
     self.setContextMenuPolicy(Qt.CustomContextMenu)
     # Signaux
     self.customContextMenuRequested.connect(self.contextMenu)
     self.downloads_table.itemClicked.connect(self.show_info_download)
     # Init
     self.load_downloads()
     # On remove les finis et en erreur si Config.clean_dl_list = 1
     if Configuration.clean_dl_list == 1:
         self.clean_list_Action()
     #########################################################
     # On désactive les boutons qui sont pas encore implantés
     self.button_stop_all.setEnabled(False)        
     self.button_resume_all.setEnabled(False)
Example #6
0
    def __init__(self):
        QMainWindow.__init__(self)
        
        self.setWindowTitle(cons.APP_TITLE)
        self.setWindowIcon(QIcon(os.path.join(cons.MEDIA_PATH, "misc", "ochd.ico")))
        self.resize(MIN_WIDTH, MIN_HEIGHT)
        self.center()
        
        self.restore_wnd_geometry()

        self.downloads = Downloads(self)
        self.add_downloads = AddDownloads(self)
        self.log = Log(self)
        
        self.stop = (QToolButton(), media.get_icon(media.STOP, media.MEDIUM), _('Stop Download'), self.on_stop_download, False)
        self.start = (QToolButton(), media.get_icon(media.START, media.MEDIUM), _('Start Download'), self.on_start_download, False)
        self.accounts = (QToolButton(), media.get_icon(media.ACCOUNTS, media.MEDIUM), _('Accounts'), self.on_accounts, True)
        self.preferences = (QToolButton(), media.get_icon(media.PREFERENCES, media.MEDIUM), _('Preferences'), self.on_preferences, True)
        self.about = (QToolButton(), media.get_icon(media.ABOUT, media.MEDIUM), _('About'), self.on_about, True)
        
        self.menu = QMenu()
        self.preferences[BTN].setPopupMode(QToolButton.MenuButtonPopup)
        self.preferences[BTN].setMenu(self.menu)
        
        self.toolbar = Toolbar(self, [self.start, self.stop, None, self.accounts, self.preferences, None, self.about])

        self.addToolBar(self.toolbar)

        #tabs
        self.previous_tab = None
        self.tab = QTabWidget()
        #
        self.tab.addTab(self.downloads, _('Downloads'))
        #
        self.tab_add_downloads = QWidget()
        self.tab_add_downloads.setLayout(self.add_downloads)
        self.tab.addTab(self.tab_add_downloads, _('Add downloads'))
        #
        #addons
        self.addons_manager = AddonsManager(self)
        self.addons_list = self.addons_manager.addons_list
        #...tabs
        self.addon_tab_widgets = []
        self.load_addon_tabs()
        #
        self.tab_log = QWidget()
        self.tab_log.setLayout(self.log)
        self.tab.addTab(self.tab_log, _('Log'))
        #
        self.preferences = Preferences(self.addons_list)
        #self.tab.addTab(self.preferences, 'Preferences')
        #
        self.tab.currentChanged.connect(self.on_tab_switch)
        #
        self.setCentralWidget(self.tab)

        #status bar
        self.status_bar = StatusBar(self)
        self.setStatusBar(self.status_bar)

        #drop down menu
        [addon.set_menu_item() for addon in self.addons_list]
        #self.menu.addSeparator()
        #self.menu.addAction('Preferences', self.on_preferences)

        #system tray icon
        self.tray = Tray(self)
        self.show_or_hide_tray()

        #load session.
        self.load_session()

        #add core's event loop
        self.dispatcher = ThreadDispatcher(self)
        self.dispatcher.start()

        #quit event
        events.quit.connect(self.event_close)

        #custom qt signals
        signals.switch_tab.connect(self.switch_tab)
        signals.show_or_hide_tray.connect(self.show_or_hide_tray)

        self.show()
from downloads import Downloads
from downloads import log2, log
import feedparser
import sys
from optparse import OptionParser


def arguments():
    """ Parse command line arguments """
    parser = OptionParser(usage="usage: %prog [options] --feed=<RSS-Feed-URL>\
                                --output=<PATH-TO-DIRECTORY>",
                          version="%prog 1.0")
    parser.add_option("-f", "--feed", dest="feed", help="rss feed link")
    parser.add_option("-o",
                      "--output",
                      action="store",
                      dest="output",
                      help="download directory")
    (options, args) = parser.parse_args()
    return options


if __name__ == '__main__':
    option = arguments()
    ''' checking for missing argument '''
    log2('getting feed ...' + option.feed)
    d = feedparser.parse(option.feed)
    log2('urls are ...' + str([en['link'] for en in d.entries]))
    Downloads.config(urls=[en['link'] for en in d.entries], path=option.output)
    Downloads.run()
Example #8
0
class Gui(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        
        self.setWindowTitle(cons.APP_TITLE)
        self.setWindowIcon(QIcon(os.path.join(cons.MEDIA_PATH, "misc", "ochd.ico")))
        self.resize(MIN_WIDTH, MIN_HEIGHT)
        self.center()
        
        self.restore_wnd_geometry()

        self.downloads = Downloads(self)
        self.add_downloads = AddDownloads(self)
        self.log = Log(self)
        
        self.stop = (QToolButton(), media.get_icon(media.STOP, media.MEDIUM), _('Stop Download'), self.on_stop_download, False)
        self.start = (QToolButton(), media.get_icon(media.START, media.MEDIUM), _('Start Download'), self.on_start_download, False)
        self.accounts = (QToolButton(), media.get_icon(media.ACCOUNTS, media.MEDIUM), _('Accounts'), self.on_accounts, True)
        self.preferences = (QToolButton(), media.get_icon(media.PREFERENCES, media.MEDIUM), _('Preferences'), self.on_preferences, True)
        self.about = (QToolButton(), media.get_icon(media.ABOUT, media.MEDIUM), _('About'), self.on_about, True)
        
        self.menu = QMenu()
        self.preferences[BTN].setPopupMode(QToolButton.MenuButtonPopup)
        self.preferences[BTN].setMenu(self.menu)
        
        self.toolbar = Toolbar(self, [self.start, self.stop, None, self.accounts, self.preferences, None, self.about])

        self.addToolBar(self.toolbar)

        #tabs
        self.previous_tab = None
        self.tab = QTabWidget()
        #
        self.tab.addTab(self.downloads, _('Downloads'))
        #
        self.tab_add_downloads = QWidget()
        self.tab_add_downloads.setLayout(self.add_downloads)
        self.tab.addTab(self.tab_add_downloads, _('Add downloads'))
        #
        #addons
        self.addons_manager = AddonsManager(self)
        self.addons_list = self.addons_manager.addons_list
        #...tabs
        self.addon_tab_widgets = []
        self.load_addon_tabs()
        #
        self.tab_log = QWidget()
        self.tab_log.setLayout(self.log)
        self.tab.addTab(self.tab_log, _('Log'))
        #
        self.preferences = Preferences(self.addons_list)
        #self.tab.addTab(self.preferences, 'Preferences')
        #
        self.tab.currentChanged.connect(self.on_tab_switch)
        #
        self.setCentralWidget(self.tab)

        #status bar
        self.status_bar = StatusBar(self)
        self.setStatusBar(self.status_bar)

        #drop down menu
        [addon.set_menu_item() for addon in self.addons_list]
        #self.menu.addSeparator()
        #self.menu.addAction('Preferences', self.on_preferences)

        #system tray icon
        self.tray = Tray(self)
        self.show_or_hide_tray()

        #load session.
        self.load_session()

        #add core's event loop
        self.dispatcher = ThreadDispatcher(self)
        self.dispatcher.start()

        #quit event
        events.quit.connect(self.event_close)

        #custom qt signals
        signals.switch_tab.connect(self.switch_tab)
        signals.show_or_hide_tray.connect(self.show_or_hide_tray)

        self.show()

    def customEvent(self, event):
        #process idle_queue_dispacher events
        event.callback()

    def switch_tab(self, index):
        self.tab.setCurrentIndex(index)

    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())
    
    def restore_wnd_geometry(self):
        wx, wy, ww, wh = QDesktopWidget().availableGeometry().getRect()
        x, y, w, h = conf.get_window_settings()
        if ww <= w or wh <= h:
            self.showMaximized()
        elif ww > x >= 0 and wh > y >= 0: #resize and move
            self.setGeometry(x, y, w, h)
        else: #resize only
            self.resize(w, h)

    def on_stop_download(self):
        rows = self.downloads.get_selected_rows()
        if rows:
            for row in rows:
                items = self.downloads.items
                id_item = items[row][0]
                stopped = api.stop_download(id_item)
                if stopped:
                    if items[row][1] == self.downloads.icons_dict[cons.STATUS_QUEUE]:
                        items[row][1] = self.downloads.icons_dict[cons.STATUS_STOPPED]
                    self.stop[BTN].setEnabled(False)
                    self.start[BTN].setEnabled(True)

    def on_start_download(self):
        rows = self.downloads.get_selected_rows()
        if rows:
            for row in rows:
                items = self.downloads.items
                id_item = items[row][0]
                started = api.start_download(id_item)
                if started:
                    items[row][1] = self.downloads.icons_dict[cons.STATUS_QUEUE] #status
                    items[row][10] = None #status_msg
                    self.stop[BTN].setEnabled(True)
                    self.start[BTN].setEnabled(False)
            id_item_list = [row[0] for row in items]
            api.reorder_queue(id_item_list)
    
    def on_accounts(self):
        accounts = ConfigAccounts(self)
    
    def on_preferences(self):
        index_page = self.tab.indexOf(self.preferences) #get the page containig the widget
        if index_page >= 0: #if = -1 there is not such tab.
            self.tab.setCurrentIndex(index_page)
        else:
            index_page = self.tab.addTab(self.preferences, _('Preferences'))
            btn_close = QPushButton(self)
            #btn_close.setIcon(QIcon('stop.png'))
            #btn_close.setIconSize(QSize(10, 10))
            btn_close.setFixedHeight(12)
            btn_close.setFixedWidth(12)
            #btn_close.setFlat(True)
            btn_close.clicked.connect(self.on_close_preferences)
            self.tab.tabBar().setTabButton(index_page, QTabBar.RightSide, btn_close)
            #
            last_index = self.tab.count() - 1
            self.tab.setCurrentIndex(last_index)
    
    def on_close_preferences(self):
        index_page = self.tab.indexOf(self.preferences)
        if index_page >= 0:
            self.tab.removeTab(index_page)
        #self.tab.setCurrentIndex(0)
    
    def on_about(self):
        about = About(self)
    
    def on_tab_switch(self, index):
        current_widget = self.tab.currentWidget()
        if current_widget == self.tab_log:
            self.log.on_load()
        elif current_widget in self.addon_tab_widgets:
            tab = current_widget.layout()
            tab.on_load()

        if self.previous_tab == self.preferences:
            self.previous_tab.on_close()
        elif self.previous_tab in self.addon_tab_widgets:
            tab = self.previous_tab.layout()
            tab.on_close()
        self.previous_tab = current_widget

    def show_or_hide_tray(self):
        if self.tray.is_available() and conf.get_tray_available():
            self.tray.show()
        else:
            self.tray.hide()

    def load_addon_tabs(self):
        for tab, addon in [(addon.get_tab(), addon) for addon in self.addons_list]:
            if tab is not None:
                tab_widget = QWidget()
                tab_widget.setLayout(tab)
                self.tab.addTab(tab_widget, addon.name)
                self.addon_tab_widgets.append(tab_widget)

    def load_session(self):
        """"""
        download_items = api.load_session()
        for download_item in download_items:
            self.downloads.store_item(download_item)
    
    def save_session(self):
        """"""
        id_item_list = [row[0] for row in self.downloads.items]
        api.save_session(id_item_list)
    
    def idle_timeout(self, interval, func):
        timer = QTimer()
        timer.timeout.connect(func)
        timer.start(interval)
        return timer

    def event_close(self):
        self.tray.hide()
        self.close()

    def closeEvent(self, event):
        # overridden
        if not self.tray.isVisible():
            x, y, w, h = self.geometry().getRect()
            self.hide()
            self.save_session()
            self.preferences.on_close()
            self.dispatcher.stop()
            conf.set_window_settings(x, y, w, h)
            conf.save()
            accounts_manager.save()
            event.accept()
        else:  # hide only
            self.hide()
            event.ignore()
Example #9
0
class Gui(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)

        self.setWindowTitle(cons.APP_TITLE)
        self.setWindowIcon(
            QIcon(os.path.join(cons.MEDIA_PATH, "misc", "ochd.ico")))
        self.resize(MIN_WIDTH, MIN_HEIGHT)
        self.center()

        self.restore_wnd_geometry()

        self.stop = (QToolButton(), media.get_icon(media.STOP, media.MEDIUM),
                     _('Stop Download'), self.on_stop_download, False)
        self.start = (QToolButton(), media.get_icon(media.START, media.MEDIUM),
                      _('Start Download'), self.on_start_download, False)
        accounts = (QToolButton(), media.get_icon(media.ACCOUNTS,
                                                  media.MEDIUM), _('Accounts'),
                    self.on_accounts, True)
        preferences = (QToolButton(),
                       media.get_icon(media.PREFERENCES, media.MEDIUM),
                       _('Preferences'), self.on_preferences, True)
        about = (QToolButton(), media.get_icon(media.ABOUT, media.MEDIUM),
                 _('About'), self.on_about, True)

        self.menu = QMenu()
        preferences[BTN].setPopupMode(QToolButton.MenuButtonPopup)
        preferences[BTN].setMenu(self.menu)

        toolbar = Toolbar(
            self,
            [self.start, self.stop, None, accounts, preferences, None, about])

        self.toolbar = self.addToolBar(toolbar)

        #self.vbox = QVBoxLayout(self)

        #tabs
        self.previous_tab = None
        self.tab = QTabWidget(self)
        #
        self.downloads = Downloads(self)
        self.tab.addTab(self.downloads, _('Downloads'))
        #
        self.add_downloads = AddDownloads(self.downloads, self)
        self.tab_add_downloads = QWidget()
        self.tab_add_downloads.setLayout(self.add_downloads)
        self.tab.addTab(self.tab_add_downloads, _('Add downloads'))
        #
        #addons
        self.addons_manager = AddonsManager(self)
        self.addons_list = self.addons_manager.addons_list
        #...tabs
        self.addon_tab_widgets = []
        self.load_addon_tabs()
        #
        self.log = Log()
        self.tab_log = QWidget()
        self.tab_log.setLayout(self.log)
        self.tab.addTab(self.tab_log, _('Log'))
        #
        self.preferences = Preferences(self.addons_list, self)
        #self.tab.addTab(self.preferences, 'Preferences')
        #
        self.tab.currentChanged.connect(self.on_tab_switch)
        #
        self.setCentralWidget(self.tab)

        #status bar
        self.status_bar = StatusBar(self)
        self.setStatusBar(self.status_bar)

        #drop down menu
        [addon.set_menu_item() for addon in self.addons_list]
        #self.menu.addSeparator()
        #self.menu.addAction('Preferences', self.on_preferences)

        #system tray icon
        self.tray = Tray(self)
        if self.tray.available:
            self.can_close = False
        else:
            self.can_close = True

        #on select button state
        self.downloads.selectionModel().selectionChanged.connect(
            self.on_selected)

        #load session.
        self.load_session()

        #add core's event loop
        self.idle_timeout(500, self.queue_loop)

        #quit event
        events.connect(cons.EVENT_QUIT, self.event_close)

        self.show()

    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def restore_wnd_geometry(self):
        wx, wy, ww, wh = QDesktopWidget().availableGeometry().getRect()
        x, y, w, h = conf.get_window_settings()
        if ww <= w or wh <= h:
            self.showMaximized()
        elif ww > x >= 0 and wh > y >= 0:  #resize and move
            self.setGeometry(x, y, w, h)
        else:  #resize only
            self.resize(w, h)

    def on_stop_download(self):
        rows = self.downloads.get_selected_rows()
        if rows:
            for row in rows:
                items = self.downloads.items
                id_item = items[row][0]
                stopped = api.stop_download(id_item)  #return true or false
                if stopped:
                    if items[row][1] == self.downloads.icons_dict[
                            cons.STATUS_QUEUE]:
                        items[row][1] = self.downloads.icons_dict[
                            cons.STATUS_STOPPED]
                    self.stop[BTN].setEnabled(
                        False
                    )  #deshabilitar el boton de stop ya que acaban de detener la descarga.
                    self.start[BTN].setEnabled(True)

    def on_start_download(self):
        rows = self.downloads.get_selected_rows()
        if rows:
            #id_item = model[row][0]
            for row in rows:
                items = self.downloads.items
                id_item = items[row][0]

                #TODO: Implementar lo mismo pero para stopped (buscar en lista stopped y finished para comparar)
                started = api.start_download(id_item)  #return true or false
                if started:
                    items[row][1] = self.downloads.icons_dict[
                        cons.STATUS_QUEUE]  #status
                    items[row][10] = None  #status_msg
                    self.stop[BTN].setEnabled(
                        True
                    )  #deshabilitar el boton de stop ya que acaban de detener la descarga.
                    self.start[BTN].setEnabled(False)

            #self.downloads.get_status() #iniciar update de lista.
            id_item_list = [row[0] for row in items]
            api.reorder_queue(id_item_list)

    def on_accounts(self):
        accounts = ConfigAccounts(self)

    def on_preferences(self):
        index_page = self.tab.indexOf(
            self.preferences)  #get the page containig the widget
        if index_page >= 0:  #if = -1 there is not such tab.
            self.tab.setCurrentIndex(index_page)
        else:
            index_page = self.tab.addTab(self.preferences, _('Preferences'))
            btn_close = QPushButton(self)
            #btn_close.setIcon(QIcon('stop.png'))
            #btn_close.setIconSize(QSize(10, 10))
            btn_close.setFixedHeight(12)
            btn_close.setFixedWidth(12)
            #btn_close.setFlat(True)
            btn_close.clicked.connect(self.on_close_preferences)
            self.tab.tabBar().setTabButton(index_page, QTabBar.RightSide,
                                           btn_close)
            #
            last_index = self.tab.count() - 1
            self.tab.setCurrentIndex(last_index)

    def on_close_preferences(self):
        index_page = self.tab.indexOf(self.preferences)
        if index_page >= 0:
            self.tab.removeTab(index_page)

    def on_about(self):
        about = About(self)

    def on_tab_switch(self, index):
        current_widget = self.tab.currentWidget()
        if current_widget == self.tab_log:
            self.log.on_load()
        elif current_widget in self.addon_tab_widgets:
            tab = current_widget.layout()
            tab.on_load()

        if self.previous_tab == self.preferences:
            self.previous_tab.on_close()
        elif self.previous_tab in self.addon_tab_widgets:
            tab = self.previous_tab.layout()
            tab.on_close()
        self.previous_tab = current_widget

    def on_selected(self, current, previous):
        rows = self.downloads.get_selected_rows()

        self.stop[BTN].setEnabled(False)
        self.start[BTN].setEnabled(False)

        if len(rows) == 1:  #single selection.
            items = self.downloads.items
            row = rows[0]
            id_item = items[row][0]
            self.stop[BTN].setEnabled(True)
            self.start[BTN].setEnabled(False)
            stopped_downloads = api.get_stopped_downloads()
            try:
                item = stopped_downloads[id_item]
                self.stop[BTN].setEnabled(False)
                self.start[BTN].setEnabled(True)
            except KeyError:
                pass
        elif rows:  #multi selection
            self.stop[BTN].setEnabled(True)
            self.start[BTN].setEnabled(True)

    def load_addon_tabs(self):
        for tab, addon in [(addon.get_tab(), addon)
                           for addon in self.addons_list]:
            if tab is not None:
                tab_widget = QWidget()
                tab_widget.setLayout(tab)
                self.tab.addTab(tab_widget, addon.name)
                self.addon_tab_widgets.append(tab_widget)

    def addons_save(self):
        """"""
        [addon.save() for addon in self.addons_list]

    def load_session(self):
        """"""
        ordered_list = api.load_session()
        self.downloads.store_items(ordered_list)

    def save_session(self):
        """"""
        id_item_list = [row[0] for row in self.downloads.items]
        api.save_session(id_item_list)

    def idle_timeout(self, interval, func):
        timer = QTimer(self)
        timer.timeout.connect(func)
        timer.start(interval)
        return timer

    def queue_loop(self):
        try:
            callback = idle_loop.get_nowait()
            callback()
        except Queue.Empty:
            pass

    def event_close(self):
        self.can_close = True
        self.close()

    def closeEvent(self, event):  #overloaded method
        """
        also useful for any QWidget
        """
        if self.can_close:  #if self.canExit():
            x, y, w, h = self.geometry().getRect()
            self.hide()
            self.save_session()
            self.addons_save()
            conf.set_window_settings(x, y, w, h)
            conf.save()
            event.accept()
        else:  #hide only
            self.hide()
            event.ignore()
Example #10
0
    def __init__(self):
        QMainWindow.__init__(self)

        self.setWindowTitle(cons.APP_TITLE)
        self.setWindowIcon(
            QIcon(os.path.join(cons.MEDIA_PATH, "misc", "ochd.ico")))
        self.resize(MIN_WIDTH, MIN_HEIGHT)
        self.center()

        self.restore_wnd_geometry()

        self.stop = (QToolButton(), media.get_icon(media.STOP, media.MEDIUM),
                     _('Stop Download'), self.on_stop_download, False)
        self.start = (QToolButton(), media.get_icon(media.START, media.MEDIUM),
                      _('Start Download'), self.on_start_download, False)
        accounts = (QToolButton(), media.get_icon(media.ACCOUNTS,
                                                  media.MEDIUM), _('Accounts'),
                    self.on_accounts, True)
        preferences = (QToolButton(),
                       media.get_icon(media.PREFERENCES, media.MEDIUM),
                       _('Preferences'), self.on_preferences, True)
        about = (QToolButton(), media.get_icon(media.ABOUT, media.MEDIUM),
                 _('About'), self.on_about, True)

        self.menu = QMenu()
        preferences[BTN].setPopupMode(QToolButton.MenuButtonPopup)
        preferences[BTN].setMenu(self.menu)

        toolbar = Toolbar(
            self,
            [self.start, self.stop, None, accounts, preferences, None, about])

        self.toolbar = self.addToolBar(toolbar)

        #self.vbox = QVBoxLayout(self)

        #tabs
        self.previous_tab = None
        self.tab = QTabWidget(self)
        #
        self.downloads = Downloads(self)
        self.tab.addTab(self.downloads, _('Downloads'))
        #
        self.add_downloads = AddDownloads(self.downloads, self)
        self.tab_add_downloads = QWidget()
        self.tab_add_downloads.setLayout(self.add_downloads)
        self.tab.addTab(self.tab_add_downloads, _('Add downloads'))
        #
        #addons
        self.addons_manager = AddonsManager(self)
        self.addons_list = self.addons_manager.addons_list
        #...tabs
        self.addon_tab_widgets = []
        self.load_addon_tabs()
        #
        self.log = Log()
        self.tab_log = QWidget()
        self.tab_log.setLayout(self.log)
        self.tab.addTab(self.tab_log, _('Log'))
        #
        self.preferences = Preferences(self.addons_list, self)
        #self.tab.addTab(self.preferences, 'Preferences')
        #
        self.tab.currentChanged.connect(self.on_tab_switch)
        #
        self.setCentralWidget(self.tab)

        #status bar
        self.status_bar = StatusBar(self)
        self.setStatusBar(self.status_bar)

        #drop down menu
        [addon.set_menu_item() for addon in self.addons_list]
        #self.menu.addSeparator()
        #self.menu.addAction('Preferences', self.on_preferences)

        #system tray icon
        self.tray = Tray(self)
        if self.tray.available:
            self.can_close = False
        else:
            self.can_close = True

        #on select button state
        self.downloads.selectionModel().selectionChanged.connect(
            self.on_selected)

        #load session.
        self.load_session()

        #add core's event loop
        self.idle_timeout(500, self.queue_loop)

        #quit event
        events.connect(cons.EVENT_QUIT, self.event_close)

        self.show()
Example #11
0
class Gui(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)

        self.setWindowTitle(cons.APP_TITLE)
        self.setWindowIcon(
            QIcon(os.path.join(cons.MEDIA_PATH, "misc", "ochd.ico")))
        self.resize(MIN_WIDTH, MIN_HEIGHT)
        self.center()

        self.restore_wnd_geometry()

        self.downloads = Downloads(self)
        self.add_downloads = AddDownloads(self)
        self.log = Log(self)

        self.stop = (QToolButton(), media.get_icon(media.STOP, media.MEDIUM),
                     _('Stop Download'), self.on_stop_download, False)
        self.start = (QToolButton(), media.get_icon(media.START, media.MEDIUM),
                      _('Start Download'), self.on_start_download, False)
        self.accounts = (QToolButton(),
                         media.get_icon(media.ACCOUNTS, media.MEDIUM),
                         _('Accounts'), self.on_accounts, True)
        self.preferences = (QToolButton(),
                            media.get_icon(media.PREFERENCES, media.MEDIUM),
                            _('Preferences'), self.on_preferences, True)
        self.about = (QToolButton(), media.get_icon(media.ABOUT, media.MEDIUM),
                      _('About'), self.on_about, True)

        self.menu = QMenu()
        self.preferences[BTN].setPopupMode(QToolButton.MenuButtonPopup)
        self.preferences[BTN].setMenu(self.menu)

        self.toolbar = Toolbar(self, [
            self.start, self.stop, None, self.accounts, self.preferences, None,
            self.about
        ])

        self.addToolBar(self.toolbar)

        #tabs
        self.previous_tab = None
        self.tab = QTabWidget()
        #
        self.tab.addTab(self.downloads, _('Downloads'))
        #
        self.tab_add_downloads = QWidget()
        self.tab_add_downloads.setLayout(self.add_downloads)
        self.tab.addTab(self.tab_add_downloads, _('Add downloads'))
        #
        #addons
        self.addons_manager = AddonsManager(self)
        self.addons_list = self.addons_manager.addons_list
        #...tabs
        self.addon_tab_widgets = []
        self.load_addon_tabs()
        #
        self.tab_log = QWidget()
        self.tab_log.setLayout(self.log)
        self.tab.addTab(self.tab_log, _('Log'))
        #
        self.preferences = Preferences(self.addons_list)
        #self.tab.addTab(self.preferences, 'Preferences')
        #
        self.tab.currentChanged.connect(self.on_tab_switch)
        #
        self.setCentralWidget(self.tab)

        #status bar
        self.status_bar = StatusBar(self)
        self.setStatusBar(self.status_bar)

        #drop down menu
        [addon.set_menu_item() for addon in self.addons_list]
        #self.menu.addSeparator()
        #self.menu.addAction('Preferences', self.on_preferences)

        #system tray icon
        self.tray = Tray(self)
        self.show_or_hide_tray()

        #load session.
        self.load_session()

        #add core's event loop
        self.dispatcher = ThreadDispatcher(self)
        self.dispatcher.start()

        #quit event
        events.quit.connect(self.event_close)

        #custom qt signals
        signals.switch_tab.connect(self.switch_tab)
        signals.show_or_hide_tray.connect(self.show_or_hide_tray)

        self.show()

    def customEvent(self, event):
        #process idle_queue_dispacher events
        event.callback()

    def switch_tab(self, index):
        self.tab.setCurrentIndex(index)

    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def restore_wnd_geometry(self):
        wx, wy, ww, wh = QDesktopWidget().availableGeometry().getRect()
        x, y, w, h = conf.get_window_settings()
        if ww <= w or wh <= h:
            self.showMaximized()
        elif ww > x >= 0 and wh > y >= 0:  #resize and move
            self.setGeometry(x, y, w, h)
        else:  #resize only
            self.resize(w, h)

    def on_stop_download(self):
        rows = self.downloads.get_selected_rows()
        if rows:
            for row in rows:
                items = self.downloads.items
                id_item = items[row][0]
                stopped = api.stop_download(id_item)
                if stopped:
                    if items[row][1] == self.downloads.icons_dict[
                            cons.STATUS_QUEUE]:
                        items[row][1] = self.downloads.icons_dict[
                            cons.STATUS_STOPPED]
                    self.stop[BTN].setEnabled(False)
                    self.start[BTN].setEnabled(True)

    def on_start_download(self):
        rows = self.downloads.get_selected_rows()
        if rows:
            for row in rows:
                items = self.downloads.items
                id_item = items[row][0]
                started = api.start_download(id_item)
                if started:
                    items[row][1] = self.downloads.icons_dict[
                        cons.STATUS_QUEUE]  #status
                    items[row][10] = None  #status_msg
                    self.stop[BTN].setEnabled(True)
                    self.start[BTN].setEnabled(False)
            id_item_list = [row[0] for row in items]
            api.reorder_queue(id_item_list)

    def on_accounts(self):
        accounts = ConfigAccounts(self)

    def on_preferences(self):
        index_page = self.tab.indexOf(
            self.preferences)  #get the page containig the widget
        if index_page >= 0:  #if = -1 there is not such tab.
            self.tab.setCurrentIndex(index_page)
        else:
            index_page = self.tab.addTab(self.preferences, _('Preferences'))
            btn_close = QPushButton(self)
            #btn_close.setIcon(QIcon('stop.png'))
            #btn_close.setIconSize(QSize(10, 10))
            btn_close.setFixedHeight(12)
            btn_close.setFixedWidth(12)
            #btn_close.setFlat(True)
            btn_close.clicked.connect(self.on_close_preferences)
            self.tab.tabBar().setTabButton(index_page, QTabBar.RightSide,
                                           btn_close)
            #
            last_index = self.tab.count() - 1
            self.tab.setCurrentIndex(last_index)

    def on_close_preferences(self):
        index_page = self.tab.indexOf(self.preferences)
        if index_page >= 0:
            self.tab.removeTab(index_page)
        #self.tab.setCurrentIndex(0)

    def on_about(self):
        about = About(self)

    def on_tab_switch(self, index):
        current_widget = self.tab.currentWidget()
        if current_widget == self.tab_log:
            self.log.on_load()
        elif current_widget in self.addon_tab_widgets:
            tab = current_widget.layout()
            tab.on_load()

        if self.previous_tab == self.preferences:
            self.previous_tab.on_close()
        elif self.previous_tab in self.addon_tab_widgets:
            tab = self.previous_tab.layout()
            tab.on_close()
        self.previous_tab = current_widget

    def show_or_hide_tray(self):
        if self.tray.is_available() and conf.get_tray_available():
            self.tray.show()
        else:
            self.tray.hide()

    def load_addon_tabs(self):
        for tab, addon in [(addon.get_tab(), addon)
                           for addon in self.addons_list]:
            if tab is not None:
                tab_widget = QWidget()
                tab_widget.setLayout(tab)
                self.tab.addTab(tab_widget, addon.name)
                self.addon_tab_widgets.append(tab_widget)

    def load_session(self):
        """"""
        download_items = api.load_session()
        for download_item in download_items:
            self.downloads.store_item(download_item)

    def save_session(self):
        """"""
        id_item_list = [row[0] for row in self.downloads.items]
        api.save_session(id_item_list)

    def idle_timeout(self, interval, func):
        timer = QTimer()
        timer.timeout.connect(func)
        timer.start(interval)
        return timer

    def event_close(self):
        self.tray.hide()
        self.close()

    def closeEvent(self, event):
        # overridden
        if not self.tray.isVisible():
            x, y, w, h = self.geometry().getRect()
            self.hide()
            self.save_session()
            self.preferences.on_close()
            self.dispatcher.stop()
            conf.set_window_settings(x, y, w, h)
            conf.save()
            accounts_manager.save()
            event.accept()
        else:  # hide only
            self.hide()
            event.ignore()
from downloads import log2 , log
import feedparser
import sys
from optparse import OptionParser


def arguments():
    """ Parse command line arguments """
    parser = OptionParser(usage="usage: %prog [options] --feed=<RSS-Feed-URL>\
                                --output=<PATH-TO-DIRECTORY>",
                          version="%prog 1.0")
    parser.add_option("-f", "--feed",
                      dest="feed",
                      help="rss feed link")
    parser.add_option("-o", "--output",
                      action="store",
                      dest="output",
                      help="download directory")
    (options, args) = parser.parse_args()
    return options


if __name__ == '__main__':
    option = arguments()
    ''' checking for missing argument '''
    log2('getting feed ...' +  option.feed )
    d = feedparser.parse(option.feed) 
    log2('urls are ...' +  str([ en['link']  for en in d.entries ]) )
    Downloads.config( urls = [ en['link']  for en in d.entries ] , path = option.output )
    Downloads.run()
Example #13
0
 def test_config(self):
     Downloads.config( url = 'https://dl.dropboxusercontent.com/u/6160850/downloads.rss', path = '/usr/local/src/testdownload' )
     assert Downloads._url.scheme == 'https'
     assert Downloads._url.host == 'dl.dropboxusercontent.com'
     assert Downloads._url.last == 'downloads.rss'
Example #14
0
 def test_fulldownloadafter(self):
     Downloads.config( url = 'https://dl.dropboxusercontent.com/u/6160850/downloads.rss', path = '/usr/local/src/testdownload' )
     assert Downloads.run() == False
Example #15
0
class OnionShareGui(QtGui.QWidget):
    """
    OnionShareGui is the main window for the GUI that contains all of the
    GUI elements.
    """
    start_server_finished = QtCore.pyqtSignal()
    stop_server_finished = QtCore.pyqtSignal()
    starting_server_step2 = QtCore.pyqtSignal()

    def __init__(self, qtapp, app):
        super(OnionShareGui, self).__init__()
        self.qtapp = qtapp
        self.app = app

        self.setWindowTitle('OnionShare')
        self.setWindowIcon(window_icon)

    def send_files(self, filenames=None):
        """
        Build the GUI in send files mode.
        Note that this is the only mode currently implemented.
        """
        # file selection
        self.file_selection = FileSelection()
        if filenames:
            for filename in filenames:
                self.file_selection.file_list.add_file(filename)

        # server status
        self.server_status = ServerStatus(self.qtapp, self.app, web, self.file_selection)
        self.server_status.server_started.connect(self.file_selection.server_started)
        self.server_status.server_started.connect(self.start_server)
        self.server_status.server_stopped.connect(self.file_selection.server_stopped)
        self.server_status.server_stopped.connect(self.stop_server)
        self.start_server_finished.connect(self.clear_message)
        self.start_server_finished.connect(self.server_status.start_server_finished)
        self.stop_server_finished.connect(self.server_status.stop_server_finished)
        self.file_selection.file_list.files_updated.connect(self.server_status.update)
        self.server_status.url_copied.connect(self.copy_url)
        self.starting_server_step2.connect(self.start_server_step2)

        # filesize warning
        self.filesize_warning = QtGui.QLabel()
        self.filesize_warning.setStyleSheet('padding: 10px 0; font-weight: bold; color: #333333;')
        self.filesize_warning.hide()

        # downloads
        self.downloads = Downloads()

        # options
        self.options = Options(web, self.app)

        # status bar
        self.status_bar = QtGui.QStatusBar()
        self.status_bar.setSizeGripEnabled(False)

        # main layout
        self.layout = QtGui.QVBoxLayout()
        self.layout.addLayout(self.file_selection)
        self.layout.addLayout(self.server_status)
        self.layout.addWidget(self.filesize_warning)
        self.layout.addLayout(self.downloads)
        self.layout.addLayout(self.options)
        self.layout.addWidget(self.status_bar)
        self.setLayout(self.layout)
        self.show()

        # check for requests frequently
        self.timer = QtCore.QTimer()
        QtCore.QObject.connect(self.timer, QtCore.SIGNAL("timeout()"), self.check_for_requests)
        self.timer.start(500)

    def start_server_step2(self):
        """
        Step 2 in starting the onionshare server. This displays the large filesize
        warning, if applicable.
        """
        # warn about sending large files over Tor
        if web.zip_filesize >= 157286400:  # 150mb
            self.filesize_warning.setText(strings._("large_filesize", True))
            self.filesize_warning.show()

    def start_server(self):
        """
        Start the onionshare server. This uses multiple threads to start the Tor hidden
        server and the web app.
        """
        # start the hidden service
        self.status_bar.showMessage(strings._('gui_starting_server1', True))
        self.app.choose_port()
        try:
            self.status_bar.showMessage(strings._('gui_starting_server1', True))
            self.app.start_hidden_service(gui=True)
        except onionshare.hs.NoTor as e:
            alert(e.args[0], QtGui.QMessageBox.Warning)
            self.server_status.stop_server()
            self.status_bar.clearMessage()
            return

        # start onionshare service in new thread
        t = threading.Thread(target=web.start, args=(self.app.port, self.app.stay_open, self.app.transparent_torification))
        t.daemon = True
        t.start()

        # prepare the files for sending in a new thread
        def finish_starting_server(self):
            # prepare files to share
            web.set_file_info(self.file_selection.file_list.filenames)
            self.app.cleanup_filenames.append(web.zip_filename)
            self.starting_server_step2.emit()

            # wait for hs
            if not self.app.hs.supports_ephemeral:
                if not self.app.local_only:
                    self.status_bar.showMessage(strings._('gui_starting_server3', True))
                    self.app.hs.wait_for_hs(self.app.onion_host)

            # done
            self.start_server_finished.emit()

        self.status_bar.showMessage(strings._('gui_starting_server2', True))
        t = threading.Thread(target=finish_starting_server, kwargs={'self': self})
        t.daemon = True
        t.start()

    def stop_server(self):
        """
        Stop the onionshare server.
        """
        if self.server_status.status == self.server_status.STATUS_STARTED:
            web.stop(self.app.port)
        self.app.cleanup()
        self.filesize_warning.hide()
        self.stop_server_finished.emit()

    def check_for_requests(self):
        """
        Check for messages communicated from the web app, and update the GUI accordingly.
        """
        self.update()
        # only check for requests if the server is running
        if self.server_status.status != self.server_status.STATUS_STARTED:
            return

        events = []

        done = False
        while not done:
            try:
                r = web.q.get(False)
                events.append(r)
            except web.Queue.Empty:
                done = True

        for event in events:
            if event["type"] == web.REQUEST_LOAD:
                self.status_bar.showMessage(strings._('download_page_loaded', True))

            elif event["type"] == web.REQUEST_DOWNLOAD:
                self.downloads.add_download(event["data"]["id"], web.zip_filesize)

            elif event["type"] == web.REQUEST_PROGRESS:
                self.downloads.update_download(event["data"]["id"], web.zip_filesize, event["data"]["bytes"])

                # is the download complete?
                if event["data"]["bytes"] == web.zip_filesize:
                    # close on finish?
                    if not web.get_stay_open():
                        self.server_status.stop_server()

            elif event["type"] == web.REQUEST_CANCELED:
                self.downloads.cancel_download(event["data"]["id"])

            elif event["path"] != '/favicon.ico':
                self.status_bar.showMessage('{0:s}: {1:s}'.format(strings._('other_page_loaded', True), event["path"]))

    def copy_url(self):
        """
        When the URL gets copied to the clipboard, display this in the status bar.
        """
        self.status_bar.showMessage(strings._('gui_copied_url', True), 2000)

    def clear_message(self):
        """
        Clear messages from the status bar.
        """
        self.status_bar.clearMessage()
Example #16
0
class TabDownloads(QWidget):
    instance = None

    def __init__(self, search, parent=None):
        QWidget.__init__(self, parent)
        # Load de l'UI
        PyQt4.uic.loadUi('ui/downloads.ui', self)
        # Ajout de la progressBar
        self.progressBar = QProgressBar()
        self.progressBar.setMinimum(0)
        self.progressBar.setMaximum(100)
        self.progressBar.hide()
        self.HLayout = QBoxLayout(QBoxLayout.LeftToRight)
        self.HLayout.addWidget(self.progress_label)
        self.HLayout.addWidget(self.progressBar)
        self.formLayout_3.addRow(self.HLayout)
        # Vars 
        TabDownloads.instance = self
        self.downloads        = Downloads()
        self.pos              = None
        self.download_looked  = None
        # Affichage custom
        #self.downloads_table.setStyleSheet(\
        #        "QTableView::item{ \
        #         border-right-style:solid; \
        #         border-width:0.5; \
        #         border-color: #9B9B9B; \
        #         }")
        # On autorise la creation de menu contextuel
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        # Signaux
        self.customContextMenuRequested.connect(self.contextMenu)
        self.downloads_table.itemClicked.connect(self.show_info_download)
        # Init
        self.load_downloads()
        # On remove les finis et en erreur si Config.clean_dl_list = 1
        if Configuration.clean_dl_list == 1:
            self.clean_list_Action()
        #########################################################
        # On désactive les boutons qui sont pas encore implantés
        self.button_stop_all.setEnabled(False)        
        self.button_resume_all.setEnabled(False)
        #########################################################

    def load_downloads(self):
        import xml.sax
        parser = xml.sax.make_parser()
        parser.setContentHandler(AnalyseDownloads(self.add_downloads))
        try:
            for line in open(os.path.expanduser("~") + '/.pyrex/downloads.xml'):
                parser.feed(line)
            self.downloads.save()
        except:
            pass

    def add_download(self, download):
        # Avant de filtrer on écrit le download
        #self.downloads.append(download) #TODO : pour quand on pourra resume, décommenter la ligne et ramener le save ici
                
        if download.state == 4 or download.progress == 0:
            rows = self.downloads_table.rowCount()
            self.downloads_table.insertRow(rows)
            self.downloads_table.setItem(rows, 0, MyQTableWidgetItem(download.file_share.name, download))
            self.downloads_table.setItem(rows, 1, QTableWidgetItem(download.get_progress()))
            self.downloads_table.setItem(rows, 2, QTableWidgetItem(download.state_str))
            self.downloads_table.setItem(rows, 3, QTableWidgetItem("0 ko/s"))
            self.downloads_table.setItem(rows, 5, QTableWidgetItem(download.date.strftime('%d/%m/%y')))
            self.downloads.append(download)
                    
        # TODO : à modifier probablement quand on aura le resume pour les downloads
        if download.state != 4 and download.progress == 0:
            # Signaux
            download.progressModified.connect(self.update_progress)
            download.stateChanged.connect(self.update_state)
            download.downloadFinished.connect(self.download_finished)
            download.speedModified.connect(self.update_speed)
        
        # On save
        self.downloads.save()
        
    def add_downloads(self, downloads):
        for download in downloads:
          self.add_download(download)
        
    def update_progress(self, download):
        item = self.downloads_table.findItems(download.file_share.name, Qt.MatchExactly)[0]
        row = self.downloads_table.row(item)
        self.downloads_table.item(row, 1).setText(download.get_progress())
        # On update la barre de progression si on est en train de regarder un download
        if self.download_looked == download:
            self.progressBar.setValue(int(download.progress))

    def update_speed(self, download):
        item = self.downloads_table.findItems(download.file_share.name, Qt.MatchExactly)[0]
        row = self.downloads_table.row(item)
        self.downloads_table.item(row, 3).setText(convert_speed_str(download.speed))
        
    def update_state(self, download):
        item = self.downloads_table.findItems(download.file_share.name, Qt.MatchExactly)[0]
        row = self.downloads_table.row(item)
        self.downloads_table.item(row, 2).setText(download.state_str)
        # On save
        self.downloads.save()
        
    def download_finished(self, download):
        if download.read_bytes == download.file_share.size:
            item = self.downloads_table.findItems(download.file_share.name, Qt.MatchExactly)[0]
            row = self.downloads_table.row(item)
            self.downloads_table.item(row, 2).setText("Finished!")
            self.downloads_table.item(row, 3).setText("")
            # On save
            self.downloads.save()
        else:
            print "Erreur dans le téléchargement"
            item = self.downloads_table.findItems(download.file_share.name, Qt.MatchExactly)[0]
            row = self.downloads_table.row(item)
            self.downloads_table.item(row, 2).setText("Error : invalid size :(")
            self.downloads_table.item(row, 3).setText("")
            # On save
            self.downloads.save()
            
    def contextMenu(self, pos):
        self.pos = pos
        menu = QMenu()
        # Actions 
        forceAction         = menu.addAction("Forcer la reprise")
        continueAction      = menu.addAction("Reprise")
        pauseAction         = menu.addAction("Pause")
        openAction          = menu.addAction("Ouvrir")
        abortAction         = menu.addAction("Annuler")
        supprListeAction    = menu.addAction("Supprimer de la liste")
        supprDiskAction     = menu.addAction("Supprimer de la liste et du disque")
        copyAction          = menu.addAction("Copier l'URL")
        searchAction        = menu.addAction("Rechercher des fichiers similaires")
        # On désactive les actions s'il n'y a pas de downloads
        if self.downloads == [] or self.downloads_table.currentRow() < 0:
            forceAction.setEnabled(False)
            continueAction.setEnabled(False)
            pauseAction.setEnabled(False)
            openAction.setEnabled(False)
            abortAction.setEnabled(False)
            supprListeAction.setEnabled(False)
            supprDiskAction.setEnabled(False)
            copyAction.setEnabled(False)
            searchAction.setEnabled(False)
        #########################################################
        # On désactive les boutons qui sont pas encore implantés
        forceAction.setEnabled(False)
        #continueAction.setEnabled(False)
        #pauseAction.setEnabled(False)        
        searchAction.setEnabled(False)        
        #########################################################
        # Signaux
        self.connect(forceAction, SIGNAL('triggered()'), self.force_Action)
        self.connect(continueAction, SIGNAL('triggered()'), self.continue_Action)
        self.connect(pauseAction, SIGNAL('triggered()'), self.pause_Action)
        self.connect(openAction, SIGNAL('triggered()'), self.open_Action)
        self.connect(abortAction, SIGNAL('triggered()'), self.abort_Action)
        self.connect(supprListeAction, SIGNAL('triggered()'), self.suppr_liste_Action)
        self.connect(supprDiskAction, SIGNAL('triggered()'), self.suppr_disk_Action)
        self.connect(copyAction, SIGNAL('triggered()'), self.copy_Action)
        self.connect(searchAction, SIGNAL('triggered()'), self.search_Action)
        # On affiche le menu
        menu.exec_(self.mapToGlobal(pos))
      
    def getDownloads(self):
        rows = self.downloads_table.selectionModel().selectedRows()
        return [self.downloads_table.item(row.row(), 0).download for row in rows]
          
    def force_Action(self):
        print "TODO"
        
    def continue_Action(self):
        for download in self.getDownloads():
            print "Resuming download"
            download.resume()
        self.display_resume_pause()
        
    def pause_Action(self):
        for download in self.getDownloads():
            print "Pausing download"
            download.pause()
        self.display_resume_pause()
        
    def open_Action(self):
        for download in self.getDownloads():
            open_file(download.local_path)
        
    def abort_Action(self):
        for download in self.getDownloads():
            download.stop()
        row = self.downloads_table.currentRow()
        self.downloads_table.item(row, 2).setText(u"Annulé!")
        self.downloads_table.item(row, 3).setText("")
  
    def remove_download(self, download, erase):
        download.stop()
        row = self.downloads_table.currentRow()
        # On supprime la ligne
        self.downloads_table.removeRow(row)
        # On supprime de la liste
        self.downloads.remove(download)    
        # On save
        self.downloads.save()
        if erase:
            try:
                os.remove(download.local_path)
            except OSError:
                try:
                    shutil.rmtree(download.local_path)
                except:
                    print "Erreur dans la suppression du fichier"

    def suppr_liste_Action(self):
        for download in self.getDownload():
            self.remove_download(download, False)
        
    def suppr_disk_Action(self):
        for download in self.getDownloads():
            self.remove_download(download, True)
        
    def copy_Action(self):
        pressPaper = QApplication.clipboard()
        text = '\n'.join([dl.local_path for dl in self.getDownloads()])
        pressPaper.setText(text)
        
    def search_Action(self):
        print "TODO"
        
    def show_info_download(self):
        download = self.getDownloads()[0]
        self.name_label.setText(u"Nom : {}".format(download.file_share.name))
        self.path_label.setText(u"Chemin local : {}".format(download.local_path))
        self.url_label.setText(u"URL : {}".format(download.file_share.url))
        self.size_label.setText(u"Taille : {}".format(download.file_share.str_size))   
        self.progressBar.show()     
        self.progressBar.setValue(int(download.progress))
        self.download_looked = download
        
    def clean_list_Action(self):
        remove_list = []
        for download in self.downloads:
            if download.state == 4 or download.state == 7:
                # On trouve la ligne
                item = self.downloads_table.findItems(download.file_share.name, Qt.MatchExactly)[0]
                row = self.downloads_table.row(item)
                # On la supprime
                self.downloads_table.removeRow(row)
                # On save pour après la boucle for
                remove_list.append(download)
        # On supprime de la liste
        for download in remove_list:
            self.downloads.remove(download)    
        # On save
        self.downloads.save()
                               
    def double_clicked(self, row, col):
        download = self.getDownloads()[0]
        if download:
            open_file(download.local_path)
            
    def display_resume_pause(self):
        downloads = self.getDownloads()
        pause = False
        resume = False
        if downloads:
            for download in downloads:
                if download.state == 5:
                    pause = True
                else:
                    resume = True
            self.button_pause.setEnabled(resume)
            self.button_resume.setEnabled(pause)
                    
    def clicked(self, row, col):
        self.display_resume_pause()    
        
    def resizeEvent(self, event):
        maxSize = self.downloads_table.size().width()
        # Nom Ficher : 24%
        self.downloads_table.horizontalHeader().resizeSection(0, maxSize*.24)
        # Avancement : 22%
        self.downloads_table.horizontalHeader().resizeSection(1, maxSize*.22)
        # Etat : 17%
        self.downloads_table.horizontalHeader().resizeSection(2, maxSize*.17)
        # Vitesse : 13% 
        self.downloads_table.horizontalHeader().resizeSection(3, maxSize*.13)
        # Fin : 12%
        self.downloads_table.horizontalHeader().resizeSection(4, maxSize*.12)
        event.accept()
Example #17
0
class Window(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title="YT Downloader")
        self.current = None
        self.data = self.load_config()

        self.download_screen = Downloads()
        self.download_screen.open_folder_button.connect("clicked", self.open_folder)

        self.hbar = hb.Headerbar()
        self.hbar.hbar_download.connect("clicked", self.open_download_screen)
        self.hbar.hbar_settings.connect("clicked", self.open_settings_popup)

        self.set_titlebar(self.hbar)
        
        self.video_window = Video()
        self.video_window.download_video_button.connect("clicked", self.add_to_download_section, "video")
        self.video_window.download_audio_button.connect("clicked", self.add_to_download_section, "audio")       

        self.welcome = wl.Welcome()
        self.open_popup = self.welcome.light
        self.open_popup.get_button.connect("clicked", self.open_click)

        self.add(self.welcome)

    def open_folder(self, widget):
        os.system("pantheon-files "+self.data['download_path'])

    def load_config(self):
        home_directory = os.path.expanduser("~")
        path = os.path.join(home_directory, ".ytdownloader.json")

        if os.path.isfile(path):
            with open(path) as data_file:    
                self.data = json.load(data_file)
        else:
            temp_download_dir = os.path.join(home_directory, "ytdownloader")
            if os.path.isdir(temp_download_dir) is False:
                os.makedirs(temp_download_dir)
            self.data = {"download_path": temp_download_dir}
            with open(path, 'w') as outfile:
                json.dump(self.data, outfile)
        return self.data

    def open_settings_popup(self, widget):
        from settings import SettingsPopup
        settings_popup = SettingsPopup()
        settings_popup.show()

    def open_download_screen(self, widget=None):
        if self.get_child() == self.download_screen:
            self.remove(self.get_child())
            self.add(self.current)
            self.hbar.hbar_download.set_icon_name("folder-download")
        else:
            self.current = self.get_child()
            self.remove(self.get_child())
            self.add(self.download_screen)
            self.hbar.hbar_download.set_icon_name("edit-undo")

    def open_click(self, widget):
        self.address = self.open_popup.address_input.get_text()
        self.type = self.open_popup.combobox.get_active()

        self.open_popup.vbox.hide()
        self.progressbar = Gtk.Spinner()

        self.progressbar.show()
        self.open_popup.vbox.pack_start(self.progressbar, True, True, 10)
        self.open_popup.vbox.show()
        self.progressbar.start()
        #import threading
        #th = threading.Thread(target=self.get_video)
        #th.start()
        self.get_video()

    def mycb(self, total, recvd, ratio, rate, eta):
        self.download_progressbar.set_fraction(ratio)

    def download_video(self):
        if self.media_type == "video":
            self.video_window.video.videostreams[self.video_window.video_combobox.get_active()].download(filepath=self.data['download_path'], quiet=True, callback=self.mycb)
        elif self.media_type == "audio":
            self.video_window.video.audiostreams[self.video_window.audio_combobox.get_active()].download(filepath=self.data['download_path'], quiet=True, callback=self.mycb)

    def add_to_download_section(self, widget, media_type):
        self.media_type = media_type
        self.download_hbox = Gtk.HBox()
 
        if self.media_type == "audio":
            self.media_type_name = "Audio"
        elif self.media_type == "video":
            self.media_type_name = "Video"

        self.image = Gtk.Image()
        
        self.download_label = Gtk.Label(self.video_window.video.title+" | "+self.media_type_name)
        self.download_progressbar = Gtk.ProgressBar()

        response=requests.get(self.video_window.video.thumb)
        input_stream = Gio.MemoryInputStream.new_from_bytes(GLib.Bytes.new(response.content))             
        pixbuf = GdkPixbuf.Pixbuf.new_from_stream(input_stream, None) 
        self.image.set_from_pixbuf(pixbuf)

        self.download_hbox.pack_start(self.image, False, False, 5)
        self.download_vbox = Gtk.VBox()
        self.download_vbox.pack_start(self.download_label, False, False, 5)
        self.download_vbox.pack_start(self.download_progressbar, False, False, 5)

        self.download_hbox.pack_start(self.download_vbox, True, True, 10)

        self.download_screen.pack_start(self.download_hbox, False, False, 5)
        self.download_screen.show_all()

        self.open_download_screen()

        self.work_thread = threading.Thread(target=self.download_video)
        self.work_thread.start()

    def get_video(self):
        if self.type == 0:
            video = pafy.new(self.address)
      
            self.remove(self.get_child())
            self.open_popup.hide()

            self.video_window.video = video
            self.video_window.video_title.set_text(video.title)
            self.video_window.video_description_label.set_text(video.description)
            self.video_window.video_author_label.set_text(video.author)
            for obj in video.audiostreams:
                self.video_window.audio_store.append([str(obj)])

            for obj in video.videostreams:
                self.video_window.video_store.append([str(obj)])

            self.add(self.video_window)

            response=requests.get(video.bigthumb)
            input_stream = Gio.MemoryInputStream.new_from_bytes(GLib.Bytes.new(response.content))             
            pixbuf = GdkPixbuf.Pixbuf.new_from_stream(input_stream, None) 
            self.video_window.image.set_from_pixbuf(pixbuf)
Example #18
0
class OnionShareGui(QtGui.QWidget):
    start_server_finished = QtCore.pyqtSignal()
    stop_server_finished = QtCore.pyqtSignal()

    def __init__(self, qtapp, app):
        super(OnionShareGui, self).__init__()
        self.qtapp = qtapp
        self.app = app

        self.setWindowTitle('OnionShare')
        self.setWindowIcon(window_icon)

    def send_files(self, filenames=None):
        # file selection
        self.file_selection = FileSelection()
        if filenames:
            for filename in filenames:
                self.file_selection.file_list.add_file(filename)

        # server status
        self.server_status = ServerStatus(self.qtapp, self.app, web, self.file_selection)
        self.server_status.server_started.connect(self.file_selection.server_started)
        self.server_status.server_started.connect(self.start_server)
        self.server_status.server_stopped.connect(self.file_selection.server_stopped)
        self.server_status.server_stopped.connect(self.stop_server)
        self.start_server_finished.connect(self.clear_message)
        self.start_server_finished.connect(self.server_status.start_server_finished)
        self.stop_server_finished.connect(self.server_status.stop_server_finished)
        self.file_selection.file_list.files_updated.connect(self.server_status.update)
        self.server_status.url_copied.connect(self.copy_url)

        # downloads
        self.downloads = Downloads()

        # options
        self.options = Options(web)

        # status bar
        self.status_bar = QtGui.QStatusBar()
        self.status_bar.setSizeGripEnabled(False)

        # main layout
        self.layout = QtGui.QVBoxLayout()
        self.layout.addLayout(self.file_selection)
        self.layout.addLayout(self.server_status)
        self.layout.addLayout(self.downloads)
        self.layout.addLayout(self.options)
        self.layout.addWidget(self.status_bar)
        self.setLayout(self.layout)
        self.show()

        # check for requests frequently
        self.timer = QtCore.QTimer()
        QtCore.QObject.connect(self.timer, QtCore.SIGNAL("timeout()"), self.check_for_requests)
        self.timer.start(500)

    def start_server(self):
        # start the hidden service
        self.status_bar.showMessage(strings._('gui_starting_server', True).format(self.app.port))
        try:
            self.app.choose_port()
            print strings._("connecting_ctrlport").format(self.app.port)
            self.app.start_hidden_service(gui=True)
        except onionshare.NoTor as e:
            alert(e.args[0], QtGui.QMessageBox.Warning)
            self.server_status.stop_server()
            self.status_bar.clearMessage()
            return
        except onionshare.TailsError as e:
            alert(e.args[0], QtGui.QMessageBox.Warning)
            self.server_status.stop_server()
            self.status_bar.clearMessage()
            return

        # start onionshare service in new thread
        t = threading.Thread(target=web.start, args=(self.app.port, self.app.stay_open))
        t.daemon = True
        t.start()

        # prepare the files for sending in a new thread
        def finish_starting_server(self):
            # prepare files to share
            web.set_file_info(self.file_selection.file_list.filenames)
            self.app.cleanup_filenames.append(web.zip_filename)

            # wait for hs
            self.app.wait_for_hs()

            # done
            self.start_server_finished.emit()

        t = threading.Thread(target=finish_starting_server, kwargs={'self':self})
        t.daemon = True
        t.start()

    def stop_server(self):
        if self.server_status.status == self.server_status.STATUS_STARTED:
            web.stop(self.app.port)
        self.app.cleanup()
        self.stop_server_finished.emit()

    def check_for_requests(self):
        self.update()
        # only check for requests if the server is running
        if self.server_status.status != self.server_status.STATUS_STARTED:
            return

        events = []

        done = False
        while not done:
            try:
                r = web.q.get(False)
                events.append(r)
            except web.Queue.Empty:
                done = True

        for event in events:
            if event["type"] == web.REQUEST_LOAD:
                self.status_bar.showMessage(strings._('download_page_loaded', True))

            elif event["type"] == web.REQUEST_DOWNLOAD:
                self.downloads.add_download(event["data"]["id"], web.zip_filesize)

            elif event["type"] == web.REQUEST_PROGRESS:
                self.downloads.update_download(event["data"]["id"], web.zip_filesize, event["data"]["bytes"])

                # is the download complete?
                if event["data"]["bytes"] == web.zip_filesize:
                    # close on finish?
                    if not web.get_stay_open():
                        self.server_status.stop_server()
            
            elif event["path"] != '/favicon.ico':
                self.status_bar.showMessage('{0}: {1}'.format(strings._('other_page_loaded', True), event["path"]))

    def copy_url(self):
        self.status_bar.showMessage(strings._('gui_copied_url', True), 2000)

    def clear_message(self):
        self.status_bar.clearMessage()
Example #19
0
class Gui(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        
        self.setWindowTitle(cons.APP_TITLE)
        self.setWindowIcon(QIcon(os.path.join(cons.MEDIA_PATH, "misc", "ochd.ico")))
        self.resize(MIN_WIDTH, MIN_HEIGHT)
        self.center()
        
        self.restore_wnd_geometry()
        
        self.stop = (QToolButton(), media.get_icon(media.STOP, media.MEDIUM), _('Stop Download'), self.on_stop_download, False)
        self.start = (QToolButton(), media.get_icon(media.START, media.MEDIUM), _('Start Download'), self.on_start_download, False)
        accounts = (QToolButton(), media.get_icon(media.ACCOUNTS, media.MEDIUM), _('Accounts'), self.on_accounts, True)
        preferences = (QToolButton(), media.get_icon(media.PREFERENCES, media.MEDIUM), _('Preferences'), self.on_preferences, True)
        about = (QToolButton(), media.get_icon(media.ABOUT, media.MEDIUM), _('About'), self.on_about, True)
        
        self.menu = QMenu()
        preferences[BTN].setPopupMode(QToolButton.MenuButtonPopup)
        preferences[BTN].setMenu(self.menu)
        
        toolbar = Toolbar(self, [self.start, self.stop, None, accounts, preferences, None, about])

        self.toolbar = self.addToolBar(toolbar)

        #self.vbox = QVBoxLayout(self)
        
        #tabs
        self.previous_tab = None
        self.tab = QTabWidget(self)
        #
        self.downloads = Downloads(self)
        self.tab.addTab(self.downloads, _('Downloads'))
        #
        self.add_downloads = AddDownloads(self.downloads, self)
        self.tab_add_downloads = QWidget()
        self.tab_add_downloads.setLayout(self.add_downloads)
        self.tab.addTab(self.tab_add_downloads, _('Add downloads'))
        #
        #addons
        self.addons_manager = AddonsManager(self)
        self.addons_list = self.addons_manager.addons_list
        #...tabs
        self.addon_tab_widgets = []
        self.load_addon_tabs()
        #
        self.log = Log()
        self.tab_log = QWidget()
        self.tab_log.setLayout(self.log)
        self.tab.addTab(self.tab_log, _('Log'))
        #
        self.preferences = Preferences(self.addons_list, self)
        #self.tab.addTab(self.preferences, 'Preferences')
        #
        self.tab.currentChanged.connect(self.on_tab_switch)
        #
        self.setCentralWidget(self.tab)
        
        #status bar
        self.status_bar = StatusBar(self)
        self.setStatusBar(self.status_bar)
        
        #drop down menu
        [addon.set_menu_item() for addon in self.addons_list]
        #self.menu.addSeparator()
        #self.menu.addAction('Preferences', self.on_preferences)

        #system tray icon
        self.tray = Tray(self)
        if self.tray.available:
            self.can_close = False
        else:
            self.can_close = True

        #on select button state
        self.downloads.selectionModel().selectionChanged.connect(self.on_selected)

        #load session.
        self.load_session()

        #add core's event loop
        self.idle_timeout(500, self.queue_loop)

        #quit event
        events.connect(cons.EVENT_QUIT, self.event_close)
        
        self.show()

    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())
    
    def restore_wnd_geometry(self):
        wx, wy, ww, wh = QDesktopWidget().availableGeometry().getRect()
        x, y, w, h = conf.get_window_settings()
        if ww <= w or wh <= h:
            self.showMaximized()
        elif ww > x >= 0 and wh > y >= 0: #resize and move
            self.setGeometry(x, y, w, h)
        else: #resize only
            self.resize(w, h)
    
    def on_stop_download(self):
        rows = self.downloads.get_selected_rows()
        if rows:
            for row in rows:
                items = self.downloads.items
                id_item = items[row][0]
                stopped = api.stop_download(id_item) #return true or false
                if stopped:
                    if items[row][1] == self.downloads.icons_dict[cons.STATUS_QUEUE]:
                        items[row][1] = self.downloads.icons_dict[cons.STATUS_STOPPED]
                    self.stop[BTN].setEnabled(False) #deshabilitar el boton de stop ya que acaban de detener la descarga.
                    self.start[BTN].setEnabled(True)
    
    def on_start_download(self):
        rows = self.downloads.get_selected_rows()
        if rows:
            #id_item = model[row][0]
            for row in rows:
                items = self.downloads.items
                id_item = items[row][0]

                #TODO: Implementar lo mismo pero para stopped (buscar en lista stopped y finished para comparar)
                started = api.start_download(id_item) #return true or false
                if started:
                    items[row][1] = self.downloads.icons_dict[cons.STATUS_QUEUE] #status
                    items[row][10] = None #status_msg
                    self.stop[BTN].setEnabled(True) #deshabilitar el boton de stop ya que acaban de detener la descarga.
                    self.start[BTN].setEnabled(False)
                
            #self.downloads.get_status() #iniciar update de lista.
            id_item_list = [row[0] for row in items]
            api.reorder_queue(id_item_list)
    
    def on_accounts(self):
        accounts = ConfigAccounts(self)
    
    def on_preferences(self):
        index_page = self.tab.indexOf(self.preferences) #get the page containig the widget
        if index_page >= 0: #if = -1 there is not such tab.
            self.tab.setCurrentIndex(index_page)
        else:
            index_page = self.tab.addTab(self.preferences, _('Preferences'))
            btn_close = QPushButton(self)
            #btn_close.setIcon(QIcon('stop.png'))
            #btn_close.setIconSize(QSize(10, 10))
            btn_close.setFixedHeight(12)
            btn_close.setFixedWidth(12)
            #btn_close.setFlat(True)
            btn_close.clicked.connect(self.on_close_preferences)
            self.tab.tabBar().setTabButton(index_page, QTabBar.RightSide, btn_close)
            #
            last_index = self.tab.count() - 1
            self.tab.setCurrentIndex(last_index)
    
    def on_close_preferences(self):
        index_page = self.tab.indexOf(self.preferences)
        if index_page >= 0:
            self.tab.removeTab(index_page)
    
    def on_about(self):
        about = About(self)
    
    def on_tab_switch(self, index):
        current_widget = self.tab.currentWidget()
        if current_widget == self.tab_log:
            self.log.on_load()
        elif current_widget in self.addon_tab_widgets:
            tab = current_widget.layout()
            tab.on_load()

        if self.previous_tab == self.preferences:
            self.previous_tab.on_close()
        elif self.previous_tab in self.addon_tab_widgets:
            tab = self.previous_tab.layout()
            tab.on_close()
        self.previous_tab = current_widget
    
    def on_selected(self, current, previous):
        rows = self.downloads.get_selected_rows()
        
        self.stop[BTN].setEnabled(False)
        self.start[BTN].setEnabled(False)
        
        if len(rows) == 1: #single selection.
            items = self.downloads.items
            row = rows[0]
            id_item = items[row][0]
            self.stop[BTN].setEnabled(True)
            self.start[BTN].setEnabled(False)
            stopped_downloads = api.get_stopped_downloads()
            try:
                item = stopped_downloads[id_item]
                self.stop[BTN].setEnabled(False)
                self.start[BTN].setEnabled(True)
            except KeyError:
                pass
        elif rows: #multi selection
            self.stop[BTN].setEnabled(True)
            self.start[BTN].setEnabled(True)
    
    def load_addon_tabs(self):
        for tab, addon in [(addon.get_tab(), addon) for addon in self.addons_list]:
            if tab is not None:
                tab_widget = QWidget()
                tab_widget.setLayout(tab)
                self.tab.addTab(tab_widget, addon.name)
                self.addon_tab_widgets.append(tab_widget)

    def addons_save(self):
        """"""
        [addon.save() for addon in self.addons_list]

    def load_session(self):
        """"""
        ordered_list = api.load_session()
        self.downloads.store_items(ordered_list)
    
    def save_session(self):
        """"""
        id_item_list = [row[0] for row in self.downloads.items]
        api.save_session(id_item_list)
    
    def idle_timeout(self, interval, func):
        timer = QTimer(self)
        timer.timeout.connect(func)
        timer.start(interval)
        return timer
    
    def queue_loop(self):
        try:
            callback = idle_loop.get_nowait()
            callback()
        except Queue.Empty:
            pass

    def event_close(self):
        self.can_close = True
        self.close()

    def closeEvent(self, event): #overloaded method
        """
        also useful for any QWidget
        """
        if self.can_close: #if self.canExit():
            x, y, w, h = self.geometry().getRect()
            self.hide()
            self.save_session()
            self.addons_save()
            conf.set_window_settings(x, y, w, h)
            conf.save()
            event.accept()
        else: #hide only
            self.hide()
            event.ignore()
Example #20
0
class OnionShareGui(QtGui.QWidget):
    start_server_finished = QtCore.pyqtSignal()
    stop_server_finished = QtCore.pyqtSignal()
    starting_server_step2 = QtCore.pyqtSignal()

    def __init__(self, qtapp, app):
        super(OnionShareGui, self).__init__()
        self.qtapp = qtapp
        self.app = app

        self.setWindowTitle('OnionShare')
        self.setWindowIcon(window_icon)

    def send_files(self, filenames=None):
        # file selection
        self.file_selection = FileSelection()
        if filenames:
            for filename in filenames:
                self.file_selection.file_list.add_file(filename)

        # server status
        self.server_status = ServerStatus(self.qtapp, self.app, web,
                                          self.file_selection)
        self.server_status.server_started.connect(
            self.file_selection.server_started)
        self.server_status.server_started.connect(self.start_server)
        self.server_status.server_stopped.connect(
            self.file_selection.server_stopped)
        self.server_status.server_stopped.connect(self.stop_server)
        self.start_server_finished.connect(self.clear_message)
        self.start_server_finished.connect(
            self.server_status.start_server_finished)
        self.stop_server_finished.connect(
            self.server_status.stop_server_finished)
        self.file_selection.file_list.files_updated.connect(
            self.server_status.update)
        self.server_status.url_copied.connect(self.copy_url)
        self.starting_server_step2.connect(self.start_server_step2)

        # filesize warning
        self.filesize_warning = QtGui.QLabel()
        self.filesize_warning.setStyleSheet(
            'padding: 10px 0; font-weight: bold; color: #333333;')
        self.filesize_warning.hide()

        # downloads
        self.downloads = Downloads()

        # options
        self.options = Options(web)

        # status bar
        self.status_bar = QtGui.QStatusBar()
        self.status_bar.setSizeGripEnabled(False)

        # main layout
        self.layout = QtGui.QVBoxLayout()
        self.layout.addLayout(self.file_selection)
        self.layout.addLayout(self.server_status)
        self.layout.addWidget(self.filesize_warning)
        self.layout.addLayout(self.downloads)
        self.layout.addLayout(self.options)
        self.layout.addWidget(self.status_bar)
        self.setLayout(self.layout)
        self.show()

        # check for requests frequently
        self.timer = QtCore.QTimer()
        QtCore.QObject.connect(self.timer, QtCore.SIGNAL("timeout()"),
                               self.check_for_requests)
        self.timer.start(500)

    def start_server_step2(self):
        self.status_bar.showMessage(strings._('gui_starting_server3', True))

        # warn about sending large files over Tor
        if web.zip_filesize >= 157286400:  # 150mb
            self.filesize_warning.setText(strings._("large_filesize", True))
            self.filesize_warning.show()

    def start_server(self):
        # start the hidden service
        self.status_bar.showMessage(strings._('gui_starting_server1', True))
        try:
            self.app.choose_port()
            print strings._("connecting_ctrlport").format(self.app.port)
            self.app.start_hidden_service(gui=True)
        except onionshare.NoTor as e:
            alert(e.args[0], QtGui.QMessageBox.Warning)
            self.server_status.stop_server()
            self.status_bar.clearMessage()
            return
        except onionshare.TailsError as e:
            alert(e.args[0], QtGui.QMessageBox.Warning)
            self.server_status.stop_server()
            self.status_bar.clearMessage()
            return

        # start onionshare service in new thread
        t = threading.Thread(target=web.start,
                             args=(self.app.port, self.app.stay_open))
        t.daemon = True
        t.start()

        # prepare the files for sending in a new thread
        def finish_starting_server(self):
            # prepare files to share
            web.set_file_info(self.file_selection.file_list.filenames)
            self.app.cleanup_filenames.append(web.zip_filename)
            self.starting_server_step2.emit()

            # wait for hs
            self.app.wait_for_hs()

            # done
            self.start_server_finished.emit()

        self.status_bar.showMessage(strings._('gui_starting_server2', True))
        t = threading.Thread(target=finish_starting_server,
                             kwargs={'self': self})
        t.daemon = True
        t.start()

    def stop_server(self):
        if self.server_status.status == self.server_status.STATUS_STARTED:
            web.stop(self.app.port)
        self.app.cleanup()
        self.filesize_warning.hide()
        self.stop_server_finished.emit()

    def check_for_requests(self):
        self.update()
        # only check for requests if the server is running
        if self.server_status.status != self.server_status.STATUS_STARTED:
            return

        events = []

        done = False
        while not done:
            try:
                r = web.q.get(False)
                events.append(r)
            except web.Queue.Empty:
                done = True

        for event in events:
            if event["type"] == web.REQUEST_LOAD:
                self.status_bar.showMessage(
                    strings._('download_page_loaded', True))

            elif event["type"] == web.REQUEST_DOWNLOAD:
                self.downloads.add_download(event["data"]["id"],
                                            web.zip_filesize)

            elif event["type"] == web.REQUEST_PROGRESS:
                self.downloads.update_download(event["data"]["id"],
                                               web.zip_filesize,
                                               event["data"]["bytes"])

                # is the download complete?
                if event["data"]["bytes"] == web.zip_filesize:
                    # close on finish?
                    if not web.get_stay_open():
                        self.server_status.stop_server()

            elif event["type"] == web.REQUEST_CANCELED:
                self.downloads.cancel_download(event["data"]["id"])

            elif event["path"] != '/favicon.ico':
                self.status_bar.showMessage('{0}: {1}'.format(
                    strings._('other_page_loaded', True), event["path"]))

    def copy_url(self):
        self.status_bar.showMessage(strings._('gui_copied_url', True), 2000)

    def clear_message(self):
        self.status_bar.clearMessage()
Example #21
0
class OnionShareGui(QtGui.QWidget):
    """
    OnionShareGui is the main window for the GUI that contains all of the
    GUI elements.
    """
    start_server_finished = QtCore.pyqtSignal()
    stop_server_finished = QtCore.pyqtSignal()
    starting_server_step2 = QtCore.pyqtSignal()

    def __init__(self, qtapp, app):
        super(OnionShareGui, self).__init__()
        self.qtapp = qtapp
        self.app = app

        self.setWindowTitle('OnionShare')
        self.setWindowIcon(window_icon)

    def send_files(self, filenames=None):
        """
        Build the GUI in send files mode.
        Note that this is the only mode currently implemented.
        """
        # file selection
        self.file_selection = FileSelection()
        if filenames:
            for filename in filenames:
                self.file_selection.file_list.add_file(filename)

        # server status
        self.server_status = ServerStatus(self.qtapp, self.app, web,
                                          self.file_selection)
        self.server_status.server_started.connect(
            self.file_selection.server_started)
        self.server_status.server_started.connect(self.start_server)
        self.server_status.server_stopped.connect(
            self.file_selection.server_stopped)
        self.server_status.server_stopped.connect(self.stop_server)
        self.start_server_finished.connect(self.clear_message)
        self.start_server_finished.connect(
            self.server_status.start_server_finished)
        self.stop_server_finished.connect(
            self.server_status.stop_server_finished)
        self.file_selection.file_list.files_updated.connect(
            self.server_status.update)
        self.server_status.url_copied.connect(self.copy_url)
        self.starting_server_step2.connect(self.start_server_step2)

        # filesize warning
        self.filesize_warning = QtGui.QLabel()
        self.filesize_warning.setStyleSheet(
            'padding: 10px 0; font-weight: bold; color: #333333;')
        self.filesize_warning.hide()

        # downloads
        self.downloads = Downloads()

        # options
        self.options = Options(web, self.app)

        # status bar
        self.status_bar = QtGui.QStatusBar()
        self.status_bar.setSizeGripEnabled(False)

        # main layout
        self.layout = QtGui.QVBoxLayout()
        self.layout.addLayout(self.file_selection)
        self.layout.addLayout(self.server_status)
        self.layout.addWidget(self.filesize_warning)
        self.layout.addLayout(self.downloads)
        self.layout.addLayout(self.options)
        self.layout.addWidget(self.status_bar)
        self.setLayout(self.layout)
        self.show()

        # check for requests frequently
        self.timer = QtCore.QTimer()
        QtCore.QObject.connect(self.timer, QtCore.SIGNAL("timeout()"),
                               self.check_for_requests)
        self.timer.start(500)

    def start_server_step2(self):
        """
        Step 2 in starting the onionshare server. This displays the large filesize
        warning, if applicable.
        """
        # warn about sending large files over Tor
        if web.zip_filesize >= 157286400:  # 150mb
            self.filesize_warning.setText(strings._("large_filesize", True))
            self.filesize_warning.show()

    def start_server(self):
        """
        Start the onionshare server. This uses multiple threads to start the Tor hidden
        server and the web app.
        """
        # start the hidden service
        self.status_bar.showMessage(strings._('gui_starting_server1', True))
        self.app.choose_port()
        try:
            self.status_bar.showMessage(strings._('gui_starting_server1',
                                                  True))
            self.app.start_hidden_service(gui=True)
        except onionshare.hs.NoTor as e:
            alert(e.args[0], QtGui.QMessageBox.Warning)
            self.server_status.stop_server()
            self.status_bar.clearMessage()
            return

        # start onionshare service in new thread
        t = threading.Thread(target=web.start,
                             args=(self.app.port, self.app.stay_open,
                                   self.app.transparent_torification))
        t.daemon = True
        t.start()

        # prepare the files for sending in a new thread
        def finish_starting_server(self):
            # prepare files to share
            web.set_file_info(self.file_selection.file_list.filenames)
            self.app.cleanup_filenames.append(web.zip_filename)
            self.starting_server_step2.emit()

            # wait for hs
            if not self.app.local_only:
                if not self.app.hs.supports_ephemeral:
                    self.status_bar.showMessage(
                        strings._('gui_starting_server3', True))
                    self.app.hs.wait_for_hs(self.app.onion_host)

            # done
            self.start_server_finished.emit()

        self.status_bar.showMessage(strings._('gui_starting_server2', True))
        t = threading.Thread(target=finish_starting_server,
                             kwargs={'self': self})
        t.daemon = True
        t.start()

    def stop_server(self):
        """
        Stop the onionshare server.
        """
        if self.server_status.status != self.server_status.STATUS_STOPPED:
            web.stop(self.app.port)
        self.app.cleanup()
        self.filesize_warning.hide()
        self.stop_server_finished.emit()

    def check_for_requests(self):
        """
        Check for messages communicated from the web app, and update the GUI accordingly.
        """
        self.update()
        # only check for requests if the server is running
        if self.server_status.status != self.server_status.STATUS_STARTED:
            return

        events = []

        done = False
        while not done:
            try:
                r = web.q.get(False)
                events.append(r)
            except web.Queue.Empty:
                done = True

        for event in events:
            if event["type"] == web.REQUEST_LOAD:
                self.status_bar.showMessage(
                    strings._('download_page_loaded', True))

            elif event["type"] == web.REQUEST_DOWNLOAD:
                self.downloads.add_download(event["data"]["id"],
                                            web.zip_filesize)

            elif event["type"] == web.REQUEST_PROGRESS:
                self.downloads.update_download(event["data"]["id"],
                                               web.zip_filesize,
                                               event["data"]["bytes"])

                # is the download complete?
                if event["data"]["bytes"] == web.zip_filesize:
                    # close on finish?
                    if not web.get_stay_open():
                        self.server_status.stop_server()

            elif event["type"] == web.REQUEST_CANCELED:
                self.downloads.cancel_download(event["data"]["id"])

            elif event["path"] != '/favicon.ico':
                self.status_bar.showMessage('{0:s}: {1:s}'.format(
                    strings._('other_page_loaded', True), event["path"]))

    def copy_url(self):
        """
        When the URL gets copied to the clipboard, display this in the status bar.
        """
        self.status_bar.showMessage(strings._('gui_copied_url', True), 2000)

    def clear_message(self):
        """
        Clear messages from the status bar.
        """
        self.status_bar.clearMessage()