Пример #1
0
    def onButtonSearchByTitle(self):
        nb_connected = self._state.providers.get_number_connected_providers()
        if not nb_connected:
            return

        search_text = self.ui.movieNameText.text().strip()
        if not search_text:
            QMessageBox.about(self, _('Info'),
                              _('You must enter at least one character'))
            return

        self.ui.buttonSearchByName.setEnabled(False)

        callback = ProgressCallbackWidget(self)

        callback.set_title_text(_('Search'))
        callback.set_label_text(_('Searching...'))
        callback.set_block(True)
        callback.show()
        callback.update(0)

        try:
            query = self._state.providers.query_text(search_text)
            query.search_more_movies()
        except ProviderConnectionError:
            QMessageBox.warning(self, _('Error occured'),
                                _('A problem occured. Please try later.'))
            callback.finish()
            self.ui.buttonSearchByName.setEnabled(True)
            return
        callback.finish()

        self.moviesModel.set_query(query)

        self.ui.buttonSearchByName.setEnabled(True)
Пример #2
0
    def on_node_expanded(self, index):
        node = index.internalPointer()
        node.set_expanded(True)

        data = node.get_data()
        if isinstance(data, RemoteMovieNetwork):
            remote_movie_network = data
            if not remote_movie_network.get_nb_subs_available() and remote_movie_network.get_nb_subs_total():
                callback = ProgressCallbackWidget(self._treeview)
                callback.set_title_text(_('Search'))
                callback.set_label_text(_('Searching...'))
                callback.set_cancellable(False)
                callback.set_block(True)

                callback.show()

                success = False
                try:
                    # FIXME: use callback
                    success = remote_movie_network.search_more_subtitles()
                except ProviderConnectionError:
                    pass

                if not success:
                    QMessageBox.about(self._treeview, _('Info'),
                                      _('An unknown problem occurred or this type of movie cannot be handled.'))
                    self._treeview.collapse(index)
                    node.set_expanded(False)
                    callback.finish()
                    return

                # FIXME: do not use Node objects but add metadata to objects
                self.underlying_data_changed()

                callback.finish()
Пример #3
0
    def on_node_expanded(self, index):
        node = index.internalPointer()
        node.set_expanded(True)

        data = node.get_data()
        if isinstance(data, RemoteMovie):
            movie = data
            if not movie.get_nb_subs_available() and movie.get_nb_subs_total():
                callback = ProgressCallbackWidget(self._treeview)
                callback.set_title_text(_('Search'))
                callback.set_label_text(_("Searching..."))
                callback.set_cancellable(False)
                callback.set_block(True)

                callback.show()

                # FIXME: don't create SearchByName object here
                s = SearchByName('')
                callback.update(0)
                added_subtitles = s.search_more_subtitles(movie=movie)
                if added_subtitles is None:
                    QMessageBox.about(self._treeview, _("Info"),
                                      _("An unknown problem occurred or this type of movie cannot be handled."))
                    self._treeview.collapse(index)
                else:
                    node_origin = node.get_clone_origin()
                    for subtitle in added_subtitles:
                        node_origin.add_child(subtitle)
                    if movie.get_nb_subs_available() < movie.get_nb_subs_total():
                        node_origin.add_child(SearchMore(what=movie, text=_('More subtitles ...')))
                    self._apply_filters()
                callback.finish()
Пример #4
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
Пример #5
0
    def onButtonSearchByTitle(self):
        if not self.ui.movieNameText.text().strip():
            QMessageBox.about(
                self, _("Info"),
                _("You must enter at least one character in movie name"))
        else:
            self.ui.buttonSearchByName.setEnabled(False)

            callback = ProgressCallbackWidget(self)

            callback.set_title_text(_('Search'))
            callback.set_label_text(_("Searching..."))
            callback.set_block(True)

            callback.show()
            callback.update(0)

            self.moviesModel.clearTree()
            # This was a solution found to refresh the treeView
            self.ui.moviesView.expandAll()
            s = SearchByName()
            selected_language = self.ui.filterLanguage.get_selected_language()
            selected_language_xxx = None if selected_language.is_generic(
            ) else selected_language.xxx()
            search_text = self.ui.movieNameText.text()
            # This should be in a thread to be able to Cancel
            movies = s.search_movie(
                languages=[UnknownLanguage.create_generic()],
                moviename=search_text)
            if movies is None:
                QMessageBox.about(
                    self, _("Info"),
                    _("The server is momentarily unavailable. Please try later."
                      ))
                callback.finish()
                self.ui.buttonSearchByName.setEnabled(True)
                return
            self.moviesModel.setMovies(movies, selected_language_xxx)
            if len(movies) == 1:
                self.ui.moviesView.expandAll()
            else:
                self.ui.moviesView.collapseAll()
            callback.finish()
            self.ui.buttonSearchByName.setEnabled(True)
Пример #6
0
    def onExpandMovie(self, index):
        if index.internalPointer() is None:
            return
        movie = index.internalPointer().data
        if type(movie) == Movie and not movie.subtitles and movie.totalSubs:

            callback = ProgressCallbackWidget(self)
            callback.set_title_text(_('Search'))
            callback.set_label_text(_("Searching..."))
            callback.set_cancellable(False)
            callback.set_block(True)

            callback.show()

            s = SearchByName()
            selected_language = self.ui.filterLanguage.get_selected_language()
            selected_language_xxx = None if selected_language.is_generic(
            ) else selected_language.xxx()
            callback.update(0)
            temp_movie = s.search_movie(
                languages=[UnknownLanguage.create_generic()],
                MovieID_link=movie.MovieSiteLink)
            # The internal results are not filtered by language, so in case we change the filter, we don't need to request again.
            # print temp_movie
            try:
                movie.subtitles = temp_movie[0].subtitles
            except IndexError:
                QMessageBox.about(
                    self, _("Info"),
                    _("This is a TV series and it cannot be handled."))
                callback.finish()
                return
            except AttributeError:
                # this means only one subtitle was returned
                movie.subtitles = [temp_movie[1]]
            # The treeview is filtered by language
            self.moviesModel.updateMovie(index, selected_language_xxx)
            self.ui.moviesView.collapse(index)
            self.ui.moviesView.expand(index)
            callback.finish()
Пример #7
0
    def onButtonSearchByTitle(self):
        search_text = self.ui.movieNameText.text().strip()
        if not search_text:
            QMessageBox.about(self, _("Info"), _("You must enter at least one character in movie name"))
            return

        self.ui.buttonSearchByName.setEnabled(False)

        callback = ProgressCallbackWidget(self)

        callback.set_title_text(_('Search'))
        callback.set_label_text(_("Searching..."))
        callback.set_block(True)

        callback.show()
        callback.update(0)

        result = self.moviesModel.search_movies(query=search_text)

        if not result:
            QMessageBox.about(self, _("Info"), _("The server is momentarily unavailable. Please try later."))

        callback.finish()
        self.ui.buttonSearchByName.setEnabled(True)
Пример #8
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))
Пример #9
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)
Пример #10
0
    def onButtonPlay(self):
        settings = QSettings()
        programPath = settings.value('options/VideoPlayerPath', '')
        parameters = settings.value('options/VideoPlayerParameters', '')
        if programPath == '':
            QMessageBox.about(
                self, _('Error'),
                _('No default video player has been defined in Settings.'))
            return

        selected_subtitle = self.get_current_selected_item_videomodel()
        if isinstance(selected_subtitle, SubtitleFileNetwork):
            selected_subtitle = selected_subtitle.get_subtitles()[0]

        if isinstance(selected_subtitle, LocalSubtitleFile):
            subtitle_file_path = selected_subtitle.get_filepath()
        elif isinstance(selected_subtitle, RemoteSubtitleFile):
            subtitle_file_path = QDir.temp().absoluteFilePath(
                'subdownloader.tmp.srt')
            log.debug(
                'Temporary subtitle will be downloaded into: {temp_path}'.
                format(temp_path=subtitle_file_path))
            # FIXME: must pass mainwindow as argument to ProgressCallbackWidget
            callback = ProgressCallbackWidget(self)
            callback.set_title_text(_('Playing video + sub'))
            callback.set_label_text(_('Downloading files...'))
            callback.set_finished_text(_('Downloading finished'))
            callback.set_block(True)
            callback.set_range(0, 100)
            callback.show()
            try:
                subtitle_stream = selected_subtitle.download(
                    self.get_state().get_OSDBServer(), callback=callback)
            except ProviderConnectionError:
                log.debug('Unable to download subtitle "{}"'.format(
                    selected_subtitle.get_filename()),
                          exc_info=True)
                QMessageBox.about(
                    self, _('Error'),
                    _('Unable to download subtitle "{subtitle}"').format(
                        subtitle=selected_subtitle.get_filename()))
                callback.finish()
                return
            callback.finish()
            write_stream(subtitle_stream, subtitle_file_path)

        video = selected_subtitle.get_parent().get_parent().get_parent()

        def windows_escape(text):
            return '"{text}"'.format(text=text.replace('"', '\\"'))

        params = [windows_escape(programPath)]

        for param in parameters.split(' '):
            param = param.format(video.get_filepath(), subtitle_file_path)
            if platform.system() in ('Windows', 'Microsoft'):
                param = windows_escape(param)
            params.append(param)

        pid = None
        log.info('Running this command: {params}'.format(params=params))
        try:
            log.debug('Trying os.spawnvpe ...')
            pid = os.spawnvpe(os.P_NOWAIT, programPath, params, os.environ)
            log.debug('... SUCCESS. pid={pid}'.format(pid=pid))
        except AttributeError:
            log.debug('... FAILED', exc_info=True)
        except Exception as e:
            log.debug('... FAILED', exc_info=True)
        if pid is None:
            try:
                log.debug('Trying os.fork ...')
                pid = os.fork()
                if not pid:
                    log.debug('... SUCCESS. pid={pid}'.format(pid=pid))
                    os.execvpe(os.P_NOWAIT, programPath, params, os.environ)
            except:
                log.debug('... FAIL', exc_info=True)
        if pid is None:
            QMessageBox.about(self, _('Error'),
                              _('Unable to launch videoplayer'))
Пример #11
0
    def _search_videos_raw(self, paths):
        # FIXME: must pass mainwindow as argument to ProgressCallbackWidget
        callback = ProgressCallbackWidget(self)
        callback.set_title_text(_("Scanning..."))
        callback.set_label_text(_("Scanning files"))
        callback.set_finished_text(_("Scanning finished"))
        callback.set_block(True)

        try:
            local_videos, local_subs = scan_videopaths(paths,
                                                       callback=callback,
                                                       recursive=True)
        except OSError:
            callback.cancel()
            QMessageBox.warning(self, _('Error'),
                                _('Some directories are not accessible.'))

        if callback.canceled():
            return

        callback.finish()

        log.debug("Videos found: %s" % local_videos)
        log.debug("Subtitles found: %s" % local_subs)
        self.hideInstructions()

        QCoreApplication.processEvents()

        if not local_videos:
            QMessageBox.about(self, _("Scan Results"),
                              _("No video has been found!"))
            return

        total = len(local_videos)

        # FIXME: must pass mainwindow as argument to ProgressCallbackWidget
        # callback = ProgressCallbackWidget(self)
        # callback.set_title_text(_("Asking Server..."))
        # callback.set_label_text(_("Searching subtitles..."))
        # callback.set_updated_text(_("Searching subtitles ( %d / %d )"))
        # callback.set_finished_text(_("Search finished"))
        callback.set_block(True)
        callback.set_range(0, total)

        callback.show()

        callback.set_range(0, 2)

        download_callback = callback.get_child_progress(0, 1)
        # videoSearchResults = self.get_state().get_OSDBServer().SearchSubtitles("", videos_piece)
        remote_subs = self.get_state().get_OSDBServer().search_videos(
            videos=local_videos, callback=download_callback)

        self.videoModel.set_videos(local_videos)
        # self.onFilterLanguageVideo(self.ui.filterLanguageForVideo.get_selected_language())

        if remote_subs is None:
            QMessageBox.about(
                self, _("Error"),
                _("Error contacting the server. Please try again later"))
        callback.finish()
Пример #12
0
    def onButtonPlay(self):
        selected_item = self.get_current_selected_item_videomodel()
        log.debug('Trying to play selected item: {}'.format(selected_item))

        if selected_item is None:
            QMessageBox.warning(self, _('No subtitle selected'),
                                _('Select a subtitle and try again'))
            return

        if isinstance(selected_item, SubtitleFileNetwork):
            selected_item = selected_item.get_subtitles()[0]

        if isinstance(selected_item, VideoFile):
            subtitle_file_path = None
            video = selected_item
        elif isinstance(selected_item, LocalSubtitleFile):
            subtitle_file_path = selected_item.get_filepath()
            video = selected_item.get_super_parent(VideoFile)
        elif isinstance(selected_item, RemoteSubtitleFile):
            video = selected_item.get_super_parent(VideoFile)
            subtitle_file_path = Path(
                tempfile.gettempdir()) / 'subdownloader.tmp.srt'
            log.debug('tmp path is {}'.format(subtitle_file_path))
            log.debug(
                'Temporary subtitle will be downloaded into: {temp_path}'.
                format(temp_path=subtitle_file_path))
            # FIXME: must pass mainwindow as argument to ProgressCallbackWidget
            callback = ProgressCallbackWidget(self)
            callback.set_title_text(_('Playing video + sub'))
            callback.set_label_text(_('Downloading files...'))
            callback.set_finished_text(_('Downloading finished'))
            callback.set_block(True)
            callback.set_range(0, 100)
            callback.show()

            try:
                selected_item.download(
                    subtitle_file_path,
                    self._state.providers.get(selected_item.get_provider),
                    callback)
            except ProviderConnectionError:
                log.debug('Unable to download subtitle "{}"'.format(
                    selected_item.get_filename()),
                          exc_info=sys.exc_info())
                QMessageBox.about(
                    self, _('Error'),
                    _('Unable to download subtitle "{subtitle}"').format(
                        subtitle=selected_item.get_filename()))
                callback.finish()
                return
            callback.finish()
        else:
            QMessageBox.about(
                self, _('Error'),
                '{}\n{}'.format(_('Unknown Error'),
                                _('Please submit bug report')))
            return

        # video = selected_item.get_parent().get_parent().get_parent()
        # FIXME: download subtitle with provider + use returned localSubtitleFile instead of creating one here
        if subtitle_file_path:
            local_subtitle = LocalSubtitleFile(subtitle_file_path)
        else:
            local_subtitle = None
        try:
            player = self._state.get_videoplayer()
            player.play_video(video, local_subtitle)
        except RuntimeError as e:
            QMessageBox.about(self, _('Error'), e.args[0])
Пример #13
0
    def _search_videos_raw(self, paths):
        # FIXME: must pass mainwindow as argument to ProgressCallbackWidget
        callback = ProgressCallbackWidget(self)
        callback.set_title_text(_('Scanning...'))
        callback.set_label_text(_('Scanning files'))
        callback.set_finished_text(_('Scanning finished'))
        callback.set_block(True)
        callback.show()

        try:
            local_videos, local_subs = scan_videopaths(paths,
                                                       callback=callback,
                                                       recursive=True)
        except OSError:
            callback.cancel()
            QMessageBox.warning(self, _('Error'),
                                _('Some directories are not accessible.'))

        if callback.canceled():
            return

        callback.finish()

        log.debug('Videos found: {}'.format(local_videos))
        log.debug('Subtitles found: {}'.format(local_subs))

        self.hideInstructions()

        if not local_videos:
            QMessageBox.information(self, _('Scan Results'),
                                    _('No video has been found.'))
            return

        total = len(local_videos)

        # FIXME: must pass mainwindow as argument to ProgressCallbackWidget
        # callback = ProgressCallbackWidget(self)
        # callback.set_title_text(_('Asking Server...'))
        # callback.set_label_text(_('Searching subtitles...'))
        # callback.set_updated_text(_('Searching subtitles ( %d / %d )'))
        # callback.set_finished_text(_('Search finished'))
        callback.set_block(True)
        callback.set_range(0, total)

        callback.show()

        try:
            remote_subs = self._state.search_videos(local_videos, callback)
        except ProviderConnectionError:
            log.debug(
                'Unable to search for subtitles of videos: videos={}'.format(
                    list(v.get_filename() for v in local_videos)))
            QMessageBox.about(self, _('Error'),
                              _('Unable to search for subtitles'))
            callback.finish()
            return

        self.videoModel.set_videos(local_videos)

        if remote_subs is None:
            QMessageBox.about(
                self, _('Error'),
                _('Error contacting the server. Please try again later'))
        callback.finish()
Пример #14
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!"))
Пример #15
0
    def onUploadButton(self, clicked):
        ok, error = self.uploadModel.validate()
        if not ok:
            QMessageBox.about(self, _("Error"), error)
            return
        else:
            imdb_id = self.ui.uploadIMDB.itemData(self.ui.uploadIMDB.currentIndex())
            if imdb_id is None:  # No IMDB
                QMessageBox.about(
                    self, _("Error"), _("Please identify the movie."))
                return
            else:
                callback = ProgressCallbackWidget(self)
                callback.set_title_text(_("Uploading..."))
                callback.set_label_text(_("Uploading subtitle"))
                callback.set_block(True)
                callback.set_cancellable(False)

                callback.show()

                log.debug("Compressing subtitle...")
                details = {}
                details['IDMovieImdb'] = imdb_id
                lang_xxx = self.ui.uploadLanguages.itemData(
                        self.ui.uploadLanguages.currentIndex())
                details['sublanguageid'] = lang_xxx
                details['movieaka'] = ''
                details['moviereleasename'] = self.ui.uploadReleaseText.text()
                comments = self.ui.uploadComments.toPlainText()
                details['subauthorcomment'] = comments

                movie_info = {}
                movie_info['baseinfo'] = {'idmovieimdb': details['IDMovieImdb'], 'moviereleasename': details['moviereleasename'], 'movieaka': details[
                    'movieaka'], 'sublanguageid': details['sublanguageid'], 'subauthorcomment': details['subauthorcomment']}

                nb = self.uploadModel.getTotalRows()
                callback.set_range(0, nb)
                for i in range(nb):
                    curr_sub = self.uploadModel._subs[i]
                    curr_video = self.uploadModel._videos[i]
                    if curr_sub:  # Make sure is not an empty row with None
                        buf = open(curr_sub.getFilePath(), mode='rb').read()
                        curr_sub_content = base64.encodestring(zlib.compress(buf))
                        cd = "cd" + str(i)
                        movie_info[cd] = {'subhash': curr_sub.get_hash(), 'subfilename': curr_sub.get_filepath(), 'moviehash': curr_video.get_hash(), 'moviebytesize': curr_video.get_size(
                        ), 'movietimems': curr_video.get_time_ms(), 'moviefps': curr_video.get_fps(), 'moviefilename': curr_video.get_filepath(), 'subcontent': curr_sub_content}
                    callback.update(i)

                try:
                    info = self.get_state().upload(movie_info)
                    callback.finish()
                    if info['status'] == "200 OK":
                        successBox = QMessageBox(_("Successful Upload"),
                                                 _(
                                                     "Subtitles successfully uploaded.\nMany Thanks!"),
                                                 QMessageBox.Information,
                                                 QMessageBox.Ok | QMessageBox.Default | QMessageBox.Escape,
                                                 QMessageBox.NoButton,
                                                 QMessageBox.NoButton,
                                                 self)

                        saveAsButton = successBox.addButton(
                            _("View Subtitle Info"), QMessageBox.ActionRole)
                        answer = successBox.exec_()
                        if answer == QMessageBox.NoButton:
                            webbrowser.open(info['data'], new=2, autoraise=1)
                        self.uploadCleanWindow()
                    else:
                        QMessageBox.about(self, _("Error"), _(
                            "Problem while uploading...\nError: %s") % info['status'])
                except:
                    callback.finish()
                    QMessageBox.about(self, _("Error"), _(
                        "Error contacting the server. Please restart or try later"))