def AddConvertTask(self, path, imgData, model, completeCallBack, backParam=None, cleanFlag="", filePath=""): info = QtDownloadTask() info.downloadCompleteBack = completeCallBack info.backParam = backParam self.taskId += 1 self.convertLoad[self.taskId] = info info.downloadId = self.taskId info.imgData = imgData info.model = model if path: a = hashlib.md5(path.encode("utf-8")).hexdigest() path = os.path.join( os.path.join(config.SavePath, config.CachePathDir), config.Waifu2xPath) path = os.path.join(path, a) info.cacheAndLoadPath = path info.loadPath = filePath if cleanFlag: info.cleanFlag = cleanFlag taskIds = self.convertFlag.setdefault(cleanFlag, set()) taskIds.add(self.taskId) Log.Debug("add convert info, cachePath:{}, loadPath:{}".format( info.cacheAndLoadPath, info.loadPath)) self._inQueue.put(self.taskId) Log.Info( "add convert info, taskId: {}, converId:{} backParam:{}".format( str(self.taskId), str(self.convertId), backParam)) return self.taskId
def UpdateFavoritesBack(self, backData): try: if backData.status != Status.Ok: return backData.status, self.page if backData.res.code == 200: info = backData.res.data.get("comics", {}) self.total = info["total"] self.page = info["page"] self.pages = info["pages"] self.category[self.page] = [] for bookInfo in info["docs"]: data = CategoryInfo() ToolUtil.ParseFromData(data, bookInfo) self.category[self.page].append(data) Log.Info("收藏夹加载成功, page:{}, pages:{}, num:{}".format( self.page, self.pages, self.total)) return Status.Ok, self.page else: return Status.Error + backData.res.message, self.page except Exception as e: import sys cur_tb = sys.exc_info()[ 2] # return (exc_type, exc_value, traceback) e = sys.exc_info()[1] Log.Error(cur_tb, e) return Status.Error + e, self.page
def PunchedBack(self, backData): if backData.res.code == 200: Log.Info("签到成功") # self.UpdateUserInfo() # self.UpdateFavorites() return Status.Ok else: Log.Info("签到失败!!!, userId:{}, msg:{}".format( self.userId, backData.res.message)) return Status.Error + backData.res.message
def HandlerDownloadTask(self, downlodaId, laveFileSize, data, isCallBack=True): info = self.downloadTask.get(downlodaId) if not info: return assert isinstance(info, QtDownloadTask) if laveFileSize == -1 and data == b"": try: if info.downloadCompleteBack: if info.backParam is not None: info.downloadCompleteBack( self.GetDownloadData(downlodaId), Status.Error, info.backParam) else: info.downloadCompleteBack( self.GetDownloadData(downlodaId), Status.Error) except Exception as es: Log.Error(es) self.ClearDownloadTask(downlodaId) return if info.isSaveData: info.saveData += data if info.downloadCallBack: try: if info.backParam is not None: info.downloadCallBack(data, laveFileSize, info.backParam) else: info.downloadCallBack(data, laveFileSize) except Exception as es: Log.Error(es) if laveFileSize == 0 and data == b"": if info.downloadCompleteBack: try: if info.cleanFlag: taskIds = self.flagToIds.get(info.cleanFlag, set()) taskIds.discard(info.downloadId) if info.backParam is not None: info.downloadCompleteBack( self.GetDownloadData(downlodaId), Status.Ok, info.backParam) else: info.downloadCompleteBack( self.GetDownloadData(downlodaId), Status.Ok) except Exception as es: Log.Error(es) self.ClearDownloadTask(downlodaId)
def RegisterBack(self, backData): try: if backData.status != Status.Ok: return backData.status if backData.res.code == 200: Log.Info("注册成功: {}".format(backData.res.raw.text)) return Status.Ok else: Log.Info("注册失败!!!, userId:{}, msg:{}".format( self.userId, backData.res.message)) return Status.RegisterError + backData.res.message except Exception as es: Log.Error(es) return Status.NetError
def InitBack(self, backData): try: if backData.status == Status.Ok and backData.res.status == "ok": if len(backData.res.addresses) > 0: self.addresss = backData.res.addresses[:] # self.address = backData.res.addresses[0] Log.Info("初始化成功, Ips:{}".format(self.addresss)) self.initRes = backData.res return Status.Ok else: Log.Info("初始化失败, info:{}".format(backData.res)) return Status.Error except Exception as es: Log.Error(es) return Status.Error
def AddBookByIdBack(self, backData): try: if backData.res.data.get("comic"): info = self.books.get(backData.res.data['comic']['_id']) if not info: info = Book() ToolUtil.ParseFromData(info, backData.res.data['comic']) self.books[info.id] = info return Status.Ok else: Log.Warn("未找到书籍, bookId:{}".format(backData)) return Status.NotFoundBook except Exception as es: Log.Error(es) return Status.NetError
def AddConvertBack(self, data, waifuId, backParam, tick): try: if data: savePath = os.path.dirname(self.curConvertPath) if not os.path.isdir(savePath): os.makedirs(savePath) f = open(self.curConvertPath, "wb+") f.write(data) f.close() self.tick = tick self.resetConvertCnt = 0 self.curPreConvertId += 1 self.StartConvert() else: self.resetConvertCnt += 1 if self.resetConvertCnt >= 3: self.status = DownloadInfo.Error self.parent.SetConvertStatu(DownloadInfo.Error) else: self.StartConvert() except Exception as es: Log.Error(es) self.status = DownloadInfo.Error self.parent.SetConvertStatu(DownloadInfo.Error) return
def InitUpdateBack(self, data): try: info = re.findall(r"\d+\d*", os.path.basename(data)) version = int(info[0]) * 100 + int(info[1]) * 10 + int(info[2]) * 1 info2 = re.findall(r"\d+\d*", os.path.basename(config.UpdateVersion)) curversion = int(info2[0]) * 100 + int(info2[1]) * 10 + int( info2[2]) * 1 if version > curversion: r = QMessageBox.information( self, "更新", "当前版本{} ,检查到更新{},是否前往更新".format(config.UpdateVersion, info), QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) if r == QMessageBox.Yes: QDesktopServices.openUrl( QUrl( "https://github.com/tonquer/picacg-windows/releases" )) except Exception as Es: import sys cur_tb = sys.exc_info()[ 2] # return (exc_type, exc_value, traceback) e = sys.exc_info()[1] Log.Error(cur_tb, e)
def DelHistory(self, bookId): query = QSqlQuery(self.db) sql = "delete from history where bookId='{}'".format(bookId) suc = query.exec_(sql) if not suc: Log.Warn(query.lastError().text()) return
def InitImageServer(self, backData): try: if backData.res.code == 200: # 选择了分流才设置 if self.server.address: self.server.imageServer = ToolUtil.GetUrlHost( backData.res.data["imageServer"]) Log.Info("初始化图片服务器成功, info:{}".format( self.server.imageServer)) return Status.Ok else: return Status.Error except Exception as es: Log.Error(es) return Status.Error
def Init(self, app): self.settingForm.SetLanguage(app, self) if config.CanWaifu2x: from waifu2x_vulkan import waifu2x_vulkan stat = waifu2x_vulkan.init() if stat < 0: self.msgForm.ShowError("Waifu2x CPU Model") waifu2x_vulkan.setDebug(True) gpuInfo = waifu2x_vulkan.getGpuInfo() cpuNum = waifu2x_vulkan.getCpuCoreNum() self.settingForm.SetGpuInfos(gpuInfo, cpuNum) self.settingForm.exec() self.settingForm.SetLanguage(app, self) waifu2x_vulkan.initSet(config.Encode, config.UseCpuNum) self.img.gpuName.setText(config.EncodeGpu) Log.Info("waifu2x init: " + str(stat) + " encode: " + str(config.Encode) + " version:" + waifu2x_vulkan.getVersion()) # self.msgForm.ShowMsg("waifu2x初始化成功\n" + waifu2x.getVersion()) else: self.msgForm.ShowError("Waifu2x can not use, " + config.ErrorMsg) self.img.checkBox.setEnabled(False) self.img.changeJpg.setEnabled(False) self.img.changePng.setEnabled(False) self.img.comboBox.setEnabled(False) self.img.SetStatus(False) config.IsOpenWaifu = 0 return
def Init(self): if config.CanWaifu2x: import waifu2x stat = waifu2x.Init(config.Encode, config.Waifu2xThread) if stat < 0: self.msgForm.ShowError("waifu2x初始化错误") gpuInfo = waifu2x.GetGpuInfo() if gpuInfo: self.settingForm.SetGpuInfos(gpuInfo) Log.Info("waifu2x初始化: " + str(stat) + " encode: " + str(config.Encode)) else: self.msgForm.ShowError("waifu2x无法启用, "+config.ErrorMsg) self.settingForm.checkBox.setEnabled(False) self.qtReadImg.frame.qtTool.checkBox.setEnabled(False) self.downloadForm.autoConvert = False self.downloadForm.radioButton.setEnabled(False) QtImgMgr().obj.radioButton.setEnabled(False) QtImgMgr().obj.changeButton.setEnabled(False) QtImgMgr().obj.changeButton.setEnabled(False) QtImgMgr().obj.comboBox.setEnabled(False) config.IsOpenWaifu = 0 self.InitUpdate() self.loginForm.Init() return
def AddHistory(self, bookId, name, epsId, index, url, path): tick = int(time.time()) info = self.history.get(bookId) if not info: info = QtHistoryData() self.history[bookId] = info info.bookId = bookId info.name = name info.epsId = epsId info.picIndex = index info.url = url info.path = path info.tick = tick query = QSqlQuery(self.db) sql = "INSERT INTO history(bookId, name, epsId, picIndex, url, path, tick) " \ "VALUES ('{0}', '{1}', {2}, {3}, '{4}', '{5}', {6}) " \ "ON CONFLICT(bookId) DO UPDATE SET name='{1}', epsId={2}, picIndex={3}, url = '{4}', path='{5}', tick={6}".\ format(bookId, name, epsId, index, url, path, tick) suc = query.exec_(sql) if not suc: Log.Warn(query.lastError().text()) return
def LoadSetting(self): x = self.settings.value("MainSize_x") y = self.settings.value("MainSize_y") if x and y: self.mainSize = QSize(int(x), int(y)) v = self.settings.value("Waifu2x/Encode") if v: config.Encode = int(v) # v = self.settings.value("Waifu2x/LogIndex") # if v: # config.LogIndex = int(v) # self.logBox.setCurrentIndex(config.LogIndex) Log.UpdateLoggingLevel() v = self.settings.value("Waifu2x/Open") config.SelectEncodeGpu = self.GetSettingV("Waifu2x/SelectEncodeGpu", "") config.UseCpuNum = self.GetSettingV("Waifu2x/UseCpuNum", 0) config.Language = self.GetSettingV("Waifu2x/Language", 0) self.encodeSelect.setCurrentIndex(0) self.languageSelect.setCurrentIndex(config.Language) for index in range(self.encodeSelect.count()): if config.SelectEncodeGpu == self.encodeSelect.itemText(index): self.encodeSelect.setCurrentIndex(index) return
def AddDownloadTask(self, url, path, downloadCallBack=None, completeCallBack=None, isSaveData=True, backParam=None, isSaveCache=True, cleanFlag="", filePath=""): self.taskId += 1 data = QtDownloadTask(self.taskId) data.downloadCallBack = downloadCallBack data.downloadCompleteBack = completeCallBack data.isSaveData = isSaveData data.backParam = backParam data.url = url data.path = path self.downloadTask[self.taskId] = data if cleanFlag: data.cleanFlag = cleanFlag taskIds = self.flagToIds.setdefault(cleanFlag, set()) taskIds.add(self.taskId) if isSaveCache: if not path: a = hashlib.md5(url.encode("utf-8")).hexdigest() else: a = hashlib.md5(path.encode("utf-8")).hexdigest() filePath2 = os.path.join(os.path.join(config.SavePath, config.CachePathDir), os.path.dirname(path)) filePath2 = os.path.join(filePath2, a) data.cacheAndLoadPath = filePath2 if filePath: data.loadPath = filePath Log.Debug("add download info, cachePath:{}, loadPath:{}".format(data.cacheAndLoadPath, data.loadPath)) from src.server import Server from src.server import req Server().Download(req.DownloadBookReq(url, path, isSaveCache), bakParams=self.taskId, cacheAndLoadPath=data.cacheAndLoadPath, loadPath=data.loadPath) return self.taskId
def AddConvertTask(self, url, path, imgData, completeCallBack=None, backParam=None, cleanFlag=""): info = QtDownloadTask() info.downloadCompleteBack = completeCallBack info.backParam = backParam info.url = url info.path = path self.taskId += 1 self.convertLoad[self.taskId] = info data = self.LoadConvertCachePicture(url, path) if data: info.saveData = data self.HandlerConvertTask(self.taskId, isCallBack=False) return self.taskId converId = waifu2x.Add(imgData, config.Format, config.Noise, config.Scale, self.taskId) Log.Info( "add convert info, taskId: {}, converId:{} backParam:{}".format( str(self.taskId), str(self.convertId), backParam)) if converId <= 0: return 0 if cleanFlag: info.cleanFlag = cleanFlag taskIds = self.convertFlag.setdefault(cleanFlag, set()) taskIds.add(self.taskId) return self.taskId
def DelRecordingAndFile(self): selected = self.tableWidget.selectedIndexes() selectRows = set() for index in selected: selectRows.add(index.row()) if not selectRows: return try: selectRows = list(selectRows) selectRows.sort(reverse=True) for row in selectRows: col = 0 bookId = self.tableWidget.item(row, col).text() bookInfo = self.downloadDict.get(bookId) if not bookInfo: continue self.RemoveRecord(bookId) if os.path.isdir(bookInfo.savePath): shutil.rmtree(bookInfo.savePath) except Exception as es: import sys cur_tb = sys.exc_info()[ 2] # return (exc_type, exc_value, traceback) e = sys.exc_info()[1] Log.Error(cur_tb, e) self.UpdateTableRow()
def _Send(self, task): try: if task.req.method.lower() == "post": self.Post(task) elif task.req.method.lower() == "get": self.Get(task) else: return except Exception as es: task.status = Status.NetError Log.Error(es) try: self.handler.get(task.req.__class__)(task) if task.res.raw: task.res.raw.close() except Exception as es: Log.Error(es)
def ParseFromData(desc, src): try: if isinstance(src, str): src = json.loads(src) for k, v in src.items(): setattr(desc, k, v) except Exception as es: Log.Error(es)
def Refresh(self, clsName, des='', checkTime=100): t2 = time.time() diff = int((t2 - self._t1) * 1000) if diff >= checkTime: text = 'CTime2 consume:{} ms, {}.{}'.format(diff, clsName, des) Log.Warn(text) self._t1 = t2 return diff
def RegisterBack(self, backData): try: if backData.status != Status.Ok: return backData.status if backData.res.code == 200: Log.Info("注册成功: {}".format(backData.res.raw.text)) return Status.Ok else: Log.Info("注册失败!!!, userId:{}, msg:{}".format( self.userId, backData.res.message)) return Status.RegisterError + backData.res.message except Exception as es: import sys cur_tb = sys.exc_info()[ 2] # return (exc_type, exc_value, traceback) e = sys.exc_info()[1] Log.Error(cur_tb, e) return Status.NetError
def RunDownload(self): while True: task = self._downloadQueue.get(True) self._downloadQueue.task_done() try: self._Download(task) except Exception as es: Log.Error(es) pass
def InitUpdateBack(self, data): try: r = QMessageBox.information(self, "更新", "当前版本{} ,检查到更新,是否前往更新\n{}".format(config.UpdateVersion, data), QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) if r == QMessageBox.Yes: QDesktopServices.openUrl(QUrl(config.UpdateUrl2)) except Exception as es: Log.Error(es)
def InitBack(self, backData): try: if backData.status == Status.Ok and backData.res.status == "ok": if len(backData.res.addresses) > 0: self.addresss = backData.res.addresses[:] # self.address = backData.res.addresses[0] Log.Info("初始化成功, Ips:{}".format(self.addresss)) self.initRes = backData.res return Status.Ok else: Log.Info("初始化失败, info:{}".format(backData.res)) return Status.Error except Exception as es: import sys cur_tb = sys.exc_info()[ 2] # return (exc_type, exc_value, traceback) e = sys.exc_info()[1] Log.Error(cur_tb, e) return Status.Error
def CancelConver(self, cleanFlag): taskIds = self.convertFlag.get(cleanFlag, set()) if not taskIds: return for taskId in taskIds: if taskId in self.convertLoad: del self.convertLoad[taskId] Log.Info("cancel convert taskId, {}".format(taskIds)) self.convertFlag.pop(cleanFlag) waifu2x.Delete(list(taskIds))
def HandlerTask2(self, taskId, data): try: info = self.tasks.get(taskId) if not info: Log.Warn("[Task] not find taskId:{}, {}".format(taskId, data)) return assert isinstance(info, QtHttpTask) if info.cleanFlag: taskIds = self.flagToIds.get(info.cleanFlag, set()) taskIds.discard(info.taskId) if info.backParam is None: info.callBack(data) else: info.callBack(data, info.backParam) del info.callBack del self.tasks[taskId] except Exception as es: Log.Error(es)
def AddBookByIdBack(self, backData): try: if backData.res.data.get("comic"): info = self.books.get(backData.res.data['comic']['_id']) if not info: info = Book() ToolUtil.ParseFromData(info, backData.res.data['comic']) self.books[info.id] = info return Status.Ok else: Log.Warn("未找到书籍, bookId:{}".format(backData)) return Status.NotFoundBook except Exception as es: import sys cur_tb = sys.exc_info()[ 2] # return (exc_type, exc_value, traceback) e = sys.exc_info()[1] Log.Error(cur_tb, e) return Status.NetError
def LoginBack(self, backData): try: if backData.status != Status.Ok: return backData.status if backData.res.code == 200 and backData.res.data.get("token"): self.isLogin = True self.token = backData.res.data.get("token") self.server.token = self.token Log.Info("登陆成功,userId: {}".format(self.userId)) if self.server.address: self.server.Send(req.InitAndroidReq()) return Status.Ok else: Log.Info("登陆失败!!!, userId:{}, msg:{}".format( self.userId, backData.res.message)) return Status.UserError + backData.res.message except Exception as es: Log.Error(es) return Status.NetError
def LeaveRoom(self): Log.Debug("level room, Url:{}".format(self.url)) self.timer.stop() self.close() self.url = "" for info in self.msgInfo.values(): info.setParent(None) self.msgInfo.clear() self.indexMsgId = 0 self.removeMsgId = 0 return