Ejemplo n.º 1
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()
Ejemplo n.º 2
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)
Ejemplo n.º 3
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)
Ejemplo n.º 4
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()
Ejemplo n.º 5
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)
Ejemplo n.º 6
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))
Ejemplo n.º 7
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)
Ejemplo n.º 8
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!"))
Ejemplo n.º 9
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"))