Example #1
0
    def test_language(self):
        with create_temporary_file() as f:
            f.file.close()
            s1 = Settings(f.name)
            s1.set_language(('section3', 'langprop'), Language.from_xxx('dut'))
            s1.write()
            del s1

            s2 = Settings(f.name)
            s2.reload()
            self.assertEqual(Language.from_xxx('dut'),
                             s2.get_language(('section3', 'langprop')))

            self.assertEqual(None, s2.get_language(('s', 'k')))
    def setup_ui(self):
        self.ui.setupUi(self)

        self.ui.buttonSearchByName.clicked.connect(self.onButtonSearchByTitle)
        self.ui.movieNameText.returnPressed.connect(self.onButtonSearchByTitle)
        self.ui.buttonDownloadByTitle.clicked.connect(self.onButtonDownloadByTitle)

        self.ui.buttonIMDBByTitle.clicked.connect(self.onViewOnlineInfo)
        self.ui.buttonIMDBByTitle.setEnabled(False)

        self.moviesModel = VideoTreeModel(self)
        self.moviesModel.connect_treeview(self.ui.moviesView)
        self.moviesModel.node_clicked.connect(self.on_item_clicked)
        self.moviesModel.dataChanged.connect(self.subtitlesMovieCheckedChanged)

        # FIXME: load settings from general place
        upload_language = Language.from_xxx(
            QSettings().value('options/uploadLanguage', UnknownLanguage.create_generic()))
        self.ui.filterLanguage.selected_language_changed.connect(self.on_language_combobox_filter_change)

        self.language_filter_change.connect(self.moviesModel.on_filter_languages_change)

        self.ui.moviesView.setContextMenuPolicy(Qt.CustomContextMenu)
        self.ui.moviesView.customContextMenuRequested.connect(self.onContext)

        self.retranslate()
Example #3
0
 def get_language(self, key, default=None):
     # FIXME: test parsing language settings (+invalid)
     try:
         xxx = self._load_str(key)
         return Language.from_xxx(xxx)
     except KeyError:
         return default
Example #4
0
    def get_permanent_language_filter(self):
        settings = QSettings()

        languages_str = settings.value('options/filterSearchLang', '')
        if languages_str:
            languages = [Language.from_xxx(lang_str) for lang_str in languages_str.split(',')]
            return languages
        else:
            return []
Example #5
0
 def get_languages(self, key, default=None):
     try:
         xxxs = self._load_str(key)
         return [
             Language.from_xxx(lang_str) for lang_str in xxxs.split(',')
             if lang_str
         ]
     except KeyError:
         return default
Example #6
0
    def test_languages(self):
        with create_temporary_file() as f:
            f.file.close()
            s1 = Settings(f.name)
            s1.set_languages(
                ('section4', 'langsprop'),
                [Language.from_xxx('spa'),
                 Language.from_xxx('eng')])
            s1.write()
            del s1

            s2 = Settings(f.name)
            s2.reload()
            self.assertListEqual(
                [Language.from_xxx('spa'),
                 Language.from_xxx('eng')],
                s2.get_languages(('section4', 'langsprop')))

            self.assertEqual(None, s2.get_languages(('s', 'k')))
Example #7
0
    def readSettings(self):
        log.debug('readSettings: start')
        self.settings.sync()

        # 1. Search tab
        checked_languages_str = self.settings.value('options/filterSearchLang',
                                                    [])
        if checked_languages_str:
            for lang_xxx in checked_languages_str.split(','):
                lang = Language.from_xxx(lang_xxx)
                if isinstance(lang, UnknownLanguage):
                    continue
                self._filterLanguageComboBoxes[lang].setChecked(True)

        # 2. Download tab

        # - Download Destination

        optionWhereToDownload = self.settings.value(
            'options/whereToDownload', self.DLDESTINATIONTYPE_SAMEFOLDER)
        if optionWhereToDownload == self.DLDESTINATIONTYPE_ASKUSER:
            self.ui.optionDlDestinationAsk.setChecked(True)
        elif optionWhereToDownload == self.DLDESTINATIONTYPE_SAMEFOLDER:
            self.ui.optionDlDestinationSame.setChecked(True)
        elif optionWhereToDownload == self.DLDESTINATIONTYPE_PREDEFINEDFOLDER:
            self.ui.optionDlDestinationUser.setChecked(True)

        dlDestination = self.settings.value('options/whereToDownloadFolder',
                                            '')
        #self._dlDestinationPredefined = dlDestination if os.path.isdir(dlDestination) else ''
        self.ui.inputDlDestinationUser.setText(dlDestination)
        self.ui.inputDlDestinationUser.editingFinished.emit()

        # - Subtitle Filename

        optionSubtitleName = self.settings.value('options/subtitleName',
                                                 self.DLSUBFN_SAME)
        if optionSubtitleName == self.DLSUBFN_SAME:
            self.ui.optionSubFnSame.setChecked(True)
        elif optionSubtitleName == self.DLSUBFN_SAMELANG:
            self.ui.optionSubFnSameLang.setChecked(True)
        elif optionSubtitleName == self.DLSUBFN_SAMELANGUPLOADER:
            self.ui.optionSubFnSameLangUploader.setChecked(True)
        elif optionSubtitleName == self.DLSUBFN_ONLINE:
            self.ui.optionSubFnOnline.setChecked(True)

        # 3. Upload tab

        # - Default Subtitle Language

        optionUploadLanguage = self.settings.value('options/uploadLanguage',
                                                   self.DEFAULT_UL_LANG.xxx())
        self._uploadLanguage = Language.from_xxx(optionUploadLanguage)

        self.ui.optionUlDefaultLanguage.set_selected_language(
            self._uploadLanguage)

        # 4. Network tab

        self.ui.inputProxyHost.setText(
            self.settings.value("options/ProxyHost", ""))
        self.ui.inputProxyPort.setValue(
            int(self.settings.value("options/ProxyPort", 8080)))

        # 5. Others tab

        # - Interface Language

        optionInterfaceLanguage = self.settings.value(
            'options/interfaceLang', self.DEFAULT_INTERFACE_LANG.locale())
        self._original_interface_language = Language.from_locale(
            optionInterfaceLanguage)
        self.ui.optionInterfaceLanguage.set_selected_language(
            self._original_interface_language)

        optionIntegrationExplorer = self.settings.value(
            "options/IntegrationExplorer", False)
        self.ui.optionIntegrationExplorer.setChecked(optionIntegrationExplorer)

        programPath = self.settings.value("options/VideoPlayerPath", "")
        parameters = self.settings.value("options/VideoPlayerParameters", "")
        self.ui.inputVideoAppLocation.setText(programPath)
        self.ui.inputVideoAppParams.setText(parameters)

        # Context menu for Explorer
        if platform.system() == "Linux":
            self.ui.optionIntegrationExplorer.setText(
                _("Enable in your Konqueror/Dolphin/Nautilus"))
            self.ui.optionIntegrationExplorer.setEnabled(False)
        elif platform.system() == "Windows":
            self.ui.optionIntegrationExplorer.setText(
                _("Enable in your Windows Explorer"))
            self.ui.optionIntegrationExplorer.setEnabled(False)
        else:
            self.ui.optionIntegrationExplorer.setText(
                _("Enable in your File Manager"))
            self.ui.optionIntegrationExplorer.setEnabled(False)

        log.debug('readSettings: finish')
Example #8
0
                if entry.getElementsByTagName('Newest') and entry.getElementsByTagName('Newest')[0].firstChild:
                    sub['Newest'] = entry.getElementsByTagName(
                        'Newest')[0].firstChild.data
                if sub:
                    # result_entries.append(sub)
                    temp_movie = Movie(sub)
                    movie_exists = False
                    for movie in result_entries:
                        if movie.MovieId == temp_movie.MovieId:
                            movie_exists = True
                            if hasattr(sub_obj, "_extraInfo") and sub_obj._extraInfo:
                                movie.subtitles.append(sub_obj)
#                            already_movie = result_entries.pop(result_entries.index(movie))
#                            temp_movie.subtitles = already_movie.subtitles
                    if not movie_exists:
                        if hasattr(sub_obj, "_extraInfo") and sub_obj._extraInfo:
                            temp_movie.subtitles.append(sub_obj)
                        result_entries.append(temp_movie)

            except IndexError as e:
                pass
        return result_entries

# For testing purposes
if __name__ == "__main__":
    s = SearchByName()
    res = s.search_movie(languages=[Language.from_xxx("por"), Language.from_xxx("pob")], moviename="anamorph")
    for movie in res:
        print(movie)
        print(len(movie.subtitles))
Example #9
0
    def _SearchSubtitles(self, language="all", videos=None, imdb_ids=None):
        """
        Search subtitles for the given video(s).

        @language: language code - string
        @videos: video objects - list
        @imdb_id: IMDB movie id's - list
        Note:Max results is 250. When nothing is found, 'data' is empty.
        """
        self.log.debug("----------------")
        self.log.debug("SearchSubtitles RPC method starting...")
        search_array = []
        if videos:
            self.log.debug("Building search array with video objects info")
            for video in videos:
                array = {'sublanguageid': language, 'moviehash':
                         video.get_hash(), 'moviebytesize': str(video.get_size())}
                self.log.debug(" - adding: %s" % array)
                search_array.append(array)
        elif imdb_ids:
            self.log.debug("Building search array with IMDB id's")
            for id in imdb_ids:
                array = {'sublanguageid': language, 'imdbid': id}
                self.log.debug(" - adding: %s" % array)
                search_array.append(array)

        self.log.debug("Communicating with server...")
        result = self._xmlrpc_server.SearchSubtitles(
            self._token, search_array)

        if result is not None and result['data'] != False:
            self.log.debug("Collecting downloaded data")
            moviehashes = {}
            for i in result['data']:
                moviehash = i['MovieHash']
                if moviehash not in moviehashes:
                    moviehashes[moviehash] = []
                moviehashes[moviehash].append(i)
            self.log.debug("Movie hashes: %i" % len(moviehashes.keys()))

            if videos:
                videos_result = []
                for video in videos:
                    if video.get_hash() in moviehashes:
                        osdb_info = moviehashes[video.get_hash()]
                        subtitles = []
                        self.log.debug("- %s (%s)" %
                                       (video.get_filepath(), video.get_hash()))
                        for i in osdb_info:
                            sub = subtitlefile.SubtitleFile(
                                online=True, id=i["IDSubtitle"])
                            sub.setHash(i["SubHash"])
                            sub.setIdFileOnline(i["IDSubtitleFile"])
                            sub.setFileName(i["SubFileName"])
                            # This method will autogenerate the XX and the
                            # LanguageName
                            sub.setLanguage(Language.from_xxx(i["SubLanguageID"]))
                            # sub.setLanguageXX(i["ISO639"])
                            # sub.setLanguageName(i["LanguageName"])
                            sub.setRating(i["SubRating"])
                            sub.setUploader(i["UserNickName"])
                            sub.setDownloadLink(i["SubDownloadLink"])
                            sub.setVideo(video)

                            self.log.debug(
                                "  [%s] - %s" % (sub.getLanguage().xxx(), sub.get_filepath()))
                            subtitles.append(sub)

                        # Let's get the IMDB info which is majority in the
                        # subtitles
                        video.setMovieInfo(self.getBestImdbInfo(osdb_info))
                        video.setOsdbInfo(osdb_info)
                        video.setSubtitles(subtitles)
                    videos_result.append(video)

                return videos_result

            elif imdb_ids:
                # TODO: search with IMDB id's
                pass
        else:
            self.log.info("No subtitles were found on Opensubtitles.org")
            return []
Example #10
0
    def upload_subtitles(self, local_movie):
        log.debug('upload_subtitles()')
        if not self.logged_in():
            raise ProviderNotConnectedError()
        video_subtitles = list(local_movie.iter_video_subtitles())
        if not video_subtitles:
            return UploadResult(
                type=UploadResult.Type.MISSINGDATA,
                reason=_('Need at least one subtitle to upload'))

        query_try = dict()
        for sub_i, (video, subtitle) in enumerate(video_subtitles):
            if not video:
                return UploadResult(
                    type=UploadResult.Type.MISSINGDATA,
                    reason=_('Each subtitle needs an accompanying video'))
            query_try['cd{}'.format(sub_i + 1)] = {
                'subhash':
                subtitle.get_md5_hash(),
                'subfilename':
                subtitle.get_filename(),
                'moviehash':
                video.get_osdb_hash(),
                'moviebytesize':
                str(video.get_size()),
                'moviefps':
                str(video.get_fps()) if video.get_fps() else None,
                'movieframes':
                str(video.get_framecount())
                if video.get_framecount() else None,
                'moviefilename':
                video.get_filename(),
            }

        def run_query_try_upload():
            return self._xmlrpc.TryUploadSubtitles(self._token, query_try)

        try_result = self._safe_exec(run_query_try_upload, None)
        self.check_result(try_result)

        if int(try_result['alreadyindb']):
            return UploadResult(type=UploadResult.Type.DUPLICATE,
                                reason=_('Subtitle is already in database'))

        if local_movie.get_imdb_id() is None:
            return UploadResult(type=UploadResult.Type.MISSINGDATA,
                                reason=_('Need IMDb id'))
        upload_base_info = {
            'idmovieimdb': local_movie.get_imdb_id(),
        }

        if local_movie.get_comments() is not None:
            upload_base_info['subauthorcomment'] = local_movie.get_comments()
        if not local_movie.get_language().is_generic():
            upload_base_info['sublanguageid'] = local_movie.get_language().xxx(
            )
        if local_movie.get_release_name() is not None:
            upload_base_info[
                'moviereleasename'] = local_movie.get_release_name()
        if local_movie.get_movie_name() is not None:
            upload_base_info['movieaka'] = local_movie.get_movie_name()
        if local_movie.is_hearing_impaired() is not None:
            upload_base_info[
                'hearingimpaired'] = local_movie.is_hearing_impaired()
        if local_movie.is_high_definition() is not None:
            upload_base_info[
                'highdefinition'] = local_movie.is_high_definition()
        if local_movie.is_automatic_translation() is not None:
            upload_base_info[
                'automatictranslation'] = local_movie.is_automatic_translation(
                )
        if local_movie.get_author() is not None:
            upload_base_info['subtranslator'] = local_movie.get_author()
        if local_movie.is_foreign_only() is not None:
            upload_base_info['foreignpartsonly'] = local_movie.is_foreign_only(
            )

        query_upload = {
            'baseinfo': upload_base_info,
        }
        for sub_i, (video, subtitle) in enumerate(video_subtitles):
            sub_bytes = subtitle.get_filepath().open(mode='rb').read()
            sub_tx_data = base64.b64encode(zlib.compress(sub_bytes)).decode()

            query_upload['cd{}'.format(sub_i + 1)] = {
                'subhash':
                subtitle.get_md5_hash(),
                'subfilename':
                subtitle.get_filename(),
                'moviehash':
                video.get_osdb_hash(),
                'moviebytesize':
                str(video.get_size()),
                'movietimems':
                str(video.get_time_ms()) if video.get_time_ms() else None,
                'moviefps':
                str(video.get_fps()) if video.get_fps() else None,
                'movieframes':
                str(video.get_framecount())
                if video.get_framecount() else None,
                'moviefilename':
                video.get_filename(),
                'subcontent':
                sub_tx_data,
            }

        def run_query_upload():
            return self._xmlrpc.UploadSubtitles(self._token, query_upload)

        result = self._safe_exec(run_query_upload, None)
        self.check_result(result)

        rsubs = []

        for sub_data in result['data']:
            filename = sub_data['SubFileName']
            file_size = sub_data['SubSize']
            md5_hash = sub_data['SubHash']
            id_online = sub_data['IDSubMOvieFile']
            download_link = sub_data['SubDownloadLink']
            link = None
            uploader = sub_data['UserNickName']
            language = Language.from_xxx(sub_data['SubLanguageID'])
            rating = float(sub_data['SubRating'])
            add_date = datetime.datetime.strptime(sub_data['SubAddDate'],
                                                  '%Y-%m-%d %H:%M:%S')
            sub = OpenSubtitlesSubtitleFile(filename=filename,
                                            file_size=file_size,
                                            md5_hash=md5_hash,
                                            id_online=id_online,
                                            download_link=download_link,
                                            link=link,
                                            uploader=uploader,
                                            language=language,
                                            rating=rating,
                                            date=add_date)
            rsubs.append(sub)

        return UploadResult(type=UploadResult.Type.OK, rsubs=rsubs)
Example #11
0
 def get_languages(self, section, option):
     xxxs = self.get_str(section, option, None)
     if xxxs is None:
         return []
     return [Language.from_xxx(lang_str) for lang_str in xxxs.split(',') if lang_str]
Example #12
0
 def get_language(self, section, option):
     xxx = self.get_str(section, option, UnknownLanguage.create_generic())
     return Language.from_xxx(xxx)