class AdvertsDao: def __init__(self): self.dateUtil = DateUtil() self.logging = LogUtil().getLogging() def saveToDb(self, advert): if isinstance(advert, DbAdverts): currentTime = str(self.dateUtil.getCurrentTime()) insert = 'insert into ffstore_adverts (advert_id, cate_id, title, pic_url, sort, create_time) ' \ 'values("%s", "%s", "%s", "%s", "%s", "%s") ' \ % (advert.advert_id, advert.cate_id, advert.title, advert.pic_url, advert.sort, currentTime) return DbUtil.insert(insert) return False def updateToDb(self, advert): if isinstance(advert, DbAdverts): if not advert.advert_id: return False else: currentTime = self.dateUtil.getCurrentTime() update = 'update ffstore_adverts set cate_id = "%s", title = "%s", pic_url="%s", sort="%s",' \ ' create_time="%s" where advert_id = "%s" ' \ % (advert.cate_id, advert.title, advert.pic_url, advert.sort, currentTime, advert.advert_id) print 'update adverts to db' return DbUtil.update(update) return False def updateSortToDb(self, advert): if isinstance(advert, DbAdverts): if not advert.sort: return False else: update = 'update ffstore_adverts set sort="%s" where advert_id = "%s" ' % ( advert.sort, advert.advert_id) return DbUtil.update(update) return False def deleteByCateId(self, cate_id): if not cate_id: return False delete = 'delete from ffstore_adverts where cate_id = "%s" ' % cate_id return DbUtil.delete(delete) def deleteById(self, advert_id): if not advert_id: return False delete = 'delete from ffstore_adverts where advert_id = "%s" ' % advert_id return DbUtil.delete(delete) # 查询所有广告 def queryAllAdverts(self): query = 'select * from ffstore_adverts' return DbUtil.query(query) # 查询最新几条广告 def queryLastAdverts(self, last_count): query = 'select * from ffstore_adverts order by _id desc LIMIT %d ' % last_count return DbUtil.query(query)
def checkIfShouldCheckForAppUpdate(): if config.lastAppUpdateCheckDate == '': config.lastAppUpdateCheckDate = str(DateUtil.localDateNow()) return False else: compareDate = DateUtil.addDays(UpdateUtil.lastAppUpdateCheckDateObject(), int(config.daysElapseForNextAppUpdateCheck)) if compareDate <= DateUtil.localDateNow(): return True else: return False
def post(self, *args, **kwargs): param = self.request.body.decode('utf-8') param = json.loads(param) sign = param['sign'] time = param['time'] admin_tel = param['tel'] sms_pwd = param['sms'] advert_cate_id = param['cate_id'] advert_title = param['title'] advert_sort = param['sort'] advert_pic_url = param['pic_url'] getAdverts = GetAdverts() netAdverts = NetAdverts() netAdverts.title = advert_title netAdverts.picUrl = advert_pic_url netAdverts.sort = advert_sort netAdverts.createTime = DateUtil().getCurrentTime() permissionMgr = PermissionManager() baseResponse = permissionMgr.checkAdminPermissionWithLoginStatus( sign=sign, time=time, admin_tel=admin_tel, sms_pwd=sms_pwd) if baseResponse.code == ResponseCode.success_check_admin_permission: addResult = getAdverts.addAdverts(netAdverts, advert_cate_id) if addResult: baseResponse.code = ResponseCode.op_success baseResponse.desc = ResponseCode.op_success_desc else: baseResponse.code = ResponseCode.fail_op_db_data baseResponse.desc = ResponseCode.fail_op_db_data_desc json_str = json.dumps(baseResponse, cls=StrEncoder) self.write(json_str)
def keepAlive(self): print '---self.cancel_status: ', self.cancel_status while not self.cancel_status: # 保持屏幕常亮功能 # 获取鼠标坐标 x, y = pag.position() # print 'x-> ' + str(x) + ' y -> ' + str(y) # print 'oldx-> ' + str(self.oldx) + ' oldy -> ' + str(self.oldy) now_time = DateUtil().getCurrentTime() if x == self.oldx and y == self.oldy: stay_seconds = (now_time - self.prev_time).seconds if stay_seconds >= 60: self.prev_time = now_time pag.click() pag.moveTo(x + 10, y + 10, 0.1) pag.moveTo(x, y, 0.1) print u'>>> 模拟了一次鼠标移动' # pag.press('esc') # print u'模拟点击esc' else: # 更新旧坐标 self.oldx = x self.oldy = y self.prev_time = now_time stay_seconds = (now_time - self.prev_time).seconds print "鼠标{%s}秒未移动" % stay_seconds pos_str = "Position:" + str(x).rjust(4) + ',' + str(y).rjust(4) # #打印坐标 print pos_str time.sleep(2)
def updateLoginTime(self, admin_tel, login_time): current_time = DateUtil().getCurrentTimeStamp() if not login_time or login_time > current_time: return False update = 'update ffstore_admin set login_time = "%s" where admin_tel = "%s"' % ( login_time, admin_tel) return DbUtil.update(update)
def doScreenCap(self, deviceModel=None, callBack=None): screenPath = '/sdcard/screenshot_' if deviceModel: screenPath += deviceModel + "_" screenPath += str(DateUtil().getCurrentTimeStamp()) + ".png" destPath = "d:" + os.sep + "adbTools" + os.sep FileUtil.mkdirNotExist(destPath) cmd = str('%s -s %s shell /system/bin/screencap -p %s ' % (adbCmd, self.getCurrentSerialNo(), screenPath)) result = self._runSysCmd.run(cmd, should_process=False).stdout.read() if 'not found' in result: if callBack: callBack(_fromUtf8("未获取到设备, 请检查USB连接~")) return result cmd2 = str('%s -s %s pull %s %s' % (adbCmd, self.getCurrentSerialNo(), screenPath, destPath)) callBack(_fromUtf8("正在截屏操作, 请稍后..")) result = self._runSysCmd.run(cmd2, should_process=False).stdout.read() if "file pulled" in result: # os.startfile('d:\\adbTools') self._runSysCmd.run(['explorer.exe', destPath]) if callBack: strTmp = "已完成截屏, 保存地址为: %s" % (destPath + FileUtil.getFileName(screenPath)) callBack(_fromUtf8(strTmp)) return result
def saveChapterNote(self, b, c, note, updated=DateUtil.epoch()): delete = "DELETE FROM ChapterNote WHERE Book=? AND Chapter=?" self.cursor.execute(delete, (b, c)) self.connection.commit() if note and note != config.thisTranslation["empty"] and self.isNotEmptyNote(note): insert = "INSERT INTO ChapterNote (Book, Chapter, Note, Updated) VALUES (?, ?, ?, ?)" self.cursor.execute(insert, (b, c, note, updated)) self.connection.commit()
def saveVerseNote(b, c, v, note): now = DateUtil.epoch() if config.enableGist: gh = GitHubGist() gh.openGistVerseNote(b, c, v) gh.updateContent(note, now) ns = NoteService.getNoteSqlite() ns.saveVerseNote(b, c, v, note, now)
def orderQueryAllMethod(self): orderBeanList = self.orderDao.queryAll() if not orderBeanList: self.emitTipsChange(_fromUtf8("还没有工单信息~")) return excelPath = "C:\\Users\\20251572\\Desktop\\all_" + str( DateUtil().getCurrentTimeStamp()) + ".xls" self.write2Excel(orderBeanList, excelPath) os.startfile(excelPath)
def has_data_for_date(self, ticker, date, no_update_if_today=False): found_date = self.get_last_retrieved(ticker) # if no found date, then it isn't in the cache at all if found_date is None: return False # found_date is saturday or sunday and is today, don't update cache if DateUtil.dates_match(date, found_date) and DateUtil.is_weekend( date) and DateUtil.is_today(date): return True # if the date is today and it isn't the weekend, we need to update our cache always if DateUtil.is_today(date) and not no_update_if_today: return False # if the date in the metadata is greater than the requested date # we already have data for this date, otherwise we need to go get it return found_date > date or (no_update_if_today and DateUtil.is_today(date))
def updateUniqueBibleApp(parent=None, debug=False): if config.updateWithGitPull and os.path.isdir(".git"): subprocess.Popen("git pull", shell=True) else: requestObject = requests.get("{0}patches.txt".format( UpdateUtil.repository)) for line in requestObject.text.split("\n"): if line: try: version, contentType, filePath = literal_eval(line) if version > config.version: localPath = os.path.join(*filePath.split("/")) if debug: print("{0}:{1}".format(version, localPath)) else: if contentType == "folder": if not os.path.isdir(localPath): os.makedirs(localPath) elif contentType == "file": requestObject2 = requests.get( "{0}{1}".format( UpdateUtil.repository, filePath)) with open(localPath, "wb") as fileObject: fileObject.write( requestObject2.content) elif contentType == "delete": try: if os.path.exists(localPath): os.remove(localPath) except: print("Could not delete {0}".format( localPath)) except Exception as e: # message on failed item if parent is not None: parent.displayMessage("{0}\n{1}".format( config.thisTranslation["message_fail"], line)) else: return "Could not update" # set executable files on macOS or Linux if not platform.system() == "Windows": for filename in ("uba.py", "main.py", "BibleVerseParser.py", "RegexSearch.py"): if os.path.isfile(filename): os.chmod(filename, 0o755) # finish message config.lastAppUpdateCheckDate = str(DateUtil.localDateNow()) if parent is not None: parent.displayMessage("{0} {1}".format( config.thisTranslation["message_done"], config.thisTranslation["message_restart"])) else: return "Success"
def doStartScreenRecord(self, deviceModel=None, callBack=None): recordPath = '/sdcard/demo_' if deviceModel: recordPath += deviceModel + "_" recordPath += str(DateUtil().getCurrentTimeStamp()) + ".mp4" self._lastScreenRecordPath = recordPath cmd = str('%s -s %s shell screenrecord %s' % (adbCmd, self.getCurrentSerialNo(), recordPath)) callBack(_fromUtf8("正在进行录屏, 如需暂停请点击'结束录屏'按钮..")) result = self._runSysCmd.run(cmd, should_process=False).stdout.read() if callBack and 'not found' in result: callBack(_fromUtf8("未获取到设备, 请检查USB连接~")) return result
def test_write(): gh = GitHubGist() if not gh.connected: print(gh.status) else: book = 40 chapter = 1 gh.openGistChapterNote(book, chapter) updated = DateUtil.epoch() gh.updateContent("Matthew chapter change from command line", updated) updated = gh.getUpdated() print(updated) file = gh.getFile() if file: print(file.content) print(gh.id()) else: print(gh.description + " gist does not exist") print(gh.id()) print("---") book = 40 chapter = 1 verse = 2 gh.openGistVerseNote(book, chapter, verse) updated = DateUtil.epoch() gh.updateContent("Matthew verse 2 from command line", updated) file = gh.getFile() updated = gh.getUpdated() print(updated) if file: print(gh.id()) print(file.content) else: print(gh.description + " gist does not exist")
def orderAddMethod(self): orderNum = str(self.orderNumEdit.text()).decode('utf8') orderTitle = str(self.orderTitleEdit.text()).decode('utf8') orderReason = str(self.orderReasonEdit.toPlainText()).decode('utf8') orderDealTime = DateUtil().getCurrentTime() if not orderNum: self.setTips(_fromUtf8("添加工单信息时,工单号必不可少!")) return orderBean = WorkOrderBean() orderBean.order_num = orderNum orderBean.order_title = orderTitle orderBean.order_reason = orderReason orderBean.deal_time = orderDealTime result = self.orderDao.save(orderBean) if result: self.setTips(_fromUtf8("工单信息添加成功")) else: self.setTips(_fromUtf8("工单信息添加失败"))
class NotifyAdmin: def __init__(self): pass """ 发送短信通知 ['*****@*****.**', '*****@*****.**'] """ def sendMsg(self, sms_msg, toaddrs=['*****@*****.**'], subject='ffstore'): sendEmail = SendEmail(toaddrs=toaddrs, subject=subject) thr = threading.Thread(target=sendEmail, args=[sms_msg]) # open new thread thr.start() """ 发送微信通知 """ def sendWxMsg(self, msg, receiver='Fan'): try: weichatSender = WeiChatSender(host='http://127.0.0.1', port='9091') weichatSender.sendMsg(msg, receiver=receiver) except Exception as e: print e if __name__ == '__main__': notify = NotifyAdmin() current_time = DateUtil().getCurrentTime() notify.sendWxMsg('Hello. oyf finish it. at: %s' % current_time) notify.sendMsg('456')
def setup(): # Check current version with open("UniqueBibleAppVersion.txt", "r", encoding="utf-8") as fileObject: text = fileObject.read() current_version = float(text) # update current version in config if not hasattr(config, "version") or current_version > config.version: config.version = current_version # Default settings for configurations: # Developer options if not hasattr(config, "developer"): config.developer = False if not hasattr(config, "referenceTranslation"): config.referenceTranslation = "en_US" if not hasattr(config, "workingTranslation"): config.workingTranslation = "en_US" # Personal google api key for display of google maps if not hasattr(config, "myGoogleApiKey"): config.myGoogleApiKey = "" # Options to always display static maps even "myGoogleApiKey" is not empty: True / False if not hasattr(config, "alwaysDisplayStaticMaps"): if config.myGoogleApiKey: config.alwaysDisplayStaticMaps = False else: config.alwaysDisplayStaticMaps = True # IBM Watson service api key if not hasattr(config, "myIBMWatsonApikey"): config.myIBMWatsonApikey = "" if not hasattr(config, "myIBMWatsonUrl"): config.myIBMWatsonUrl = "" if not hasattr(config, "myIBMWatsonVersion"): config.myIBMWatsonVersion = "2018-05-01" # Options to use control panel: True / False # This feature is created for use in church settings. # If True, users can use an additional command field, in an additional window, to control the content being displayed, even the main window of UniqueBible.app is displayed on extended screen. if not hasattr(config, "showControlPanelOnStartup"): config.showControlPanelOnStartup = False if not hasattr(config, "preferControlPanelForCommandLineEntry"): config.preferControlPanelForCommandLineEntry = False if not hasattr(config, "closeControlPanelAfterRunningCommand"): config.closeControlPanelAfterRunningCommand = True if not hasattr(config, "restrictControlPanelWidth"): config.restrictControlPanelWidth = False if not hasattr(config, "masterControlWidth"): config.masterControlWidth = 1255 if not hasattr(config, "miniControlInitialTab"): config.miniControlInitialTab = 0 if not hasattr(config, "addBreakAfterTheFirstToolBar"): config.addBreakAfterTheFirstToolBar = True if not hasattr(config, "addBreakBeforeTheLastToolBar"): config.addBreakBeforeTheLastToolBar = False # Configure verse number single-click & double-click action # available options: "_noAction", "_cp0", "_cp1", "_cp2", "_cp3", "_cp4", "COMPARE", "CROSSREFERENCE", "TSKE", "TRANSLATION", "DISCOURSE", "WORDS", "COMBO", "INDEX", "COMMENTARY", "_menu" # corresponding translation: "noAction", "cp0", "cp1", "cp2", "cp3", "cp4", "menu4_compareAll", "menu4_crossRef", "menu4_tske", "menu4_traslations", "menu4_discourse", "menu4_words", "menu4_tdw", "menu4_indexes", "menu4_commentary", "classicMenu" if not hasattr(config, "verseNoSingleClickAction"): config.verseNoSingleClickAction = "INDEX" if not hasattr(config, "verseNoDoubleClickAction"): config.verseNoDoubleClickAction = "_cp0" # Start full-screen on Linux os if not hasattr(config, "linuxStartFullScreen"): config.linuxStartFullScreen = False # Use espeak for text-to-speech feature instead of built-in qt tts engine # espeak is a text-to-speech tool that can run offline # To check for available langauge codes, run on terminal: espeak --voices # Notes on espeak setup is available at: https://github.com/eliranwong/ChromeOSLinux/blob/main/multimedia/espeak.md # If you need text-to-speech features to work on Chinese / Russian text, you may read the link above. if not hasattr(config, "espeak"): # Check if UniqueBible.app is running on Chrome OS: if (os.path.exists("/mnt/chromeos/")): config.espeak = True else: config.espeak = False # espeak speed if not hasattr(config, "espeakSpeed"): config.espeakSpeed = 160 # qtts speed if not hasattr(config, "qttsSpeed"): config.qttsSpeed = 0.0 # tts language options if not hasattr(config, "useLangDetectOnTts"): config.useLangDetectOnTts = False if not hasattr(config, "ttsDefaultLangauge"): config.ttsDefaultLangauge = "en" if not hasattr(config, "ttsChineseAlwaysCantonese"): config.ttsChineseAlwaysCantonese = False if not hasattr(config, "ttsChineseAlwaysMandarin"): config.ttsChineseAlwaysMandarin = False if not hasattr(config, "ttsEnglishAlwaysUS"): config.ttsEnglishAlwaysUS = False if not hasattr(config, "ttsEnglishAlwaysUK"): config.ttsEnglishAlwaysUK = False # Options to use ibus as input method: True / False # This option may be useful on some Linux systems, where qt4 and qt5 applications use different input method variables. if not hasattr(config, "ibus"): config.ibus = False # This option may be useful on some Linux systems, where qt4 and qt5 applications use different input method variables. if not hasattr(config, "fcitx"): config.fcitx = False # Options to use built-in virtual keyboards: True / False if not hasattr(config, "virtualKeyboard"): config.virtualKeyboard = False # Specify the "open" command on Windows if not hasattr(config, "openWindows"): config.openWindows = "start" # Specify the "open" command on macOS if not hasattr(config, "openMacos"): config.openMacos = "open" # Specify the "open" command on Linux if not hasattr(config, "openLinux"): config.openLinux = "xdg-open" # Specify the command to open pdf file on Linux if not hasattr(config, "openLinuxPdf"): config.openLinuxPdf = "xdg-open" # Specify the folder path of resources if not hasattr(config, "marvelData"): config.marvelData = "marvelData" # Specify the folder path of music files if not hasattr(config, "musicFolder"): config.musicFolder = "music" # Specify the folder path of video files if not hasattr(config, "videoFolder"): config.videoFolder = "video" # Specify the file path of note file on bible chapters and verses if not hasattr(config, "bibleNotes"): config.bibleNotes = "note.sqlite" # Specify the number of tabs for bible reading and workspace if not hasattr(config, "numberOfTab"): config.numberOfTab = 5 # Options to populate tabs with latest history records on start up: True / False if not hasattr(config, "populateTabsOnStartup"): config.populateTabsOnStartup = False # Options to open Bible Window's content in the tab next to the current one: True / False if not hasattr(config, "openBibleWindowContentOnNextTab"): config.openBibleWindowContentOnNextTab = False # Options to open Study Window's content in the tab next to the current one: True / False if not hasattr(config, "openStudyWindowContentOnNextTab"): config.openStudyWindowContentOnNextTab = True # Options to open classic html menu when a bible chapter heading is clicked # It is set to False by default that clicking a chapter heading opens Master Control panel. if not hasattr(config, "preferHtmlMenu"): config.preferHtmlMenu = False # Options to convert all bible book abbreviations to standard ones: YES / NO if not hasattr(config, "parserStandarisation"): config.parserStandarisation = "NO" # Options of language of book abbreviations: ENG / TC / SC if not hasattr(config, "standardAbbreviation"): config.standardAbbreviation = "ENG" # Option to set a customised language for google-translate # References: https://cloud.google.com/translate/docs/languages # Use gui "Set my Language" dialog, from menu bar, to set "userLanguage". if not hasattr(config, "userLanguage") or not config.userLanguage: config.userLanguage = "English" # Option to use interface translated into userLanguage: True / False if not hasattr(config, "userLanguageInterface"): config.userLanguageInterface = False # Option to copy automatically to clipboard the result of accessing Google Translate: True / False if not hasattr(config, "autoCopyTranslateResult"): config.autoCopyTranslateResult = True # Option to display verse number in a range of verses: True / False # e.g. Try entering in command field "Ps 23:1; Ps 23:1-3; Ps 23:1-24:3" if not hasattr(config, "showVerseNumbersInRange"): config.showVerseNumbersInRange = True # Options to open chapter / verse note on Study Window after saving: True / False if not hasattr(config, "openBibleNoteAfterSave"): config.openBibleNoteAfterSave = False # Default: False: Open bible note on Study Window afer it is edited with Note Editor. # Bible note is opened when Note editor is closed. if not hasattr(config, "openBibleNoteAfterEditorClosed"): config.openBibleNoteAfterEditorClosed = False # Options to export all embedded images displayed on Study Window: True / False if not hasattr(config, "exportEmbeddedImages"): config.exportEmbeddedImages = True # Options to add open image action with a single click: True / False if not hasattr(config, "clickToOpenImage"): config.clickToOpenImage = True # Options to use landscape mode: True / False if not hasattr(config, "landscapeMode"): config.landscapeMode = True # Options for NOT displaying any toolbars on startup: True / False if not hasattr(config, "noToolBar"): config.noToolBar = False # Options to display the top toolbar only, with all other toolbars hidden: True / False if not hasattr(config, "topToolBarOnly"): config.topToolBarOnly = False # Options to use large sets of icons: True / False if not hasattr(config, "toolBarIconFullSize"): config.toolBarIconFullSize = False # Options on parallel mode: 0, 1, 2, 3 if not hasattr(config, "parallelMode"): config.parallelMode = 1 # Options to display the window showing instant information: 0, 1 if not hasattr(config, "instantMode"): config.instantMode = 1 # Options to trigger instant information: True / False if not hasattr(config, "instantInformationEnabled"): config.instantInformationEnabled = True # Default font size of content in main window and workspace if not hasattr(config, "fontSize"): config.fontSize = 17 # Default font if not hasattr(config, "font"): config.font = "" # Default Chinese font if not hasattr(config, "fontChinese"): config.fontChinese = "" # Default font size of content in note editor if not hasattr(config, "noteEditorFontSize"): config.noteEditorFontSize = 14 # Show Note Editor's style toolbar by default if not hasattr(config, "hideNoteEditorStyleToolbar"): config.hideNoteEditorStyleToolbar = False # Hide Note Editor's text utility by default if not hasattr(config, "hideNoteEditorTextUtility"): config.hideNoteEditorTextUtility = True # Options to display bibles in formatted layout or paragraphs: True / False # "False" here means displaying bible verse in plain format, with each one on a single line. if not hasattr(config, "readFormattedBibles"): config.readFormattedBibles = True # Options to add sub-headings when "readFormattedBibles" is set to "False": True / False if not hasattr(config, "addTitleToPlainChapter"): config.addTitleToPlainChapter = True # Options to hide lexical entries or Strong's numbers: True / False if not hasattr(config, "hideLexicalEntryInBible"): config.hideLexicalEntryInBible = False # Import setting - add a line break after each verse: True / False if not hasattr(config, "importAddVerseLinebreak"): config.importAddVerseLinebreak = False # Import setting - keep Strong's number for search: True / False if not hasattr(config, "importDoNotStripStrongNo"): config.importDoNotStripStrongNo = False # Import setting - keep morphology codes for search: True / False if not hasattr(config, "importDoNotStripMorphCode"): config.importDoNotStripMorphCode = False # Import setting - import text in right-to-left direction: True / False if not hasattr(config, "importRtlOT"): config.importRtlOT = False # Import setting - import interlinear text: True / False if not hasattr(config, "importInterlinear"): config.importInterlinear = False # List of modules, which contains Hebrew / Greek texts if not hasattr(config, "originalTexts"): config.originalTexts = [ 'original', 'MOB', 'MAB', 'MTB', 'MIB', 'MPB', 'OHGB', 'OHGBi', 'LXX', 'LXX1', 'LXX1i', 'LXX2', 'LXX2i' ] # List of modules, which contains right-to-left texts on old testament if not hasattr(config, "rtlTexts"): config.rtlTexts = [ "original", "MOB", "MAB", "MIB", "MPB", "OHGB", "OHGBi" ] # Open bible references on main window instead of workspace: Ture / False if not hasattr(config, "openBibleInMainViewOnly"): config.openBibleInMainViewOnly = False # Last-opened bible version and passage to be displayed on main window if not hasattr(config, "mainText"): config.mainText = "KJV" if not hasattr(config, "mainB"): config.mainB = 1 if not hasattr(config, "mainC"): config.mainC = 1 if not hasattr(config, "mainV"): config.mainV = 1 # Last-opened bible version and passage to be displayed on workspace if not hasattr(config, "studyText"): config.studyText = "NET" if not hasattr(config, "studyB"): config.studyB = 43 if not hasattr(config, "studyC"): config.studyC = 3 if not hasattr(config, "studyV"): config.studyV = 16 # Search Bible Mode # Accept value: 0-4 # Correspond to ("SEARCH", "SHOWSEARCH", "ANDSEARCH", "ORSEARCH", "ADVANCEDSEARCH") if not hasattr(config, "bibleSearchMode"): config.bibleSearchMode = 0 # Set your favourite version here if not hasattr(config, "favouriteBible"): config.favouriteBible = "OHGBi" # Options to display "favouriteBible" together with the main version for reading multiple references: True / False if not hasattr(config, "addFavouriteToMultiRef"): config.addFavouriteToMultiRef = False # Options to enforce comparison / parallel: True / False # When it is enabled after comparison / parallel feature is loaded once, subsequence entries of bible references will be treated as launching comparison / parallel even COMPARE::: or PARALLEL::: keywords is not used. # Please note that change in bible version for chapter reading is ignored when this option is enabled. # This feature is accessible via a left toolbar button, located under the "Comparison / Parallel Reading / Difference" button. if not hasattr(config, "enforceCompareParallel"): config.enforceCompareParallel = False # Options to show note indicator on bible chapter: True / False if not hasattr(config, "showNoteIndicatorOnBibleChapter"): config.showNoteIndicatorOnBibleChapter = True # Options sync Study Window's with changes verse references on Main Window: True / False if not hasattr(config, "syncStudyWindowBibleWithMainWindow"): config.syncStudyWindowBibleWithMainWindow = False # Options sync commentary with changes verse references on Main Window: True / False if not hasattr(config, "syncCommentaryWithMainWindow"): config.syncCommentaryWithMainWindow = False # Last-opened commentary text and passage if not hasattr(config, "commentaryText"): config.commentaryText = "CBSC" if not hasattr(config, "commentaryB"): config.commentaryB = 43 if not hasattr(config, "commentaryC"): config.commentaryC = 3 if not hasattr(config, "commentaryV"): config.commentaryV = 16 # Last-opened module for topical studies if not hasattr(config, "topic"): config.topic = "EXLBT" # Last-opened dictionary module if not hasattr(config, "dictionary"): config.dictionary = "EAS" # Last-opened encyclopedia module if not hasattr(config, "encyclopedia"): config.encyclopedia = "ISB" # Last-opened book module if not hasattr(config, "book"): config.book = "Harmonies_and_Parallels" # Last-opened book chapter if not hasattr(config, "bookChapter"): config.bookChapter = "03 - Gospels I" # Option to open book content on a new window if not hasattr(config, "bookOnNewWindow"): config.bookOnNewWindow = False # Popover Windows width if not hasattr(config, "popoverWindowWidth"): config.popoverWindowWidth = 640 # Popover Windows height if not hasattr(config, "popoverWindowHeight"): config.popoverWindowHeight = 480 # Option to overwrite font in book modules if not hasattr(config, "overwriteBookFont"): config.overwriteBookFont = True # Overwrite book font family if not hasattr(config, "overwriteBookFontFamily"): config.overwriteBookFontFamily = "" # Option to overwrite font size in book modules if not hasattr(config, "overwriteBookFontSize"): config.overwriteBookFontSize = True # Option to overwrite font in bible notes if not hasattr(config, "overwriteNoteFont"): config.overwriteNoteFont = True # Option to overwrite font size in bible notes if not hasattr(config, "overwriteNoteFontSize"): config.overwriteNoteFontSize = True # List of favourite book modules # Only the first 10 books are shown on menu bar if not hasattr(config, "favouriteBooks"): config.favouriteBooks = [ "Harmonies_and_Parallels", "Bible_Promises", "Timelines", "Maps_ABS", "Maps_NET" ] # Remove book, note and instant highlights on exit. if not hasattr(config, "removeHighlightOnExit"): config.removeHighlightOnExit = True # Last string entered for searching book if not hasattr(config, "bookSearchString"): config.bookSearchString = "" # Instant Highlight: highlighted word in Main Window if not hasattr(config, "instantHighlightString"): config.instantHighlightString = "" # Last string entered for searching note if not hasattr(config, "noteSearchString"): config.noteSearchString = "" # Last-opened third-party dictionary if not hasattr(config, "thirdDictionary"): config.thirdDictionary = "webster" # Last-opened lexicon if not hasattr(config, "lexicon"): config.lexicon = "ConcordanceBook" # Default Hebrew lexicon if not hasattr(config, "defaultLexiconStrongH"): config.defaultLexiconStrongH = "TBESH" # Default Greek lexicon if not hasattr(config, "defaultLexiconStrongG"): config.defaultLexiconStrongG = "TBESG" # Default lexicon based on ETCBC data if not hasattr(config, "defaultLexiconETCBC"): config.defaultLexiconETCBC = "ConcordanceMorphology" # Default lexicon on LXX words if not hasattr(config, "defaultLexiconLXX"): config.defaultLexiconLXX = "LXX" # Default lexicon on GK entries if not hasattr(config, "defaultLexiconGK"): config.defaultLexiconGK = "MCGED" # Default lexicon on LN entries if not hasattr(config, "defaultLexiconLN"): config.defaultLexiconLN = "LN" # Maximum number of history records allowed to be stored if not hasattr(config, "maximumHistoryRecord"): config.maximumHistoryRecord = 50 # Indexes of last-opened records if not hasattr(config, "currentRecord"): config.currentRecord = {"main": 0, "study": 0} # History records are kept in config.history if not hasattr(config, "history"): config.history = { "external": ["note_editor.uba"], "main": ["BIBLE:::KJV:::Genesis 1:1"], "study": ["BIBLE:::NET:::John 3:16"] } # Installed Formatted Bibles if not hasattr(config, "installHistory"): config.installHistory = {} # Use webbrowser module to open internal website links instead of opening on Study Window if not hasattr(config, "useWebbrowser"): config.useWebbrowser = True # set show information to True if not hasattr(config, "showInformation"): config.showInformation = True # Window Style # Availability of window styles depends on device if not hasattr(config, "windowStyle") or not config.windowStyle: config.windowStyle = "Fusion" # Theme (default, dark) if not hasattr(config, "theme"): config.theme = "default" # qt-material theme # qt-material theme is used only qtMaterial is true and qtMaterialTheme is not empty if not hasattr(config, "qtMaterial"): config.qtMaterial = False if not hasattr(config, "qtMaterialTheme"): config.qtMaterialTheme = "" # Disable modules update check if not hasattr(config, "disableModulesUpdateCheck"): config.disableModulesUpdateCheck = True # Force generate main.html for all pages if not hasattr(config, "forceGenerateHtml"): config.forceGenerateHtml = False # Enable logging if not hasattr(config, "enableLogging"): config.enableLogging = False # Log commands for debugging if not hasattr(config, "logCommands"): config.logCommands = False # Migrate Bible name from Verses table to Details table if not hasattr(config, "migrateDatabaseBibleNameToDetailsTable"): config.migrateDatabaseBibleNameToDetailsTable = True # Verse highlighting functionality if not hasattr(config, "enableVerseHighlighting"): config.enableVerseHighlighting = False # Show verse highlight markers if not hasattr(config, "showHighlightMarkers"): config.showHighlightMarkers = True # Menu layout if not hasattr(config, "menuLayout"): config.menuLayout = "focus" # Verse parsing method if not hasattr(config, "useFastVerseParsing"): config.useFastVerseParsing = False # Running custom python script "custom.py" on startup #if not hasattr(config, "customPythonOnStartup"): # config.customPythonOnStartup = False # Enable plugins if not hasattr(config, "enablePlugins"): config.enablePlugins = True # Enable macros if not hasattr(config, "enableMacros"): config.enableMacros = False # Startup macro if not hasattr(config, "startupMacro"): config.startupMacro = "" # Gist synching if not hasattr(config, "enableGist"): config.enableGist = False if not hasattr(config, "gistToken"): config.gistToken = '' # Clear command entry line by default if not hasattr(config, "clearCommandEntry"): config.clearCommandEntry = False # Highlight collections if not hasattr(config, "highlightCollections") or len( config.highlightCollections) < 12: config.highlightCollections = [ "Collection 1", "Collection 2", "Collection 3", "Collection 4", "Collection 5", "Collection 6", "Collection 7", "Collection 8", "Collection 9", "Collection 10", "Collection 11", "Collection 12" ] if not hasattr(config, "highlightDarkThemeColours") or len( config.highlightDarkThemeColours) < 12: config.highlightDarkThemeColours = [ "#646400", "#060166", "#646400", "#646400", "#646400", "#646400", "#646400", "#646400", "#646400", "#646400", "#646400", "#646400" ] if not hasattr(config, "highlightLightThemeColours") or len( config.highlightLightThemeColours) < 12: config.highlightLightThemeColours = [ "#e8e809", "#4ff7fa", "#e8e809", "#e8e809", "#e8e809", "#e8e809", "#e8e809", "#e8e809", "#e8e809", "#e8e809", "#646400", "#646400" ] # Default menu shortcuts if not hasattr(config, "menuShortcuts"): config.menuShortcuts = "micron" # Option to use flags=re.IGNORECASE with regular expression for searching bible # flags=re.IGNORECASE will be applied only if config.regexCaseSensitive is set to False if not hasattr(config, "regexCaseSensitive"): config.regexCaseSensitive = False if not hasattr(config, "displayLanguage"): config.displayLanguage = 'en_US' # App update check if not hasattr(config, "lastAppUpdateCheckDate"): config.lastAppUpdateCheckDate = str(DateUtil.localDateNow()) if not hasattr(config, "daysElapseForNextAppUpdateCheck"): config.daysElapseForNextAppUpdateCheck = '14' if not hasattr(config, "minicontrolWindowWidth"): config.minicontrolWindowWidth = 450 if not hasattr(config, "minicontrolWindowHeight"): config.minicontrolWindowHeight = 400 if not hasattr(config, "refButtonClickAction"): config.refButtonClickAction = "master" if not hasattr(config, "presentationScreenNo"): config.presentationScreenNo = -1 if not hasattr(config, "presentationFontSize"): config.presentationFontSize = 3.0 if not hasattr(config, "presentationMargin"): config.presentationMargin = 50 if not hasattr(config, "presentationColorOnLightTheme"): config.presentationColorOnLightTheme = "black" if not hasattr(config, "presentationColorOnDarkTheme"): config.presentationColorOnDarkTheme = "magenta" if not hasattr(config, "presentationVerticalPosition"): config.presentationVerticalPosition = 50 if not hasattr(config, "presentationHorizontalPosition"): config.presentationHorizontalPosition = 50 if not hasattr(config, "hideBlankVerseCompare"): config.hideBlankVerseCompare = False if not hasattr(config, "miniBrowserHome"): config.miniBrowserHome = "https://www.youtube.com/" if not hasattr(config, "enableMenuUnderline"): config.enableMenuUnderline = True if not hasattr(config, "addOHGBiToMorphologySearch"): config.addOHGBiToMorphologySearch = True if not hasattr(config, "activeVerseNoColourLight"): config.activeVerseNoColourLight = "red" if not hasattr(config, "activeVerseNoColourDark"): config.activeVerseNoColourDark = "rgb(197, 197, 56)" if not hasattr(config, "maximumOHGBiVersesDisplayedInSearchResult"): config.maximumOHGBiVersesDisplayedInSearchResult = 50 if not hasattr(config, "excludeStartupPlugins"): config.excludeStartupPlugins = [] if not hasattr(config, "excludeMenuPlugins"): config.excludeMenuPlugins = [] if not hasattr(config, "excludeContextPlugins"): config.excludeContextPlugins = [] if not hasattr(config, "excludeShutdownPlugins"): config.excludeShutdownPlugins = [] if not hasattr(config, "toolbarIconSizeFactor"): config.toolbarIconSizeFactor = 0.75 if not hasattr(config, "sidebarIconSizeFactor"): config.sidebarIconSizeFactor = 0.6 if not hasattr(config, "githubAccessToken"): token = "{0}_{1}0{2}".format('tuc', 'pOgQGiZ7QLV6N37UN', 'S1ubxgHbiE5Z34mbiZ') config.githubAccessToken = codecs.encode(token, 'rot_13') # Temporary configurations # Their values are not saved on exit. config.controlPanel = False config.miniControl = False config.tempRecord = "" config.contextItem = "" config.isDownloading = False config.noStudyBibleToolbar = False config.noteOpened = False config.pipIsUpdated = False config.bibleWindowContentTransformers = [] config.studyWindowContentTransformers = [] config.shortcutList = [] if config.enableMenuUnderline: config.menuUnderline = "&" else: config.menuUnderline = ""
def _get_filename(self): return os.path.join(os.path.dirname(__file__), "videos/%s.h264" % DateUtil.get_current_datetime_as_filename())
def __init__(self): self.dateUtil = DateUtil() pass
class OrderDao: def __init__(self): self.dateUtil = DateUtil() pass # 创建订单 def saveToDb(self, orderInfo): if isinstance(orderInfo, DbOrder): currentTime = self.dateUtil.getCurrentTime() insert = 'insert into ffstore_order (order_id, goods_id, user_id, order_goods_size, order_goods_color,' \ ' order_goods_count, order_status, order_pay_time, order_update_time,' \ ' order_express_num, order_express_code)' \ ' values("%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s")' \ % (orderInfo.order_id, orderInfo.goods_id, orderInfo.user_id, orderInfo.order_goods_size, orderInfo.order_goods_color, orderInfo.order_goods_count, orderInfo.order_status, orderInfo.order_pay_time, currentTime, orderInfo.order_express_num, orderInfo.order_express_code) print 'insert order to db.' return DbUtil.insert(insert) return False # 根据订单ID,更新订单所有信息,会更新所有订单表字段,如果需要更新单个字段值,请使用单个更新的方式 def updateToDb(self, orderInfo): if isinstance(orderInfo, DbOrder): currentTime = self.dateUtil.getCurrentTime() update = 'update ffstore_order set goods_id = "%s", user_id = "%s", order_goods_size = "%s",' \ ' order_goods_color = "%s", order_goods_count = "%s", order_status = "%s", order_pay_time = "%s",' \ ' order_update_time = "%s", order_express_num = "%s", order_express_code = "%s"' \ ' where order_id = "%s" ' \ % (orderInfo.goods_id, orderInfo.user_id, orderInfo.order_goods_size, orderInfo.order_goods_color, orderInfo.order_goods_count, orderInfo.order_status, orderInfo.order_pay_time, currentTime, orderInfo.order_express_num, orderInfo.order_express_code, orderInfo.order_id) print 'update order information to db' return DbUtil.update(update) return False # 下订单,更新订单, 为了保证下订单时数据正确性,需要将所有数据全部更新为当前下订单时的最新数据信息。 # 根据订单ID,下订单时,更新订单,此时需要将订单状态status 改为"待发货"状态, 并且更新订单下单时间 # 订单ID, 一定要提前生成好, 关于ID 的生成 def updateByPayment(self, orderInfo): if isinstance(orderInfo, DbOrder): db_order = self.queryByOrderId(orderInfo.order_id) if db_order: db_order.order_pay_time = self.dateUtil.getCurrentTime() db_order.order_status = OrderStatus.STATUS_NO_DELIVERY return self.updateToDb(db_order) else: orderInfo.order_pay_time = self.dateUtil.getCurrentTime() orderInfo.order_status = OrderStatus.STATUS_NO_DELIVERY return self.saveToDb(orderInfo) return False # 根据订单ID,更新订单快递信息 # 用于增加快递单信息,此时需要将订单状态status 改为"待收货"状态 def updateExpress(self, orderInfo): if isinstance(orderInfo, DbOrder): currentTime = self.dateUtil.getCurrentTime() orderInfo.order_status = OrderStatus.STATUS_NO_RECEIVE update = 'update ffstore_order set order_status = "%s", order_update_time = "%s", ' \ 'order_express_num = "%s", order_express_code = "%s" where order_id = "%s" ' \ % (orderInfo.order_status, currentTime, orderInfo.order_express_num, orderInfo.order_express_code, orderInfo.order_id) return DbUtil.update(update) return False # 订单完成 # 根据订单ID,订单完成时,更新订单,此时需要将订单状态status 改为"订单完成"状态 def updateByCompleted(self, orderInfo): if isinstance(orderInfo, DbOrder): orderInfo.order_status = OrderStatus.STATUS_COMPLETE return self.updateStatus(orderInfo) return False # 根据订单ID,更新订单状态{@see #OrderStatus} def updateStatus(self, orderInfo): if isinstance(orderInfo, DbOrder): currentTime = self.dateUtil.getCurrentTime() update = 'update ffstore_order set order_status = "%s", order_update_time = "%s" where order_id = "%s" ' \ % (orderInfo.order_status, currentTime, orderInfo.order_id) return DbUtil.update(update) return False # 根据订单ID 以及商品ID,更新订单商品信息(尺码和颜色) def updateGoodsSizeAndColor(self, orderInfo): if isinstance(orderInfo, DbOrder): currentTime = self.dateUtil.getCurrentTime() update = 'update ffstore_order set order_goods_size = "%s", order_goods_color = "%s", ' \ 'order_update_time = "%s" where order_id = "%s" and goods_id = "%s" ' \ % (orderInfo.order_goods_size, orderInfo.order_goods_color, currentTime, orderInfo.order_id, orderInfo.goods_id) return DbUtil.update(update) return False # 根据订单ID,查询单个订单 def queryByOrderId(self, order_id): if not order_id: return None query = 'select * from ffstore_order where order_id = "%s" ' % order_id return DbUtil.query(query) # 根据用户ID,查询单个用户所有订单 def queryByUserId(self, user_id): if not user_id: return None query = 'select * from ffstore_order where user_id = "%s" ' % user_id return DbUtil.query(query) # 根据商品ID,查询该商品对应的所有用户订单 def queryByGoodsId(self, goods_id): if not goods_id: return None query = 'select * from ffstore_order where goods_id = "%s" ' % goods_id return DbUtil.query(query) # 根据商品ID 以及订单状态,查询该商品对应改状态下,所有用户的订单 def queryByGoodsIdAndStatus(self, goods_id, order_status): if not goods_id or not order_status: return None query = 'select * from ffstore_order where goods_id = "%s" and order_status= "%s" ' % ( goods_id, order_status) return DbUtil.query(query) # 根据用户ID 和订单状态,查询该用户对应状态的所有订单 def queryByUserIdAndStatus(self, user_id, order_status, page_num=1, page_size=10): if not user_id or not order_status: return None start = (page_num - 1) * page_size # query = 'select * from ffstore_order where user_id = "%s" and order_status= "%s" ' % (user_id, order_status) query = 'select * from ffstore_order where user_id = "%s" and order_status= "%s" limit %s, %s; ' \ % (user_id, order_status, start, page_size) return DbUtil.query(query) # 根据订单状态,查询所有用户对应该状态的订单 def queryByStatus(self, order_status): if not order_status: return None query = 'select * from ffstore_order where order_status= "%s" ' % ( order_status) return DbUtil.query(query) # 查询这段时间内下单的所有用户的订单, 查询的订单结果,会包含其他状态的订单 def queryByPayTimeInterval(self, start_time, end_time): if not start_time or not end_time: return None query = 'select * from ffstore_order where order_pay_time >= UNIX_TIMESTAMP("%s") and ' \ 'order_pay_time < UNIX_TIMESTAMP("%s")' % (start_time, end_time) return DbUtil.query(query) # 查询这段时间内更新订单的所有用户的订单, 查询的订单结果,会包含其他状态的订单 def queryByUpdateTimeInterval(self, start_time, end_time): if not start_time or not end_time: return None query = 'select * from ffstore_order where order_update_time >= UNIX_TIMESTAMP("%s") and ' \ 'order_pay_time < UNIX_TIMESTAMP("%s")' % (start_time, end_time) return DbUtil.query(query) # 根据用户ID,查询单个用户的订单总量 def queryCountByUserId(self, user_id): if not user_id: return 0 query = 'select count(*) as count from ffstore_order where user_id = "%s" ' % user_id return DbUtil.querySingleRow(query) # 根据用户ID和订单状态,查询满足该条件的订单总数 def queryCountByUserIdAndStatus(self, user_id, order_status): if not user_id: return 0 query = 'select count(*) as count from ffstore_order where user_id = "%s" and order_status= "%s" ' % ( user_id, order_status) return DbUtil.querySingleRow(query) # 根据商品ID,查询该商品对应的订单总量 def queryCountByGoodsId(self, goods_id): if not goods_id: return 0 query = 'select count(*) as count from ffstore_order where goods_id = "%s" ' % goods_id return DbUtil.querySingleRow(query) # 查询这段时间内订单的总量 def queryCountByPayTimeInterval(self, start_time, end_time): if not start_time or not end_time: return 0 query = 'select count(*) as count from ffstore_order where order_update_time >= UNIX_TIMESTAMP("%s") and ' \ 'order_pay_time < UNIX_TIMESTAMP("%s")' % (start_time, end_time) return DbUtil.querySingleRow(query) # 删除单个订单,当用户添加订单后,取消订单,此时需要删除该订单 # 只有当订单状态为"未支付" 状态下,才允许删除订单,其他状态不允许进行删除操作 def deleteByOrderId(self, orderInfo): if isinstance(orderInfo, DbOrder): if orderInfo.order_status == OrderStatus.STATUS_NO_PAYMENT: delete = 'delete from ffstore_order where order_id = "%s" and order_status = "%s" ' \ % (orderInfo.order_id, OrderStatus.STATUS_NO_PAYMENT) print 'delete order_id:%s from db.' % orderInfo.order_id return DbUtil.delete(delete) return False return False
def process(self): return {"message_text" : "RaspberryPi is on. Current time: " + DateUtil.get_current_datetime_as_string()}
def lastAppUpdateCheckDateObject(): return DateUtil.dateStringToObject(config.lastAppUpdateCheckDate)
def stamp2TimeBtnClick(self): srcStr = unicode(self.srcStrEdit.toPlainText()) if not srcStr: return self.destStrEdit.setText(DateUtil().convert2Time(srcStr))
def time2StampBtnClick(self): srcStr = unicode(self.srcStrEdit.toPlainText()) if not srcStr: return self.destStrEdit.setText(str(DateUtil().convert2TimeStamp(srcStr)))
class AdminManager: def __init__(self): self.adminDao = AdminDao() self.dateUtil = DateUtil() self.notifyAdmin = NotifyAdmin() self.logging = LogUtil().getLogging() """ 登录 1. 如果数据库中没有对应的管理员手机号, 禁止非法登录 2. 如果没有短信验证码, 或者验证码过期, 则重新发送验证码到手机 3. 根据新验证码重新登录管理系统 4. 登录成功后,需要运维将管理员登录信息短信或微信告知我这个超管 """ def login(self, admin_tel, sms_pwd): login_status = self.checkLoginState(admin_tel, sms_pwd) if login_status == LoginStatus.STATUS_LOGIN_NO_ADMIN: # 警告!非法管理员操作 sms_msg = str(admin_tel) + u' 正在登陆后台系统, 请注意检查! ' self.notifyAdmin.sendMsg(sms_msg=sms_msg, subject=SMS_SUBJECT_INVALID_ADMIN_LOGIN) self.notifyAdmin.sendWxMsg(msg=sms_msg) return False elif login_status == LoginStatus.STATUS_LOGIN_FAIL_PWD or login_status == LoginStatus.STATUS_LOGIN_OUT_OF_DATE: # 重新发送验证码到手机进行登录 # 获取此刻登录密码,并且已经先更新了数据库 pwd = self.getSmsPwdAndSaveDb(admin_tel) if not pwd: # 这里是因为数据库没有插入成功, 或者验证码未生成, 无法发送验证码给管理员 return False # 发送短信验证码至当前管理员手机 day = LOGIN_TIME_INTERVAL / 24 / 60 / 60 hour = (LOGIN_TIME_INTERVAL - (day * 24 * 60 * 60)) / 60 / 60 min = LOGIN_TIME_INTERVAL - (day * 24 * 60 * 60) - (hour * 60 * 60) inteval = '' if day > 0: inteval = "%d 天 " % day if hour > 0: inteval += "%d 时 " % hour if min > 0: inteval += "%d 分" % min sms_msg = '您的登陆密码为: %s, %s内有效。' % (pwd, inteval) toEmailAddr = "*****@*****.**" % admin_tel self.notifyAdmin.sendMsg(sms_msg=sms_msg, toaddrs=[toEmailAddr], subject=SMS_SUBJECT_PWD) # 发送登陆信息给超级管理员(我) admin_sms_msg = '用户 {tel}|{pwd}正在尝试登陆后台系统.'.format(tel=admin_tel, pwd=pwd) # 先发送微信,再发短信 self.notifyAdmin.sendWxMsg(msg=admin_sms_msg) self.notifyAdmin.sendMsg(sms_msg=admin_sms_msg, subject=SMS_SUBJECT_LOGIN) # 需要重新登录, 所以返回false return False elif login_status == LoginStatus.STATUS_LOGIN_SUCCESS: # 发送运维信息,告诉我这个超管,有人登录系统了 admin_sms_msg = '用户 {tel} 已成功登陆后台系统.'.format(tel=admin_tel) self.notifyAdmin.sendMsg(sms_msg=admin_sms_msg, subject=SMS_SUBJECT_LOGIN) self.notifyAdmin.sendWxMsg(msg=admin_sms_msg) return True else: return False """ 获取短信验证码, 获取短信验证码后,需要更新当前最新的验证码到数据库中 """ def getSmsPwdAndSaveDb(self, admin_tel): if not admin_tel: return None pwd = RandomPwd().genPwd() updateResult = self.adminDao.updateSmsPwd(admin_tel, pwd) if updateResult: return pwd return None """ 校验登陆信息, 1. 检验用户号码和密码 2. 检验登录实效,超期操作非法。 只有当查询到管理员数据,以及管理员号码不为空时,校验通过。 """ def checkLoginState(self, admin_tel, sms_pwd): dbAdmin = self.getAdminByTel(admin_tel) if not dbAdmin: return LoginStatus.STATUS_LOGIN_NO_ADMIN dbAdmin = self.getAdminByTelAndPwd(admin_tel, sms_pwd) if not dbAdmin: return LoginStatus.STATUS_LOGIN_FAIL_PWD dbLoginTime = None if dbAdmin.login_time: dbLoginTime = int(float(dbAdmin.login_time)) currentTime = self.dateUtil.getCurrentTimeStamp() if not dbLoginTime or dbLoginTime + LOGIN_TIME_INTERVAL <= int( float(currentTime)): return LoginStatus.STATUS_LOGIN_OUT_OF_DATE return LoginStatus.STATUS_LOGIN_SUCCESS """ 查询数据库, 根据管理员号码查询管理员信息 该操作,用于前期判断是否存在该管理员,若不存在, 禁止非法操作, 同时不进行发短信验证码功能 """ def getAdminByTel(self, admin_tel): if not admin_tel: return None adminResult = self.adminDao.queryByTel(admin_tel) return self.convertDbRow2Admin(adminResult) """ 查询数据库, 根据管理员号码和密码查询管理员信息 该操作可用于登录校验,满足查询的结果,说明已经获取到短信验证码了 """ def getAdminByTelAndPwd(self, admin_tel, sms_pwd): if not admin_tel or not sms_pwd: return None adminResult = self.adminDao.queryByTelAndPwd(admin_tel, sms_pwd) return self.convertDbRow2Admin(adminResult) """ 更新登录密码, 该密码会以短信形式发送到手机, 以及微信通知 """ def updateLoginPwd(self, admin_tel, sms_pwd): return self.adminDao.updateSmsPwd(admin_tel, sms_pwd) """ 将登录时间更新为当前时间 """ def updateLoginTime2Current(self, admin_tel): currentTime = self.dateUtil.getCurrentTimeStamp() return self.adminDao.updateLoginTime(admin_tel, currentTime) # =========================== 转换开始 ===================================== # # 将数据库查询出来的结果,对应设置给admin实体bean, 并将单个 admin 返回出去 def convertDbRow2Admin(self, dbAdminRowsResult): if not dbAdminRowsResult: return None # self.logging.info('------------------>') # self.logging.info(dbAdminRowsResult) # self.logging.info('<------------------>') dbAdmin = DbAdmin() # single admin dbSingleRow = dbAdminRowsResult[0] row_id = dbSingleRow['_id'] dbAdmin.admin_tel = dbSingleRow['admin_tel'] dbAdmin.sms_pwd = dbSingleRow['sms_pwd'] dbAdmin.login_time = dbSingleRow['login_time'] return dbAdmin
def run(self): gh = GitHubGist() gNotes = gh.getAllNoteGists() gists = {} if gNotes: for gist in gNotes: gists[gist.description] = gist ns = NoteService.getNoteSqlite() count = 0 books = ns.getAllBooks() chapters = ns.getAllChapters() verses = ns.getAllVerses() notes = books + chapters + verses self.logger.debug("Uploading {0} notes".format(len(notes))) # Upload from local to Gist for note in notes: count += 1 book = note[0] chapter = note[1] verse = note[2] contentL = note[3] updatedL = note[4] if chapter == 0: description = GitHubGist.bToBookName(book) elif verse == 0: description = GitHubGist.bcToChapterName(book, chapter) else: description = GitHubGist.bcvToVerseName(book, chapter, verse) msg = "Processing upload " + description + " ..." self.progress.emit(msg) self.logger.debug(msg) updateGistFile = False updated = DateUtil.epoch() gist = None if description in gists.keys(): gist = gists[description] if gist is None: updateGistFile = True else: updatedG = GitHubGist.extractUpdated(gist) # if the local updated time is blank, merge the local database file with the gist file if updatedL is None: contentG = GitHubGist.extractContent(gist) contentL = NoteService.mergeNotes(contentL, contentG, "---<br/>") if chapter == 0: ns.saveBookNote(book, contentL, updated) elif verse == 0: ns.saveChapterNote(book, chapter, contentL, updated) else: ns.saveVerseNote(book, chapter, verse, contentL, updated) updateGistFile = True # if the updated time of local database note > gist time, then update gist elif updatedL > updatedG: updateGistFile = True updated = updatedL # if the local time <= gist time, then don't update gist elif updatedL <= updatedG: updateGistFile = False if updateGistFile: msg = "Updating gist " + description self.logger.debug(msg) if chapter == 0: gh.openGistBookNote(book) elif verse == 0: gh.openGistChapterNote(book, chapter) else: gh.openGistVerseNote(book, chapter, verse) gh.updateContent(contentL, updated) # Download from Gist gNotes = gh.getAllNoteGists() for gist in gNotes: count += 1 msg = "Processing download " + gist.description + " ..." self.progress.emit(msg) self.logger.debug(msg) contentG = GitHubGist.extractContent(gist) updatedG = GitHubGist.extractUpdated(gist) if "Book" in gist.description: book = GitHubGist.bookNameToB(gist.description) chapter = 0 verse = 0 res = [note for note in books if note[0] == book] elif "Chapter" in gist.description: (book, chapter) = GitHubGist.chapterNameToBc(gist.description) verse = 0 res = [note for note in chapters if note[0] == book and note[1] == chapter] elif "Verse" in gist.description: (book, chapter, verse) = GitHubGist.verseNameToBcv(gist.description) res = [note for note in verses if note[0] == book and note[1] == chapter and note[2] == verse] # if local note does not exist, then create local note if len(res) == 0: msg = "Creating local " + gist.description self.logger.debug(msg) if chapter == 0: ns.saveBookNote(book, contentG, updatedG) elif verse == 0: ns.saveChapterNote(book, chapter, contentG, updatedG) else: ns.saveVerseNote(book, chapter, verse, contentG, updatedG) # if local note already exist else: noteL = res[0] updatedL = noteL[4] # if gist update time > local update time, then update local if updatedG > updatedL: self.logger.debug("Updating local " + gist.description) if chapter == 0: ns.setBookNoteUpdate(book, contentG, updatedG) elif verse == 0: ns.setChapterNoteUpdate(book, chapter, contentG, updatedG) else: ns.setVerseNoteUpdate(book, chapter, verse, contentG, updatedG) self.finished.emit(count) self.logger.debug("Sync done")
print(len(notes)) def test_updated(): gh = GitHubGist() book = 40 chapter = 1 gh.openGistChapterNote(book, chapter) updated = gh.getUpdated() print(updated) content = gh.getContent() print(content) # def test_delete(): # gh = GitHubGist() # print(gh.deleteAllNotes()) if __name__ == "__main__": start = time.time() # test_write() # test_getNotes() test_getCount() print("---") end = time.time() print("Epoch: {0}".format(DateUtil.epoch())) print("Total time: {0}".format(end - start))
def __init__(self): self.adminDao = AdminDao() self.dateUtil = DateUtil() self.notifyAdmin = NotifyAdmin() self.logging = LogUtil().getLogging()
def __init__(self): self.dateUtil = DateUtil() self.logging = LogUtil().getLogging()
def __init__(self, parent): super(AppUpdateDialog, self).__init__() self.parent = parent self.setWindowTitle(config.thisTranslation["App_Updater"]) self.layout = QVBoxLayout() self.latestVersion = UpdateUtil.getLatestVersion() self.currentVersion = UpdateUtil.getCurrentVersion() if not config.internet: error = QLabel( config.thisTranslation["Could_not_connect_to_internet"]) error.setStyleSheet("color: rgb(253, 128, 8);") self.layout.addWidget(error) else: if UpdateUtil.currentIsLatest(self.currentVersion, self.latestVersion): self.uptodate = True else: self.uptodate = False if not self.uptodate: self.layout.addWidget( QLabel("{0}: {1}".format( config.thisTranslation["Latest_version"], self.latestVersion))) self.layout.addWidget( QLabel("{0}: {1}".format( config.thisTranslation["Current_version"], self.currentVersion))) self.updateNowButton = QPushButton( config.thisTranslation["Update_now"]) self.updateNowButton.setEnabled(True) self.updateNowButton.clicked.connect(self.updateNow) if self.uptodate: ubaUptodate = QLabel(config.thisTranslation["UBA_is_uptodate"]) if config.theme == "dark": ubaUptodate.setStyleSheet("color: green;") else: ubaUptodate.setStyleSheet("color: blue;") self.layout.addWidget(ubaUptodate) else: self.layout.addWidget(self.updateNowButton) self.layout.addWidget( QLabel("{0}: {1}".format( config.thisTranslation["Last_check"], DateUtil.formattedLocalDate( UpdateUtil.lastAppUpdateCheckDateObject())))) self.layout.addWidget( QLabel("{0}: {1}".format( config.thisTranslation["Next_check"], DateUtil.formattedLocalDate( DateUtil.addDays( UpdateUtil.lastAppUpdateCheckDateObject(), int(config.daysElapseForNextAppUpdateCheck)))))) row = QHBoxLayout() row.addWidget( QLabel("{0}:".format( config.thisTranslation["Days_between_checks"]))) self.daysInput = QLineEdit() self.daysInput.setText(str(config.daysElapseForNextAppUpdateCheck)) self.daysInput.setMaxLength(3) self.daysInput.setMaximumWidth(40) row.addWidget(self.daysInput) self.layout.addLayout(row) buttons = QDialogButtonBox.Ok self.buttonBox = QDialogButtonBox(buttons) self.buttonBox.accepted.connect(self.setDaysElapse) self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) self.layout.addWidget(self.buttonBox) self.setLayout(self.layout) if config.internet: self.updateNowButton.setFocus() if self.uptodate: self.daysInput.setFocus() else: # self.setTabOrder(self.updateNowButton, self.daysInput) # self.setTabOrder(self.daysInput, self.updateNowButton) self.updateNowButton.setFocus()
def _get_filename(self): return os.path.join( os.path.dirname(__file__), "photos/%s.jpg" % DateUtil.get_current_datetime_as_filename())
def _get_current_time(self): return DateUtil.get_current_time()