Пример #1
0
    def _create_callback(self):
        callback = ProgressCallbackWidget(self._parent)
        callback.set_title_text(_('Downloading...'))
        callback.set_label_text(_('Downloading files...'))
        callback.set_updated_text(_('Downloading subtitle {0} ({1}/{2})'))
        callback.set_finished_text(
            _('{0} from {1} subtitles downloaded successfully'))
        callback.set_block(True)
        callback.set_range(0, len(self._rsubtitles))

        callback.show()
        return callback
Пример #2
0
    def onButtonDownload(self):
        # We download the subtitle in the same folder than the video
        subs = self.videoModel.get_checked_subtitles()
        replace_all = False
        skip_all = False
        if not subs:
            QMessageBox.about(self, _("Error"),
                              _("No subtitles selected to be downloaded"))
            return
        total_subs = len(subs)
        answer = None
        success_downloaded = 0

        # FIXME: must pass mainwindow as argument to ProgressCallbackWidget
        callback = ProgressCallbackWidget(self)
        callback.set_title_text(_("Downloading..."))
        callback.set_label_text(_("Downloading files..."))
        callback.set_updated_text(_("Downloading subtitle {0} ({1}/{2})"))
        callback.set_finished_text(
            _("{0} from {1} subtitles downloaded successfully"))
        callback.set_block(True)
        callback.set_range(0, total_subs)

        callback.show()

        for i, sub in enumerate(subs):
            if callback.canceled():
                break
            destinationPath = self.get_state().getDownloadPath(self, sub)
            if not destinationPath:
                break
            log.debug("Trying to download subtitle '%s'" % destinationPath)
            callback.update(i,
                            QFileInfo(destinationPath).fileName(), i + 1,
                            total_subs)

            # Check if we have write permissions, otherwise show warning window
            while True:
                # If the file and the folder don't have write access.
                if not QFileInfo(
                        destinationPath).isWritable() and not QFileInfo(
                            QFileInfo(destinationPath).absoluteDir().path()
                        ).isWritable():
                    warningBox = QMessageBox(
                        _("Error write permission"),
                        _("%s cannot be saved.\nCheck that the folder exists and you have write-access permissions."
                          ) % destinationPath, QMessageBox.Warning,
                        QMessageBox.Retry | QMessageBox.Default,
                        QMessageBox.Discard | QMessageBox.Escape,
                        QMessageBox.NoButton, self)

                    saveAsButton = warningBox.addButton(
                        _("Save as..."), QMessageBox.ActionRole)
                    answer = warningBox.exec_()
                    if answer == QMessageBox.Retry:
                        continue
                    elif answer == QMessageBox.Discard:
                        break  # Let's get out from the While true
                    # If we choose the SAVE AS
                    elif answer == QMessageBox.NoButton:
                        fileName, t = QFileDialog.getSaveFileName(
                            self, _("Save subtitle as..."), destinationPath,
                            'All (*.*)')
                        if fileName:
                            destinationPath = fileName
                else:  # If we have write access we leave the while loop.
                    break

            # If we have chosen Discard subtitle button.
            if answer == QMessageBox.Discard:
                continue  # Continue the next subtitle

            optionWhereToDownload = QSettings().value(
                "options/whereToDownload", "SAME_FOLDER")
            # Check if doesn't exists already, otherwise show fileExistsBox
            # dialog
            if QFileInfo(destinationPath).exists(
            ) and not replace_all and not skip_all and optionWhereToDownload != "ASK_FOLDER":
                # The "remote filename" below is actually not the real filename. Real name could be confusing
                # since we always rename downloaded sub to match movie
                # filename.
                fileExistsBox = QMessageBox(
                    QMessageBox.Warning, _("File already exists"),
                    _("Local: {local}\n\nRemote: {remote}\n\nHow would you like to proceed?"
                      ).format(local=destinationPath,
                               remote=QFileInfo(destinationPath).fileName()),
                    QMessageBox.NoButton, self)
                skipButton = fileExistsBox.addButton(_("Skip"),
                                                     QMessageBox.ActionRole)
                #                    skipAllButton = fileExistsBox.addButton(_("Skip all"), QMessageBox.ActionRole)
                replaceButton = fileExistsBox.addButton(
                    _("Replace"), QMessageBox.ActionRole)
                replaceAllButton = fileExistsBox.addButton(
                    _("Replace all"), QMessageBox.ActionRole)
                saveAsButton = fileExistsBox.addButton(_("Save as..."),
                                                       QMessageBox.ActionRole)
                cancelButton = fileExistsBox.addButton(_("Cancel"),
                                                       QMessageBox.ActionRole)
                fileExistsBox.exec_()
                answer = fileExistsBox.clickedButton()
                if answer == replaceAllButton:
                    # Don't ask us again (for this batch of files)
                    replace_all = True
                elif answer == saveAsButton:
                    # We will find a uniqiue filename and suggest this to user.
                    # add .<lang> to (inside) the filename. If that is not enough, start adding numbers.
                    # There should also be a preferences setting "Autorename
                    # files" or similar ( =never ask) FIXME
                    suggBaseName, suggFileExt = os.path.splitext(
                        destinationPath)
                    fNameCtr = 0  # Counter used to generate a unique filename
                    suggestedFileName = suggBaseName + '.' + \
                        sub.get_language().xxx() + suggFileExt
                    while (os.path.exists(suggestedFileName)):
                        fNameCtr += 1
                        suggestedFileName = suggBaseName + '.' + \
                            sub.get_language().xxx() + '-' + \
                            str(fNameCtr) + suggFileExt
                    fileName, t = QFileDialog.getSaveFileName(
                        None, _("Save subtitle as..."), suggestedFileName,
                        'All (*.*)')
                    if fileName:
                        destinationPath = fileName
                    else:
                        # Skip this particular file if no filename chosen
                        continue
                elif answer == skipButton:
                    continue  # Skip this particular file
#                    elif answer == skipAllButton:
#                        count += percentage
#                        skip_all = True # Skip all files already downloaded
#                        continue
                elif answer == cancelButton:
                    break  # Break out of DL loop - cancel was pushed
            QCoreApplication.processEvents()
            # FIXME: redundant update?
            callback.update(i,
                            QFileInfo(destinationPath).fileName(), i + 1,
                            total_subs)
            try:
                if not skip_all:
                    log.debug("Downloading subtitle '%s'" % destinationPath)
                    download_callback = ProgressCallback()  # FIXME
                    data_stream = sub.download(
                        provider_instance=self.get_state().get_OSDBServer(),
                        callback=download_callback,
                    )
                    write_stream(data_stream, destinationPath)
            except Exception as e:
                log.exception('Unable to Download subtitle {}'.format(
                    sub.get_filename()))
                QMessageBox.about(
                    self, _("Error"),
                    _("Unable to download subtitle %s") % sub.get_filename())
        callback.finish(success_downloaded, total_subs)
Пример #3
0
    def onButtonDownloadByTitle(self):
        subs = self.moviesModel.get_checked_subtitles()
        total_subs = len(subs)
        if not subs:
            QMessageBox.about(
                self, _("Error"), _("No subtitles selected to be downloaded"))
            return

        settings = QSettings()
        path = settings.value("mainwindow/workingDirectory", "")
        zipDestDir = QFileDialog.getExistingDirectory(
            self, _("Select the directory where to save the subtitle(s)"), path)
        if not zipDestDir:
            return
        if zipDestDir:
            settings.setValue("mainwindow/workingDirectory", zipDestDir)

        callback = ProgressCallbackWidget(self)

        callback.set_title_text(_('Downloading'))
        callback.set_label_text(_("Downloading files..."))
        callback.set_updated_text(_("Downloading {0} to {1}"))
        callback.set_block(True)

        callback.set_range(0, len(subs))

        callback.show()

        dlOK = 0
        writtenOK = 0

        for i, sub in enumerate(subs):
            # Skip rest of loop if Abort was pushed in progress bar
            if callback.canceled():
                break

            srt_filename = "sub-" + sub.get_id_online() + ".srt"
            srt_path = os.path.join(zipDestDir, srt_filename)

            log.debug("About to download %s %s to %s" % (i, sub.__repr__, srt_path))
            log.debug("IdFileOnline: %s" % (sub.get_id_online()))
            callback.update(i, sub.get_id_online(), zipDestDir)

            try:
                data_stream = sub.download(provider_instance=self.get_state().get_OSDBServer(), callback=callback)
                dlOK += 1
            except Exception:
                log.warning('Unable to download subtitle with id={subtitle_id}'.format(subtitle_id=sub.get_id_online()),
                          exc_info=sys.exc_info())
                QMessageBox.about(self, _('Error'), _('Unable to download subtitle with id={subtitle_id}').format(
                    subtitle_id=sub.get_id_online()))
                continue
            try:
                write_stream(data_stream, srt_path)
                writtenOK += 1
            except Exception:
                log.warning('Unable to write subtitle to disk. path={path}'.format(path=zipDestFile), exc_info=sys.exc_info())
            QCoreApplication.processEvents()
        callback.finish()
        if dlOK:
            QMessageBox.about(
                self,
                _("{} subtitles downloaded successfully").format(writtenOK),
                _("{} subtitles downloaded successfully").format(writtenOK))
Пример #4
0
    def onButtonDownloadByTitle(self):
        subs = self.moviesModel.getCheckedSubtitles()
        total_subs = len(subs)
        if not subs:
            QMessageBox.about(self, _("Error"),
                              _("No subtitles selected to be downloaded"))
            return

        settings = QSettings()
        path = settings.value("mainwindow/workingDirectory", "")
        zipDestDir = QFileDialog.getExistingDirectory(
            self, _("Select the directory where to save the subtitle(s)"),
            path)
        if not zipDestDir:
            return
        if zipDestDir:
            settings.setValue("mainwindow/workingDirectory", zipDestDir)

        callback = ProgressCallbackWidget(self)

        callback.set_title_text(_('Downloading'))
        callback.set_label_text(_("Downloading files..."))
        callback.set_updated_text(_("Downloading {0} to {1}"))
        callback.set_block(True)

        callback.set_range(0, len(subs))

        callback.show()

        # Download and unzip files automatically. We might want to move this to an
        # external module, perhaps?
        unzippedOK = 0
        dlOK = 0

        for i, sub in enumerate(subs):
            # Skip rest of loop if Abort was pushed in progress bar
            if callback.canceled():
                break

            try:
                url = sub.getExtraInfo("downloadLink")
                log.debug("sub.getExtraInfo downloadLink  %s " % (url))
            except KeyError:
                url = Link().OneLink(0)
                log.debug("Link().OneLink downloadLink  %s " % (url))
                #                webbrowser.open( url, new=2, autoraise=1)
            zipFileID = re.search("(\/.*\/)(.*)\Z", url).group(2)
            zipFileName = "sub-" + zipFileID + ".srt"

            try:
                zipDestFile = os.path.join(zipDestDir, zipFileName).decode(
                    sys.getfilesystemencoding())
            except AttributeError:
                zipDestFile = (zipDestDir + '/' + zipFileName)
            log.debug("About to download %s %s to %s" %
                      (i, sub.__repr__, zipDestFile))
            log.debug("IdFileOnline: %s" % (sub.getIdFileOnline()))
            callback.update(i, sub.getIdFileOnline(), zipDestDir)

            # Download the file from opensubtitles.org
            # Note that we take for granted it will be in .zip format! Might not be so for other sites
            # This should be tested for when more sites are added or find
            # true filename like browser does FIXME
            try:
                if self.get_state().download_subtitles(
                    {sub.getIdFileOnline(): zipDestFile}):
                    dlOK += 1
                    unzippedOK += 1
                else:
                    QMessageBox.about(
                        self, _("Error"),
                        _("Unable to download subtitle %s") %
                        sub.get_filepath())
            except Exception as e:
                log.debug(e)
                QMessageBox.about(
                    self, _("Error"),
                    _("Unable to download subtitle %s") % sub.get_filepath())
                QMessageBox.critical(
                    self, _("Error"),
                    _("An error occurred downloading \"{url}\":\nError:{error_str}"
                      ).format(url=url, error_str=e), QMessageBox.Abort)
            QCoreApplication.processEvents()
        callback.finish()
        if dlOK:
            QMessageBox.about(
                self,
                _("{} subtitles downloaded successfully").format(unzippedOK),
                _("The downloaded subtitle(s) may not be in sync with your video file(s), please check this manually.\n"
                  "\nIf there is no sync problem, please consider re-uploading using subdownloader. "
                  "This will automate the search for other users!"))