Example #1
0
 def updateApp(self, data):
     if sys.platform != "win32" or "version" not in data or "updateFile" not in data:
         self.createMessageDialog("更新平台失败!",
                                  "更新平台",
                                  style=wx.OK | wx.ICON_ERROR)
         return
         # 平台更新失败
     if not self.copyUpdateVbs():
         self.createMessageDialog("更新平台失败!",
                                  "更新平台",
                                  style=wx.OK | wx.ICON_ERROR)
         return
         # 平台更新失败
     # 停止App
     self.stopApp(data)
     # 调用更新脚本
     projectPath, updatePath, runPath = os.path.abspath(
         _GG("g_ProjectPath")), os.path.abspath(
             _GG("g_DataPath") + "update"), os.path.abspath(
                 _GG("GetDependPath")("run"))
     RunCmd(" ".join([
         os.path.join(runPath, "update.bat"),
         os.path.join(_GG("g_PythonPath"), "python.exe"),
         os.path.abspath(data["updateFile"]), data["version"], projectPath,
         updatePath, updatePath
     ]))
Example #2
0
def examDepend(request, userAuth, result):
    examType, did, reason = request.POST.get(
        "examType",
        None), request.POST.get("id", ""), request.POST.get("reason", "")
    if examType and did:
        try:
            depend = models.Depend.objects.get(id=int(did))
            if examType == "release":
                # 移除已发布的同名依赖库
                for d in models.Depend.objects.filter(
                        name=depend.name, status=Status.Released.value):
                    d.delete()
                # 更新当前依赖库的状态
                depend.status = Status.Released.value
                depend.save()
                result[
                    "requestTips"] = f"依赖库【{did},{depend.name},{depend.file_key},{depend.time}】成功发布!"
            elif examType == "delete":
                depend.delete()
                delText = "撤回"
                if depend.status == Status.Released.value:
                    delText = "下架"
                result[
                    "requestTips"] = f"依赖库【{did},{depend.name},{depend.file_key},{depend.time}】成功{delText}!"
                # 发送邮件通知
                sendMsgToAllMgrs(
                    f"管理员【{userAuth.uid.name}】于{timezone.localtime(timezone.now()).strftime('%Y-%m-%d %H:%M:%S')},{delText}了【{did},{depend.name},{depend.file_key},{depend.time}】依赖库。"
                )
        except Exception as e:
            _GG("Log").w(e)
            result["requestFailedTips"] = f"依赖库【{did}】发布/撤回/下架失败。"
    else:
        result["requestFailedTips"] = f"审核依赖库的信息不完整,请重新上传!"
Example #3
0
	def dispatch(self, event, data, callObj = None):
		try:
			self.__dispatchDepth += 1;
			eventId = event.value;
			listeners = self.__listeners[eventId];
			if len(listeners) > 0:
				for listener in listeners:
					if listener["state"] == EventState.NormalState:
						targetObj = listener["target"];
						# 判断并初始化targetObj的EventIdListByDispatched_属性
						if not hasattr(targetObj, "_EventKeyListByDispatched_"):
							targetObj._EventKeyListByDispatched_ = [];
						# 判断eventKey是否在targetObj.EventIdListByDispatched_中
						eventKey = str(eventId) + listener["callbackName"];
						if eventKey not in targetObj._EventKeyListByDispatched_:
							targetObj._EventKeyListByDispatched_.append(eventKey);
							# 执行所注册事件的方法
							try:
								getattr(targetObj, listener["callbackName"])(data);
							except Exception as e:
								raise e;
							finally:
								# 移除targetObj的EventKeyListByDispatched_属性
								targetObj._EventKeyListByDispatched_.remove(eventKey);
						else:
							raise Exception("It calls the function(\"{0}\") of object(id:\"{1}\") in recursion !".format(listener["callbackName"], id(targetObj)));
			else:
				_GG("Log").w("It has not event(\"{0}\") to dispatch !".format(eventId));
			self.__dispatchDepth -= 1;
			pass;
		except Exception as e:
			raise Exception("It doesn\'t dispatch the event(\"{0}\") ! [{1}] .".format(eventId, e));
Example #4
0
 def showInstallModMsgDialog(self, obj, modNameList=[], _retTuple=None):
     messageDialog = wx.MessageDialog(obj,
                                      "是否确认安装以下模块?\n" +
                                      "\n".join(modNameList),
                                      "校验import模块失败!",
                                      style=wx.YES_NO | wx.ICON_QUESTION)
     if messageDialog.ShowModal() == wx.ID_YES:
         # 安装模块
         for modName in modNameList:
             obj.showDetailTextCtrl(text="正在安装" + modName +
                                    "模块...\n此过程可能持续10+秒,请耐心等候...")
             obj.installPackageByPip(modName,
                                     pythonPath=_GG("g_PythonPath"))
         # 校验是否成功安装
         failedNameList = []
         installedPkgDict = obj.getInstalledPackagesByPip(
             pythonPath=_GG("g_PythonPath"))
         for modName in modNameList:
             if modName in installedPkgDict:
                 obj.showDetailTextCtrl(text="安装“{}”模块成功。".format(modName))
             else:
                 obj.showDetailTextCtrl(text="安装“{}”模块失败!".format(modName))
                 failedNameList.append(modName)
         return len(failedNameList) == 0
     return False
Example #5
0
 def runGame(self, event=None):
     pyExe = os.path.abspath(os.path.join(_GG("g_PythonPath"),
                                          "python.exe"))
     toolPath = GetPathByRelativePath("../", self._curPath)
     mainFileName = self.getFile(toolPath, "main")
     # 更新run.bat文件
     runFilePath = VerifyPath(os.path.join(toolPath, "run", "run.bat"))
     if os.path.exists(runFilePath):
         content = ""
         with open(runFilePath, "r", encoding="utf-8") as f:
             for line in f.readlines():
                 if re.search("set pyexe.*=.*", line):
                     line = "set pyexe=" + VerifyPath(pyExe) + "\n"
                 elif re.search("set toolpath.*=.*", line):
                     line = "set toolpath=" + VerifyPath(toolPath) + "\n"
                 elif re.search("set pjpath.*=.*", line):
                     line = "set pjpath=" + VerifyPath(
                         _GG("g_ProjectPath")) + "\n"
                 elif re.search("set mainfile.*=.*", line):
                     line = "set mainfile=" + VerifyPath(
                         mainFileName) + "\n"
                 content += line
         with open(runFilePath, "w", encoding="utf-8") as f:
             f.write(content)
     # 运行run.bat文件
     os.system(" ".join(["start", os.path.abspath(runFilePath)]))
     pass
Example #6
0
def reqAllArticles(ctx, msg):
    article = None
    try:
        aid = msg.get("startId", -1)
        if "endId" in msg:
            aid = msg["endId"]
        article = models.Article.objects.get(id=aid)
    except Exception as e:
        _GG("Log").w(e)
    limit = reqArticleLimit
    if article:
        if "endId" in msg:
            articleList = models.Article.objects.filter(
                Q(time_gte=article.time)
                | (Q(time=article.time) & Q(id__gte=article.id))).order_by(
                    "-time", "-id")
            limit = len(articleList)
        else:
            articleList = models.Article.objects.filter(
                Q(time_lte=article.time)
                | (Q(time=article.time) & Q(id__lte=article.id))).order_by(
                    "-time", "-id")
    else:
        articleList = models.Article.objects.filter(id__lte=startId).order_by(
            "-time", "-id")
    if "endId" not in msg and len(articleList) <= reqArticleLimit:
        limit = len(articleList)
    return {
        "items": [
            convertArticleInfo(articleInfo)
            for articleInfo in articleList[:limit]
        ],
        "isInTheEnd":
        len(articleList) <= reqArticleLimit,
    }
Example #7
0
 def onClickReplaceIB(textCtrl):
     ctx.SetValue("")
     ret, label = self.checkDirPath(
         _GG("CacheManager").getCache("selectedDirPath", ""))
     if not ret:
         self.appendRichTextTo(ctx,
                               "Warning:" + label + "!\n",
                               style="warning")
         return
     if not findIb._input.GetValue():
         self.appendRichTextTo(ctx,
                               "Warning:查找输入框不能为空!\n",
                               style="warning")
         return
     self.appendRichTextTo(ctx, "---- 开始替换 ---- \n", style="normal")
     ignoreCase, maxLevel = _GG("CacheManager").getCache(
         "ignoreCase",
         False), _GG("CacheManager").getCache("maxLevel", 10)
     self.replaceByDirPath(ctx,
                           _GG("CacheManager").getCache(
                               "selectedDirPath", ""),
                           findStr=findIb._input.GetValue(),
                           replaceStr=textCtrl.GetValue(),
                           ignoreCase=ignoreCase,
                           maxLevel=maxLevel)
     self.appendRichTextTo(ctx, "---- 替换结束 ---- \n", style="normal")
     # 更新替换撤销按钮
     if self.__replaceCache:
         self.__undoReplaceBtn.Enable(True)
Example #8
0
def loginRelease(request):
    resp = None
    result = {
        "isSuccess": False
    }
    if base_util.getPostAsBool(request, "isLogin"):
        tokenMd5, expires = "", 0
        if _GG("DecodeStr")(request.POST.get("token",
                                             "")) == _GG("GetReleaseToken")():
            randCode = random_util.randomMulti(32)
            # 32位随机码
            tokenMd5 = hashlib.md5("|".join([
                datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S.%f%z"),
                randCode
            ]).encode("utf-8")).hexdigest()
            expires = 12 * 60 * 60
            # 默认12小时
            cache.set(tokenMd5,
                      _GG("GetReleaseToken")(), expires)
            result["isSuccess"] = True
        else:
            result["tips"] = "输入Token有误或已过期!"
        resp = JsonResponse(result)
        if result["isSuccess"] == True:
            resp.set_cookie("jdreamheart_token",
                            _GG("EncodeStr")(tokenMd5), expires)
    elif base_util.getPostAsBool(request, "isLogout"):
        result["isSuccess"] = True
        resp = JsonResponse(result)
        resp.set_cookie("jdreamheart_token", None)
    return resp
Example #9
0
		def onRemoveItem(pageInfo, name):
			self.checkTreeItemsData(self.getNameList(pageInfo["category"], name), self.__treeItemsData, exData = {"isRemove" : True});
			self.saveTreeItemsData();
			_GG("EventDispatcher").dispatch(_GG("EVENT_ID").UPDATE_WINDOW_RIGHT_VIEW, {
				"destroyPage" : True,
				"key" : pageInfo["key"],
			});
			assetsPath = os.path.dirname(os.path.dirname(pageInfo["pagePath"])); # 中间还有一层tool
			# 移除依赖模块
			proDialog = wx.ProgressDialog("卸载依赖模块", "", style = wx.PD_APP_MODAL|wx.PD_ELAPSED_TIME|wx.PD_ESTIMATED_TIME|wx.PD_REMAINING_TIME|wx.PD_AUTO_HIDE);
			def onUninstall(mod, value, isEnd = False):
				if not isEnd:
					wx.CallAfter(proDialog.Update, value, f"正在卸载模块【{mod}】...");
				else:
					wx.CallAfter(proDialog.Update, value, f"成功卸载模块【{mod}】。");
				pass;
			def onFinish():
				# 移除工具文件夹
				if os.path.exists(assetsPath):
					shutil.rmtree(assetsPath);
				wx.CallAfter(proDialog.Update, 1, f"完成依赖模块的卸载。");
			threading.Thread(target = self._uninstallDependMods_, args = (pageInfo["key"], assetsPath+"/tool", _GG("g_PythonPath"), onUninstall, onFinish)).start();
			proDialog.Update(0, "开始卸载依赖模块...");
			proDialog.ShowModal();
			pass;
Example #10
0
	def onRestartGame(self, btn, event):
		if self.isPlaying():
			messageDialog = wx.MessageDialog(self, "游戏已经开始,是否确认重新开始?", "重新开始游戏", style = wx.YES_NO|wx.ICON_QUESTION);
			if messageDialog.ShowModal() == wx.ID_YES:
				_GG("EventDispatcher").dispatch(EVENT_ID.CHANGE_TURN_EVENT, {"isReset" : True});
				_GG("EventDispatcher").dispatch(EVENT_ID.RESTART_GAME_EVENT, {});
		pass;
Example #11
0
def detail(request):
    request.encoding = "utf-8"
    _GG("Log").d("detail get :", request.GET, "detail post :", request.POST)
    tkey = request.GET.get("t", "")
    if "submit" in request.POST:
        result = {
            "isLoginFailed": False,
            "isSuccess": False
        }
        try:
            userAuth = request.userAuth
            if userAuth:
                tool = models.Tool.objects.get(tkey=tkey)
                # 保存收藏
                if request.POST["submit"] == "collect":
                    result["isSuccess"] = doCollect(request.POST, userAuth,
                                                    tool.aid)
                    return JsonResponse(result)
                # 保存评论
                if request.POST["submit"] == "comment":
                    result["isSuccess"] = doComment(request.POST, userAuth,
                                                    tool.aid)
                    return JsonResponse(result)
            else:
                result["isLoginFailed"] = True
        except Exception as e:
            _GG("Log").w(e)
        return JsonResponse(result)
    return render(request, "detail.html", getResultByTkey(tkey))
Example #12
0
def home(request):
    _GG("Log").d("home GET :", request.GET, "; POST :", request.POST)
    if "isGetRecommendData" in request.POST:
        return JsonResponse(getRecommendData(request))
    isHasNewestInstaller, newestInstaller = getInstallerData()
    return render(
        request, "home.html", {
            "MAIN_HOME_TITLE":
            settings.MAIN_HOME_TITLE,
            "MAIN_HOME_URL":
            settings.MAIN_HOME_URL,
            "RESOURCE_URL":
            settings.RESOURCE_URL,
            "HOME_TITLE":
            settings.HOME_TITLE,
            "HOME_URL":
            settings.HOME_URL,
            "HEAD_TITLE":
            settings.HOME_TITLE,
            "WIKI_URL":
            settings.WIKI_URL,
            "ptipInfoList":
            getPtipData(),
            "isHasNewestInstaller":
            isHasNewestInstaller,
            "newestInstaller":
            newestInstaller,
            "recommendData":
            getRecommendData(request),
            "toolTotalCount":
            len(models.Tool.objects.all()),
            "articleTotalCount":
            len(models.Article.objects.filter(
                atype=ArticleType.Article.value)),
        })
Example #13
0
def getRecommendData(request):
    limit = 9
    allInfoList = models.Article.objects.all()
    total = len(allInfoList)
    interval = int(total / limit)
    if interval > 0:
        tmpTotal = total + (limit - total % limit) % limit

        def getNextIdx(curIdx):
            nextIdx = (curIdx + interval) % tmpTotal
            if nextIdx == nextIdx % interval and interval > 1:
                nextIdx += 1
            while nextIdx >= total:
                nextIdx = (nextIdx + interval) % tmpTotal
            return nextIdx

        # 获取开始下标
        startIdx = random.randint(0, total)
        if "rlStartIdx" in request.POST:
            try:
                rlStartIdx = int(request.POST["rlStartIdx"])
                if 0 <= rlStartIdx <= total:
                    startIdx = rlStartIdx
            except Exception as e:
                _GG("Log").w(e)
        # 获取返回列表
        _GG("Log").d("GetRecommendData params:", total, interval, tmpTotal,
                     startIdx)
        retInfoList, idxList = [], []
        while len(retInfoList) < limit:
            if startIdx in idxList:
                break
            # 添加返回信息
            retInfoList.append(getRecommendInfoByArticle(
                allInfoList[startIdx]))
            idxList.append(startIdx)
            # 获取下一个下标
            startIdx = getNextIdx(startIdx)
        return {
            "startIdx":
            startIdx,
            "htmlData":
            bytes.decode(
                render(request, "tilelist.html", {
                    "infoList": retInfoList
                }).content),
        }
    return {
        "startIdx":
        0,
        "htmlData":
        bytes.decode(
            render(
                request, "tilelist.html", {
                    "infoList": [
                        getRecommendInfoByArticle(articleInfo)
                        for articleInfo in allInfoList[:limit]
                    ],
                }).content),
    }
Example #14
0
 def initWindowMethods(self):
     self.initMainWindowMethods()
     _GG("WindowObject").CreateMessageDialog = self.createMessageDialog
     # 设置显示消息弹窗函数
     _GG("WindowObject").CreateDialogCtr = self.createDialogCtr
     # 设置显示弹窗控制器
     _GG("WindowObject").CreateWxDialog = self.createWxDialog
Example #15
0
 def bindBehaviors(self):
     _GG("BehaviorManager").bindBehavior(
         self, {
             "path": "serviceBehavior/ToolServiceBehavior",
             "basePath": _GG("g_CommonPath") + "behavior/"
         })
     pass
Example #16
0
def update(request, result, wtype=0):
    cid = request.POST.get("cid", None)
    if cid:
        try:
            c = models.Carouse.objects.get(id=int(cid))
            opType = request.POST.get("opType", "")
            if opType == "enable":
                isEnable = base_util.getPostAsBool(request, "isEnable")
                state = Status.Close.value
                if isEnable:
                    state = Status.Open.value
                if c.state != state:
                    c.update_time = timezone.now()
                    c.state = state
                    c.save()
                result["isSuccess"] = True
            elif opType == "update":
                form = CarouseForm(instance=c)
                html = HttpResponse(form.as_p())
                result["id"] = c.id
                result["sortId"] = c.sort_id
                result["html"] = html.getvalue().decode()
                result["isSuccess"] = True
        except Exception as e:
            _GG("Log").w(e)
    pass
Example #17
0
 def bindBehaviors(self):
     _GG("BehaviorManager").bindBehavior(
         self, {
             "path": "formatBehavior/NumFormatBehavior",
             "basePath": _GG("g_CommonPath") + "behavior/"
         })
     pass
Example #18
0
def getVerifyCode(request):
    email = request.POST.get("email", "")
    if not email:
        return JsonResponse({
            "isSuccess": False,
            "tips": "邮箱信息不能为空!"
        })
    # 生成随机验证码
    verifyCode = random_util.randomNum(6)
    # 6位随机码
    # 缓存验证码
    expires = 2 * 60
    # 缓存2分钟
    cache.set("|".join(["verify_code", "register", email]), verifyCode,
              expires)
    # 发送邮件给指定邮箱
    try:
        send_mail("PyToolsIP",
                  "平台验证码:" + verifyCode,
                  settings.EMAIL_HOST_USER, [email],
                  fail_silently=False)
    except Exception as e:
        _GG("Log").w(e, f"-> verifyCode[{verifyCode}]")
        return JsonResponse({
            "isSuccess": False,
            "tips": "验证码发送失败,请检查邮箱是否正确!"
        })
    return JsonResponse({
        "isSuccess": True,
        "expires": expires
    })
Example #19
0
 def onClickFindIB(textCtrl):
     ctx.SetValue("")
     ret, label = self.checkDirPath(
         _GG("CacheManager").getCache("selectedDirPath", ""))
     if not ret:
         self.appendRichTextTo(ctx,
                               "Warning:" + label + "!\n",
                               style="warning")
         return
     if not textCtrl.GetValue():
         self.appendRichTextTo(ctx,
                               "Warning:查找输入框不能为空!\n",
                               style="warning")
         return
     self.appendRichTextTo(ctx, "---- 开始查找 ---- \n", style="normal")
     ignoreCase, maxLevel = _GG("CacheManager").getCache(
         "ignoreCase",
         False), _GG("CacheManager").getCache("maxLevel", 10)
     self.findByDirPath(ctx,
                        _GG("CacheManager").getCache(
                            "selectedDirPath", ""),
                        findStr=textCtrl.GetValue(),
                        ignoreCase=ignoreCase,
                        maxLevel=maxLevel)
     self.appendRichTextTo(ctx, "---- 查找结束 ---- \n", style="normal")
Example #20
0
 def bindBehaviors(self):
     _GG("BehaviorManager").bindBehavior(
         self, {
             "path": "ConfigParseBehavior/JsonConfigBehavior",
             "basePath": _GG("g_CommonPath") + "behavior/"
         })
     pass
Example #21
0
 def verifyModuleMap(self, obj, _retTuple=None):
     jsonPath = _GG("g_DataPath") + "depend_map.json"
     if os.path.exists(jsonPath):
         modNameList = []
         uninstallNameList = []
         # 读取json文件
         with open(jsonPath, "rb") as f:
             moduleMap = json.loads(f.read().decode("utf-8", "ignore"))
             # 校验模块
             installedPkgDict = obj.getInstalledPackagesByPip(
                 pythonPath=_GG("g_PythonPath"))
             for modName, depend in moduleMap.items():
                 if isinstance(depend, dict) and not depend["map"]:
                     if modName in installedPkgDict:
                         uninstallNameList.append(modName)
                 else:
                     if modName not in installedPkgDict:
                         modNameList.append(modName)
         if len(modNameList) == 0:
             if len(uninstallNameList) > 0:
                 wx.CallAfter(self.showUninstallModMsgDialog, obj,
                              uninstallNameList)
             return True
         else:
             return False, obj.showInstallModMsgDialog, modNameList
Example #22
0
 def receive(self, text_data):
     _GG("Log").d("ws receive:", text_data)
     data = json.loads(text_data)
     # 校验数据
     if "req" not in data:
         self.notify("WS_onError", "Error! No Req!")
         return
     if "ctx" not in data:
         self.notify("WS_onError", "Error! No Ctx!")
         return
     if "msg" not in data:
         self.notify("WS_onError", "Error! No Msg!")
         return
     # 处理数据
     reqName = data["req"]
     resp, status = {}, "success"
     if reqName in self.__listeners:
         ctx = data["ctx"]
         # 校验上下文内容
         if hasattr(self, "onCheckCtx"):
             if getattr(self, "onCheckCtx")(ctx):
                 resp = self.__listeners[reqName](ctx, data["msg"])
             else:
                 status = "failure"
         else:
             resp = self.__listeners[reqName](ctx, data["msg"])
     else:
         status = "failure"
     # 发送消息
     if "resp" in data and data["resp"]:
         self.notify(data["resp"], resp, status=status)
     pass
Example #23
0
	def onEnterItem(self, item, event):
		if self.currentItem != item:
			if self.currentItem:
				self.currentItem.updateBackgroundColor(_GG("AppConfig")["searchItemBlurColor"]);
			self.currentItem = item; # 重置当前Item
			self.currentItem.updateBackgroundColor(_GG("AppConfig")["searchItemFocusColor"]);
			self.updateItemBgColorTimer.Start(200); # 启动更新背景颜色定时器
Example #24
0
 def update(self, dt):
     for event in pygame.event.get():
         eventId = GetEventIdByEventType(event.type);
         if eventId:
             _GG("EventDispatcher").dispatch(eventId, {"dt" : dt});
         if event.type == pygame.KEYDOWN:
             if event.key == pygame.K_F11:
                 self.__isFullScreen = not self.__isFullScreen;
                 if self.__isFullScreen:
                     pygame.display.set_mode(_GG("GameConfig").PjConfig().Get("winSize"), flags = pygame.FULLSCREEN);
                 else:
                     pygame.display.set_mode(_GG("GameConfig").PjConfig().Get("winSize"));
             else:
                 eventId = GetEventIdByEventKey(event.key);
                 if eventId:
                     _GG("EventDispatcher").dispatch(eventId, {"dt" : dt});
         elif event.type == pygame.QUIT:
             self.destroyScreen();
             return;
     pygame.event.pump();
     # 执行定时器的update方法
     _GG("TimerManager").update(dt);
     # 执行场景的update方法
     if self.__runningScene:
         try:
             self.__runningScene(dt);
             self.getScreen().blit(self.__runningScene.surf, (0, 0)); # 更新场景
         except Exception as e:
             _GG("Log").e(f"Error to run Scene! Err[{e}]");
     pygame.display.update();
Example #25
0
def uploadExe(request, userAuth, result, isSwitchTab):
    if not isSwitchTab:
        if request.POST.get("opType", "") == "delete":
            edid = request.POST.get("id", "")
            try:
                exeDetail = models.ExeDetail.objects.get(id=int(edid))
                exeDetail.delete()
                if len(models.ExeDetail.objects.filter(
                        eid=exeDetail.eid)) == 0:
                    exeDetail.eid.delete()
                result[
                    "requestTips"] = f"依赖程序【{exeDetail.eid.name},{exeDetail.version}】成功下架!"
                # 发送邮件通知
                sendMsgToAllMgrs(
                    f"管理员【{userAuth.uid.name}】于{timezone.localtime(timezone.now()).strftime('%Y-%m-%d %H:%M:%S')},下架了【{exeDetail.eid.name},{exeDetail.version}】依赖程序。"
                )
            except Exception as e:
                _GG("Log").w(e)
                result["requestFailedTips"] = f"依赖程序【{edid}】下架失败。"
        else:
            saveExe(request, userAuth, result)
    # 所有线上工具的名称
    result["olExeInfolist"] = [{
        "name": exeInfo.name,
        "path": exeInfo.path
    } for exeInfo in models.Exe.objects.all().order_by('-name')]
    # 返回线上版本数据
    result["onlineInfoList"] = [{
        "id": exeInfo.id,
        "name": exeInfo.eid.name,
        "version": exeInfo.version,
        "time": exeInfo.time,
        "changelog": exeInfo.changelog,
        "url": exeInfo.file_path.url,
    } for exeInfo in models.ExeDetail.objects.all().order_by('-time')]
Example #26
0
 def __unload__(self):
     if isExist_G():  # window控制类中的析构函数,涉及到全局变量时,要判断全局变量是否存在
         self.unregisterEventMap()
         # 注销事件
         _GG("TimerManager").clearAllTimer()
         # 清除所有定时器
     self.delCtrMap()
Example #27
0
 def requireBehaviorByConfig(self, behaviorConfig):
     behavior = None
     if isinstance(behaviorConfig, _GG("BaseBehavior")):
         if hasattr(behaviorConfig, "behaviorId_"):
             behavior = behaviorConfig
         else:
             _GG("Log").w(
                 "Bind behavior fail ! Because of no behaviorId_ .")
     elif isinstance(behaviorConfig, str):
         behavior = self.requireBehavior(behaviorConfig)
         if not hasattr(behavior, "behaviorId_"):
             bid = _GG("getUniqueId")()
             # 组件的唯一ID
             behavior.setBehaviorId("behavior_" + str(bid))
             # 设置组件的唯一ID
     elif isinstance(behaviorConfig, dict):
         requireFunc = self.requireBehavior
         if "require" in behaviorConfig:
             requireFunc = behavior["require"]
         if "path" in behaviorConfig:
             basePath = ""
             if "basePath" in behaviorConfig:
                 basePath = behaviorConfig["basePath"]
             behavior = requireFunc(behaviorConfig["path"],
                                    basePath=basePath)
             # 设置组件ID
             if not hasattr(behavior, "behaviorId_"):
                 bid = _GG("getUniqueId")()
                 # 组件的唯一ID
                 behavior.setBehaviorId("behavior_" + str(bid))
                 # 设置组件的唯一ID
             # 设置组件名称
             if "name" in behaviorConfig:
                 behavior.setBehaviorName(behaviorConfig["name"])
     return behavior
Example #28
0
 def onDeleteItem(self, event):
     if not self.__popupMenuItem:
         return
     itemText = self.getUI().GetItemText(self.__popupMenuItem)
     itemData = self.__itemPageDataDict.get(self.__popupMenuItem, None)
     if itemData:
         if not itemData["category"]:
             self.showMessageDialog("不能删除该工具【%s】!" % itemText)
             return
         if self.showMessageDialog(
                 "是否确认删除工具【%s】?" %
             (itemData["category"] + "/" + itemText)) == wx.ID_YES:
             self.removeItem(itemData["key"])
     else:
         itemDataList = self.getItemDataListByItem(self.__popupMenuItem,
                                                   itemDataList=[])
         if len(itemDataList) == 0:
             return
         idx = itemDataList[0]["category"].find(itemText)
         if idx == -1:
             _GG("Log").w("There is not text[%s] in category[%s]!" %
                          (itemText, itemDataList[0]["category"]))
             return
         category = itemDataList[0]["category"][:idx] + itemText
         toolNamePathList = []
         for itemData in itemDataList:
             toolNamePathList.append("/".join([
                 itemData["category"][itemData["category"].find(itemText):],
                 itemData["title"]
             ]))
         if self.showMessageDialog(
                 "是否确认删除分类【%s】?\n该分类包含工具:\n%s" %
             (category, "\n".join(toolNamePathList))) == wx.ID_YES:
             for itemData in itemDataList:
                 self.removeItem(itemData["key"])
 def getPipInstallImage(self, obj):
     if os.path.exists(_GG("g_DataPath") + "config/setting_cfg.json"):
         cfg = obj.readJsonFile(
             _GG("g_DataPath") + "config/setting_cfg.json")
         if cfg:
             return cfg.get("pip_install_image", "")
     return ""
Example #30
0
 def startApp(self, data):
     if sys.platform == "win32":
         # 运行执行程序
         exeName = "pytoolsip.exe"
         if os.path.exists(os.path.join(_GG("g_ProjectPath"), exeName)):
             os.system(" ".join([
                 "start", "/d",
                 os.path.abspath(_GG("g_ProjectPath")), exeName
             ]))
             # 启动app
             return
         # 直接运行脚本
         pyName = "pytoolsip.py"
         if os.path.exists(os.path.join(_GG("g_ProjectPath"), pyName)):
             pythonPath = "python"
             if os.path.exists(_GG("g_PythonPath")):
                 pythonPath = os.path.abspath(
                     os.path.join(_GG("g_PythonPath"), "python.exe"))
             os.system(" ".join([
                 "start", "/d",
                 os.path.abspath(_GG("g_ProjectPath")), pythonPath, pyName
             ]))
             # 启动app
             return
         # 运行run.bat脚本
         batName = "run.bat"
         if os.path.exists(os.path.join(_GG("g_ProjectPath"), batName)):
             os.system(" ".join([
                 "start", "/d",
                 os.path.abspath(_GG("g_ProjectPath")), batName
             ]))
             # 启动run.bat
             return
         # 运行失败
         _GG("Log").e("Failed to start App!")