def __init__(self, parent=None): super(SystemStatus, self).__init__(parent) d = self.__d = _SystemStatus(self) netman.manager().onlineChanged.connect(self.onlineChanged) gameman.manager().processChanged.connect(d.onProcessChanged) dataman.manager().loginChanged.connect(d.onLoginChanged) settings.global_().userLanguageChanged.connect(self.userLanguageChanged) settings.global_().userIdChanged.connect(self.userIdChanged)
def _submitTopic(self, topic, image, tickets): """ @param topic kw @param image kw or None @param tickets [kw] """ dprint("enter") nm = netman.manager() if tickets: self._submitTickets(tickets) if image: data = skfileio.readdata(image['filename']) if data: topic['image'] = nm.submitImage(data, image) if image and not topic.get('image'): growl.warn("<br/>".join(( my.tr("Failed to submit topic"), my.tr("Please try again"), ))) return if nm.submitTopic(topic): self._onTopicSubmitted(topic, tickets) else: growl.warn("<br/>".join(( my.tr("Failed to submit topic"), my.tr("Please try again"), ))) dprint("leave")
def updateAndRefresh(self): if self._locked: dwarn("locked") return gameId = self.gameId if not gameId: #growl.notify(my.tr("Unknown game. Please try updating the database.")) return if netman.manager().isOnline(): if self.itemId and self.itemId < defs.MIN_NORMAL_GAME_ITEM_ID: dprint("found non-normal game, ignore refs") else: self._locked = True # lock before online access #growl.msg(my.tr("Updating game information")) ok = dataman.manager().updateReferences(gameId) #dm.touchGames() if not ok: growl.notify( my. tr("The game title it not specified. You can click the Edit button to add one." )) #else: #growl.msg(my.tr("Found game information")) self._locked = False # always unlock no matter what happened self.refresh()
def confirmUpdateTerms(): """ @return {reset=bool} or None """ if not netman.manager().isOnline(): growl.warn(my.tr("Cannot perform update when offline")) return #_speak(u"今すぐ辞書を更新しますか?") t = settings.global_().termsTime() or config.VERSION_TIMESTAMP sel = QMessageBox.question( _parent(), my.tr("Update user-contributed dictionary"), "\n\n".join(( "\n". join((my.tr( "Dictionary terms for machine translation are updated on: {0}." ), my. tr("VNR will check for automatically updates. Do you want to update now?" ))), my.tr(""" VNR will do incremental update by default. But if you press Reset, VNR will redownload the entire data, which is slow.""" ), )).format(i18n.timestamp2datetime(t)), Yes | No | Reset, No) if sel == Yes: return {'reset': False} elif sel == Reset: return {'reset': True}
def confirmUpdateRefs(game=None): """ @param game dataman.Game or None @return bool """ #if not game: # growl.notify(my.tr("Unknown game. Please try updating the database.")) # return if not netman.manager().isOnline(): growl.warn(my.tr("Cannot perform update when offline")) return #_speak(u"今すぐゲーム情報を更新しますか?") msg = "" if game: t = game.refsUpdateTime or game.visitTime or config.VERSION_TIMESTAMP msg += my.tr("Game references are updated on: {0}.").format( i18n.timestamp2datetime(t)) + "\n" msg += "\n\n".join(( my.tr("VNR will automatically check for updates."), my.tr("""Do you want to update now? It might take a couple of seconds to complete."""), )) return Yes == QMessageBox.question(_parent(), my.tr("Update game references"), msg, Yes | No, No)
def confirmUpdateComments(game=None): """ @param game dataman.Game or None @return bool """ #if not game: # growl.notify(my.tr("Unknown game. Please try updating the database.")) # return if not netman.manager().isOnline(): growl.warn(my.tr("Cannot perform update when offline")) return _speak(u"今すぐ字幕を更新しますか?") msg = "\n\n".join(( my.tr("VNR will automatically check for updates."), my.tr("""Do you want to update now? It might take a couple of seconds to complete."""), )) t = game.commentsUpdateTime or game.visitTime if game else 0 if t > 0: msg = "\n".join((my.tr("Comments are updated on: {0}.").format( i18n.timestamp2datetime(t)), msg)) return Yes == QMessageBox.question( _parent(), my.tr("Update user-contributed comments"), msg, Yes | No, No)
def confirmUpdateSubs(timestamp=0): """ @param* timestamp long @return {reset=bool} or None """ if not netman.manager().isOnline(): growl.warn(my.tr("Cannot perform update when offline")) return ts = i18n.timestamp2datetime(timestamp) if timestamp else tr_('empty') sel = QMessageBox.question( _parent(), my.tr("Update user-contributed subtitles"), "\n\n".join(( "\n".join(( my.tr("Shared subtitles are updated on: {0}."), my. tr("VNR will check for automatically updates. Do you want to update now?" ))), my.tr(""" VNR will do incremental update by default. But if you press Reset, VNR will redownload the entire data, which is slow.""" ), )).format(ts), Yes | No | Reset, No) if sel == Yes: return {'reset': False} elif sel == Reset: return {'reset': True}
def refresh(self): comment = self.comment online = netman.manager().isOnline() editable = self._canEdit() self.userNameLabel.setText( '@' + comment.userName if comment else tr_("Empty")) self.contextSizeLabel.setText( "%s" % comment.contextSize if comment else tr_("Empty")) self.timestampLabel.setText( i18n.timestamp2datetime(comment.timestamp ) if comment else tr_("Empty")) self.typeEdit.setCurrentIndex( dataman.Comment.TYPES.index(comment.type) if comment else 0) self.typeEdit.setEnabled(editable) self.enabledButton.setEnabled(bool(comment)) self.enabledButton.setChecked(bool(comment and not comment.disabled)) self.lockedButton.setEnabled(bool(comment)) self.lockedButton.setChecked(bool(comment and comment.locked)) self.textEdit.setPlainText(comment.text if comment else tr_("empty")) self.textEdit.setReadOnly(not editable) skqss.class_(self.textEdit, 'normal' if editable else 'readonly') self.commentEdit.setText(comment.comment) self.commentEdit.setReadOnly(not editable) skqss.class_(self.commentEdit, 'normal' if editable else 'readonly') self.textPermissionLabel.setText( tr_("Editable") if editable else tr_("Read-only")) skqss.class_(self.textPermissionLabel, 'normal' if editable else 'readonly') self.deleteButton.setEnabled(editable) self.onlineLabel.setText(tr_("Online") if online else tr_("Offline")) skqss.class_(self.onlineLabel, 'readonly' if online else 'error') try: langIndex = config.LANGUAGES.index(comment.language) except ValueError: langIndex = 1 # 'en' self.languageEdit.setCurrentIndex(langIndex) self.languageEdit.setEnabled(editable) self.spellHighlighter.setLanguage(comment.language) # must after lang if not comment or not comment.context: self.previousContextEdit.setPlainText(tr_("Empty")) self.currentContextEdit.setPlainText(tr_("Empty")) else: ctx = comment.context l = ctx.split(defs.CONTEXT_SEP) self.currentContextEdit.setPlainText(l[-1] or tr_("Empty")) self.previousContextEdit.setPlainText('\n'.join(l[:-1]) or tr_("Empty"))
def _submitPost(self, postData, imageData): if self.topicId and netman.manager().isOnline(): import forumapi skevents.runlater( partial(forumapi.manager().submitPost, postData, imageData, topicId=self.topicId))
def _submitPost(post, image): """ @param post kw @param image kw or None """ dprint("enter") if image: data = skfileio.readdata(image['filename']) if data: post['image'] = netman.manager().submitImage(data, image) if image and not post.get('image') or not netman.manager().submitPost( post): growl.warn("<br/>".join(( my.tr("Failed to submit post"), my.tr("Please try again"), ))) dprint("leave")
def refreshButton(self): ret = QtWidgets.QPushButton(tr_("Refresh")) skqss.class_(ret, 'btn btn-primary') ret.setToolTip(tr_("Refresh") + " (Ctrl+R)") #ret.setStatusTip(ret.toolTip()) ret.clicked.connect(self.updateAndRefresh) nm = netman.manager() ret.setEnabled(nm.isOnline()) nm.onlineChanged.connect(ret.setEnabled) return ret
def _updateTopic(self, topic, image, tickets): """ @param topic kw @param image kw or None @param tickets [kw] or None """ dprint("enter") if tickets: self._submitTickets(tickets) if image: data = skfileio.readdata(image['filename']) if data: topic['image'] = netman.manager().submitImage(data, image) if image and not topic.get('image') or not netman.manager( ).updateTopic(topic): growl.warn("<br/>".join(( my.tr("Failed to update topic"), my.tr("Please try again"), ))) dprint("leave")
def _canEdit(self): userAccess = [] user = dataman.manager().user() if user.access: #Сделал тут такую хуйню, потому что не знаю можно ли делать нормально(лол) userAccessMass = user.access.split(',') for a in userAccessMass: userAccess.append(a) # Пришлось вырезать дополнительную проверку, ибо хз как обратиться к dataman за itemId # and (self.comment.userId == user.id or (str(self.comment.userId) + ":" + str(self.comment.itemId)) in userAccess) return netman.manager().isOnline() and bool( self.comment) and not self.comment.d.protected
def setTopicId(self, topicId): # long -> if self.topicId != topicId: if topicId: if not self.topicComet: self.topicComet = comets.globalComet() if not self.topicId: self.topicComet.postDataReceived.connect(self._onPostReceived) self.topicComet.postDataUpdated.connect(self._onPostUpdated) if netman.manager().isOnline(): self.topicComet.setProperty('active', True) elif self.topicComet: self.topicComet.postDataReceived.disconnect(self._onPostReceived) self.topicComet.postDataUpdated.disconnect(self._onPostUpdated) self.topicId = topicId
def manager(self): import srman ret = srman.SpeechRecognitionManager() ret.setDetectsQuiet(True) ret.setSingleShot(True) ret.textRecognized.connect(self.textEdit.setPlainText) ret.recognitionFinished.connect(self.stop) ret.setDeviceIndex(self.deviceEdit.currentIndex()) self.deviceEdit.currentIndexChanged.connect(ret.setDeviceIndex) import netman nm = netman.manager() ret.setOnline(nm.isOnline()) nm.onlineChanged.connect(ret.setOnline) return ret
def setSubjectId(self, subjectId): # long -> if self.subjectId != subjectId: self.subjectId = subjectId if not subjectId: if self.subjectComet: self.subjectComet.setActive(False) else: if not self.subjectComet: self.subjectComet = comets.createPostComet() qml = self.subjectComet.q qml.topicDataReceived.connect(self._onTopicReceived) qml.topicDataUpdated.connect(self._onTopicUpdated) path = 'game/%s' % subjectId self.subjectComet.setPath(path) if netman.manager().isOnline(): self.subjectComet.setActive(True)
def confirmUpdateGameFiles(): """ @return bool """ if not netman.manager().isOnline(): growl.warn(my.tr("Cannot perform update when offline")) return _speak(u"今すぐゲーム情報を更新しますか?") t = settings.global_().gameFilesTime() or config.VERSION_TIMESTAMP return Yes == QMessageBox.question( _parent(), my.tr("Update online game database"), "\n\n".join(( my.tr("""Game database is updated on: {0}. The database is used to detect new games. VNR will automatically check for updates."""), my.tr("""Do you want to update now? It might take a couple of seconds to complete."""), )).format(i18n.timestamp2datetime(t)), Yes | No, No)
def setTopicId(self, topicId): # long -> if self.topicId != topicId: self.topicId = topicId if not topicId: if self.topicComet: self.topicComet.setActive(False) else: if not self.topicComet: self.topicComet = comets.createPostComet() qml = self.topicComet.q #qml.topicDataReceived.connect(self._onTopicReceived) qml.topicDataUpdated.connect(self._onTopicUpdated) qml.postDataUpdated.connect(self._onPostUpdated) qml.postDataReceived.connect(self._onPostReceived) path = 'topic/%s' % topicId self.topicComet.setPath(path) if netman.manager().isOnline(): self.topicComet.setActive(True)
def setVisible(self, value): """@reimp @public""" d = self.__d if value and not self.isVisible(): d.refresh() gameId = d.gameId if gameId and netman.manager().isOnline(): g = dataman.manager().queryGame(id=gameId) #if not g: # skevents.runlater(d.updateAndRefresh, 2000) # 2 seconds #else: if g: t = g.refsUpdateTime now = skdatetime.current_unixtime() if t + config.APP_UPDATE_REFS_INTERVAL < now: g.refsUpdateTime = now skevents.runlater(d.updateAndRefresh, 2000) # 2 seconds super(GameView, self).setVisible(value) if not value: d.webView.clear()
def refresh(self): """@reimp""" q = self.q dm = dataman.manager() info = self.gameInfo = dm.queryGameInfo(itemId=self.itemId, id=self.gameId, cache=False) self._gameBean.info = info if info: if not self.gameId: self.gameId = info.gameId if not self.itemId: self.itemId = info.itemId title = info.title if info else "" if not title and self.gameId: title = dm.queryGameName(id=self.gameId) t = title or tr_("Game") if info and info.itemId: t += " #%s" % info.itemId if info: if info.upcoming: t += u" (未発売)" elif info.recent: t += u" (新作)" q.setWindowTitle(t) icon = info.icon if info else None q.setWindowIcon(icon or rc.icon('window-gameview')) online = netman.manager().isOnline() self.editButton.setEnabled(bool(self.gameId)) self.launchButton.setEnabled(bool(info and info.local)) self.browseButton.setEnabled(online and bool(info and info.itemId)) self.topicButton.setEnabled(online and bool(info and info.itemId)) self.nameButton.setEnabled(bool(info) and info.hasCharacters()) # Fake base addr that twitter javascript can access document.cookie #baseUrl = '' #baseUrl = "http://localhost:6100" #baseUrl = "http://www.amazon.co.jp" # cross domain so that amazon iframe works #baseUrl = 'qrc://' # would crash QByteArray when refresh #baseUrl = 'qrc://any' # would crash QByteArray when refresh #baseUrl = 'file:///' # would crash QByteArray when refresh #baseUrl = 'file:///any' # any place that is local needsPost = info and info.gameItem and ( info.gameItem.overallScoreCount or info.gameItem.ecchiScoreCount) if online and needsPost: baseUrl = config.API_HOST # must be the same as rest.coffee for the same origin policy, but this would break getchu else: baseUrl = 'qrc:///_' # any place is fine user = dataman.manager().user() w = self.webView w.setHtml( rc.haml_template('haml/reader/gameview').render({ 'host': config.API_HOST, 'userName': user.name, 'userPassword': user.password, 'title': title, 'game': info, 'cache': cacheman.CacheJinjaUtil, 'rc': rc, 'py': py, 'tr': tr_, 'i18n': i18n, #'jlp': mecabman.manager(), # temporarily disabled #'settings', settings.global_(), 'online': online, 'proxy': proxy.manager(), 'mainland': features.MAINLAND_CHINA, }), baseUrl) self._injectBeans()
def renderJapanese(self, text, exact=True, feature=''): # """ @param text unicode Japanese phrase @param exact bool wheher do exact match exact match faster but return less phrases @param* feature unicode MeCab feature @return unicode not None html """ #if not d.japaneseLookupEnabled: # return EMPTY_HTML #google = proxy.manager().google_search #feature = GrimoireBean.instance.lookupFeature(text) try: ss = settings.global_() d = self.__d f = None if feature: f = mecabman.renderfeature(feature) else: roleName = mecabdef.role_name(text) if roleName: f = ','.join(( text, mecabdef.role_name_en(text) or '', # or part should never happen roleName, )) if d.userLanguage == 'ko': f += ',' + (mecabdef.role_name_ko(text) or '' ) # or part should never happen JMDictEnabled = True eb_strings = d.lookupEB(text, feature=feature) if ss.isJMDictRuEnabledJM(): JMDictEnabled = False # Init jisho dict jisho = [] if ss.isJishoOrgEnabled() and netman.manager().isOnline(): jishomass = netman.manager().jisho_api(text) for it in jishomass: word = '' reading = '' if 'word' in it['japanese'][0].keys(): word = it['japanese'][0]['word'] if 'reading' in it['japanese'][0].keys(): reading = it['japanese'][0]['reading'] jptext = '' for jp in it['japanese']: if 'word' in jp.keys(): jptext = jptext + jp['word'] if 'reading' in jp.keys(): jptext = jptext + "(" + jp['reading'] + ") " alldefinitions = [] i = 1 for sens in it['senses']: definitions = '' if 'english_definitions' in sens.keys(): if len(sens['english_definitions']) > 0: definitions = str(i) + ") " + ', '.join( sens['english_definitions']) if len(sens['parts_of_speech']) > 0: definitions = definitions + " (" + ', '.join( sens['parts_of_speech']) + ")" if definitions != "": alldefinitions.append(definitions) i = i + 1 jisho.append({ 'word': word, 'reading': reading, 'jptext': jptext, 'alldefinitions': alldefinitions }) # Init rus byars dict byars = '' if ss.isByarsEnabled() and netman.manager().isOnline(): byars = netman.manager().byars_api(text) # Убираем лишнее byars = re.sub(r'<p class="dicname">Яркси</p>', '', byars) byars = re.sub(r'<p class="dicname">БЯРС</p>', '', byars) byars = re.sub(r'onclick=".*?"', '', byars) byars = re.sub(r'href=".*?"', 'href="#"', byars) byars = re.sub(r'<span class="id">〔.*?〕<\/span>', '', byars) byars = re.sub(r'<object .*?<\/object>', '', byars) byars = re.sub( r'<div class=\"akusentoblock\">.*<\/ul>\s*<\/div>', '', byars, flags=re.M | re.S) #with SkProfiler("en-vi"): # 1/8/2014: take 7 seconds for OVDP ret = rc.jinja_template('html/shiori').render({ 'language': 'ja', 'JMDictEnabled': JMDictEnabled, 'text': text, 'feature': f, 'jisho': jisho, 'byars': byars, 'kanji': d.renderHanzi(text, html=True), 'tuples': d.lookupDB(text, exact=exact, feature=feature), 'eb_strings': eb_strings, # exact not used, since it is already very fast #'google': google, #'locale': d.locale, }) except UnicodeDecodeError, e: dwarn(e) ret = rc.jinja_template('html/shiori').render({ 'text': text, 'feature': feature, #'google': google, #'locale': d.locale, })
class SystemStatus(QObject): def __init__(self, parent=None): super(SystemStatus, self).__init__(parent) d = self.__d = _SystemStatus(self) netman.manager().onlineChanged.connect(self.onlineChanged) gameman.manager().processChanged.connect(d.onProcessChanged) dataman.manager().loginChanged.connect(d.onLoginChanged) settings.global_().userLanguageChanged.connect(self.userLanguageChanged) settings.global_().userIdChanged.connect(self.userIdChanged) wineChanged = Signal(bool) wine = Property(bool, lambda _: features.WINE, notify=wineChanged) adminChanged = Signal(int) admin = Property(int, lambda _: 1 if features.ADMIN == True else 0 if features.ADMIN == False else -1, notify=adminChanged) onlineChanged = Signal(bool) online = Property(bool, lambda _: netman.manager().isOnline(), notify=onlineChanged) loginChanged = Signal(bool) login = Property(bool, lambda _: dataman.manager().isLogin(), notify=loginChanged) userNameChanged = Signal(unicode) userName = Property(unicode, lambda _: dataman.manager().user().name, notify=userNameChanged) userPasswordChanged = Signal(unicode) userPassword = Property(unicode, lambda _: dataman.manager().user().password, notify=userPasswordChanged) userIdChanged = Signal(int) userId = Property(int, lambda _: dataman.manager().user().id, notify=userIdChanged) userLanguageChanged = Signal(unicode) userLanguage = Property(unicode, lambda _: settings.global_().userLanguage(), notify=userLanguageChanged) userTermLevelChanged = Signal(int) userTermLevel= Property(int, lambda _: dataman.manager().user().termLevel, notify=userTermLevelChanged) userCommentLevelChanged = Signal(int) userCommentLevel= Property(int, lambda _: dataman.manager().user().commentLevel, notify=userCommentLevelChanged) gameAttachedChanged = Signal(bool) gameAttached = Property(bool, lambda _: bool(gameman.manager().currentGame()), notify=gameAttachedChanged) @Slot(result=bool) def isKeyControlPressed(self): return skos.WIN and skwin.is_key_control_pressed() @Slot(result=bool) def isKeyShiftPressed(self): return skos.WIN and skwin.is_key_shift_pressed() @Slot(result=bool) def isKeyAltPressed(self): return skos.WIN and skwin.is_key_alt_pressed()
def _canEdit(self): return netman.manager().isOnline() and bool(self.comment) and self.comment.userId == dataman.manager().user().id and not self.comment.d.protected
def _submitTickets(self, tickets): # [{kw}] -> nm = netman.manager() for data in tickets: nm.updateTicket(data) # error not checked
def _updateTopic(self, topicData, imageData, ticketData): if netman.manager().isOnline(): import forumapi skevents.runlater( partial(forumapi.manager().updateTopic, topicData, imageData, ticketData))
def _refresh(self): import netman online = netman.manager().isOnline() self._onlineLabel.setText(tr_("Online") if online else tr_("Offline")) skqss.class_(self._onlineLabel, 'normal' if online else 'error')