def doDelete(self, dialog): deleteList = dialog.deleteList for x in deleteList: if isinstance(x,self.parent().parent().nodeWidget ): NetworkService.request( self.parent().parent().module, "delete/node", {"key": x.data["key"]}, secure=True, modifies=True ) elif isinstance(x,self.parent().parent().leafWidget ): NetworkService.request( self.parent().parent().module, "delete/leaf", {"key": x.data["key"]}, secure=True, modifies=True )
def setPayedSucceeded(self, response): self.done += 1 if self.done + self.failed == self.total: conf["mainWindow"].log("success", translate(self.txtSuccess, count=self.done)) NetworkService.notifyChange(self.parent().parent().module)
def reloadData(self, paramsOverride=None): assert self.node is not None, "reloadData called while self.node is None" self.entryFrame.clear() self._currentRequests = [] if paramsOverride: params = paramsOverride.copy() else: params = {"node": self.node} if "amount" not in params: params["amount"] = self._batchSize r = NetworkService.request(self.module, "list/node", params, successHandler=self.onRequestSucceded, failureHandler=self.showErrorMsg) r.reqType = "node" self._currentRequests.append(r) r = NetworkService.request(self.module, "list/leaf", params, successHandler=self.onRequestSucceded, failureHandler=self.showErrorMsg) r.reqType = "leaf" self._currentRequests.append(r) from handler.tree import TreeHandler # import must be here, otherwise it throws an importError if isinstance(conf["mainWindow"].currentPane, TreeHandler): conf["theApp"].setPath(self.module + "/list/" + self.node)
def reloadData(self, paramsOverride=None): assert self.node is not None, "reloadData called while self.node is None" self.entryFrame.clear() self._currentRequests = [] if paramsOverride: params = paramsOverride.copy() else: params = {"node": self.node} if "amount" not in params: params["amount"] = self._batchSize r = NetworkService.request(self.module, "list/node", params, successHandler=self.onRequestSucceded, failureHandler=self.showErrorMsg) r.reqType = "node" self._currentRequests.append(r) r = NetworkService.request(self.module, "list/leaf", params, successHandler=self.onRequestSucceded, failureHandler=self.showErrorMsg) r.reqType = "leaf" self._currentRequests.append(r)
def doDelete(self, dialog): deleteList = dialog.deleteList for x in deleteList: NetworkService.request(self.parent().parent().module, "delete", {"key": x}, secure=True, modifies=True)
def onDrop(self, event): """ Check if we can handle that drop and make the entries direct children of this node """ try: nodeType, srcKey = event.dataTransfer.getData("Text").split("/") except: return NetworkService.request( self.module, "move", { "skelType": nodeType, "key": srcKey, "destNode": self.data["key"] }, failureHandler=lambda req, code: conf["mainWindow"].log( "error", translate( "Node cannot be moved, error {code}.", code=code ) ), modifies=True, secure=True ) event.preventDefault() event.stopPropagation()
def onRequestSucceded(self, req): if not req in self._currentRequests: return self._currentRequests.remove(req) data = NetworkService.decode(req) for skel in data["skellist"]: if req.reqType == "node": n = self.nodeWidget(self.module, skel, data["structure"]) else: n = self.leafWidget(self.module, skel, data["structure"]) self.entryFrame.appendChild(n) self.entryFrame.sortChildren(self.getChildKey) if "cursor" in data.keys() and len(data["skellist"]) == req.params["amount"]: self._currentCursor[req.reqType] = data["cursor"] req.params["cursor"] = data["cursor"] r = NetworkService.request(self.module, "list/%s" % req.reqType, req.params, successHandler=self.onRequestSucceded, failureHandler=self.showErrorMsg) r.reqType = req.reqType self._currentRequests.append(r) else: self._currentCursor[req.reqType] = None self.actionBar.resetLoadingState()
def onDrop(self, event): """ We got a drop event. Make that item a direct child of our rootNode """ srcKey = event.dataTransfer.getData("Text") NetworkService.request(self.module,"reparent",{"item":srcKey,"dest":self.rootNode}, secure=True, modifies=True ) event.stopPropagation()
def setSelection(self, selection): """ Set our current value to 'selection' @param selection: The new entry that this bone should reference @type selection: dict """ self.selection = selection if selection: NetworkService.request( self.destModule, "view/node/" + selection["dest"]["key"], successHandler=self.onSelectionDataAvailable, cacheable=True) self.selectionTxt["value"] = translate("Loading...") if utils.getImagePreview(self.selection) is not None: self.previewImg["src"] = utils.getImagePreview(self.selection) self.previewImg["style"]["display"] = "" else: self.previewImg["style"]["display"] = "none" else: self.selectionTxt["value"] = "" self.previewImg["style"]["display"] = "none" self.updateButtons()
def editDir(self, dialog, dirName): NetworkService.request(self.parent().parent().module, "edit/node", { "key": dialog.dirKey, "name": dirName }, secure=True, modifies=True)
def nextChunk(self, cursor=None): if cursor: self.params["cursor"] = cursor NetworkService.request(self.module, "list", self.params, successHandler=self.nextChunkComplete, failureHandler=self.nextChunkFailure)
def save(self, data): self.wasInitialRequest = not len(data)>0 if self.module=="_tasks": return #FIXME! else: if not data: NetworkService.request(self.module,"view/%s" % self.key, successHandler=self.setData, failureHandler=self.showErrorMsg) else: NetworkService.request(self.module, "add", data, secure=len(data)>0, successHandler=self.setData, failureHandler=self.showErrorMsg )
def rebuildPath(self): """ Rebuild the displayed path-list. """ self.pathList.removeAllChildren() NetworkService.request(self.module, "view/node/%s" % self.node, successHandler=self.onPathRequestSucceded)
def onSuccess(self, *args, **kwargs): """ Internal callback - The upload succeeded. """ for v in self.responseValue["values"]: self.uploadSuccess.fire(self, v) NetworkService.notifyChange("file") self.replaceWithMessage("Upload complete", isSuccess=True)
def startPolling(self, *args, **kwargs): """ Start querying the server """ NetworkService.request("user", "view/self", successHandler=self.onUserTestSuccess, failureHandler=self.onUserTestFail, cacheable=False)
def doCloneHierarchy(self, sender=None ): if self.applicationType == EditWidget.appHierarchy: NetworkService.request( self.module, "clone", { "fromRepo" : self.node, "toRepo" : self.node, "fromParent" : self.clone_of, "toParent" : self.key }, secure=True, successHandler=self.cloneComplete ) else: NetworkService.request( conf[ "modules" ][ self.module ][ "rootNodeOf" ], "clone", { "fromRepo" : self.clone_of, "toRepo" : self.key }, secure=True, successHandler=self.cloneComplete )
def onDrop(self, event): """ We received a drop. Test wherever its means "make it a child of us", "insert before us" or "insert after us" and initiate the corresponding NetworkService requests. """ event.stopPropagation() event.preventDefault() height = self.element.offsetHeight offset = event.pageY - self.element.offsetTop srcKey = event.dataTransfer.getData("Text") if offset >= height * 0.20 and offset <= height * 0.80: print( "insert into" ) # Just make the item a child of us NetworkService.request(self.module,"reparent",{"item":srcKey,"dest":self.data["key"]}, secure=True, modifies=True ) elif offset < height * 0.20: #Insert this item *before* the current item print( "insert before" ) parentID = self.data["parententry"] if parentID: lastIdx = 0 for c in self.parent()._children: if "data" in dir(c) and "sortindex" in c.data.keys(): if c == self: break lastIdx = c.data["sortindex"] newIdx = str((lastIdx+self.data["sortindex"])/2.0) req = NetworkService.request(self.module,"reparent",{"item":srcKey,"dest":parentID}, secure=True, successHandler=self.onItemReparented ) req.newIdx = newIdx req.item = srcKey elif offset > height * 0.80: #Insert this item *after* the current item print( "insert after" ) parentID = self.data["parententry"] if parentID: lastIdx = time() doUseNextChild = False for c in self.parent()._children: if "data" in dir(c) and "sortindex" in c.data.keys(): if doUseNextChild: lastIdx = c.data["sortindex"] break if c == self: doUseNextChild = True newIdx = str((lastIdx+self.data["sortindex"])/2.0) req = NetworkService.request(self.module,"reparent",{"item":srcKey,"dest":parentID}, secure=True, successHandler=self.onItemReparented ) req.newIdx = newIdx req.item = srcKey
def update(self): user = conf.get("currentUser") if not user: NetworkService.request("user", "view/self", successHandler=self.onCurrentUserAvailable, cacheable=False) return if "root" in user["access"]: self.show()
def onItemReparented(self, req): """ Called after a reparent-request finished; run the setIndex request afterwards. """ assert "newIdx" in dir(req) NetworkService.request(self.module, "setIndex", { "item": req.item, "index": req.newIdx }, secure=True, modifies=True)
def onVerifyClick(self, sender = None): if not self.otp["value"]: return # fixme self.verifyBtn["disabled"] = True self.lock() NetworkService.request("user", "f2_timebasedotp/otp", params={"otptoken": self.otp["value"]}, secure=True, successHandler=self.doVerifySuccess, failureHandler=self.doVerifyFailure)
def __init__(self, master): self.master = master self._createView() # self.master.protocol("WM_DELETE_WINDOW", self._onClosed) self.GpsService = GpsService(lambda newPos: self.master.after( 0, lambda: self._onGpsPositionChanged(newPos))) self.GpsService.start() self.NetworkService = NetworkService(lambda msg: self.master.after( 0, lambda: self._onNetworkMessage(msg))) self.NetworkService.start() self.lastKnownPosition = None self.master.after(2000, self._broadCastPosition) self.master.after(0, self.animation)
def onLoginClick(self, sender = None): if not (self.username["value"] and self.password["value"]): return # fixme self.loginBtn["disabled"] = True self.lock() NetworkService.request("user", "auth_userpassword/login", params={"name": self.username["value"], "password": self.password["value"]}, secure=True, successHandler=self.doLoginSuccess, failureHandler=self.doLoginFailure)
def __init__(self, module, rootNode=None, node=None, isSelector=False, *args, **kwargs): """ @param modul: Name of the modul we shall handle. Must be a list application! @type modul: string @param rootNode: The rootNode we shall display. If None, we try to select one. @type rootNode: String or None @param node: The node we shall display at start. Must be a child of rootNode @type node: String or None """ super(TreeWidget, self).__init__() self["class"].append("tree") self.module = module self.rootNode = rootNode self.node = node or rootNode self.actionBar = ActionBar(module, "tree") self.appendChild(self.actionBar) self.pathList = html5.Div() self.pathList["class"].append("breadcrumb") self.appendChild(self.pathList) self.entryFrame = SelectableDiv(self.nodeWidget, self.leafWidget) self.appendChild(self.entryFrame) self.entryFrame.selectionActivatedEvent.register(self) self._batchSize = 99 self._currentCursor = {"node": None, "leaf": None} self._currentRequests = [] self.rootNodeChangedEvent = EventDispatcher("rootNodeChanged") self.nodeChangedEvent = EventDispatcher("nodeChanged") self.isSelector = isSelector if self.rootNode: self.reloadData() else: NetworkService.request(self.module, "listRootNodes", successHandler=self.onSetDefaultRootNode) self.path = [] self.sinkEvent("onClick") #Proxy some events and functions of the original table for f in [ "selectionChangedEvent", "selectionActivatedEvent", "cursorMovedEvent", "getCurrentSelection", "selectionReturnEvent" ]: setattr(self, f, getattr(self.entryFrame, f)) self.actionBar.setActions(self.defaultActions + (["select", "close"] if isSelector else []))
def __init__(self, module, rootNode=None, isSelector=False, context=None, *args, **kwargs): """ @param module: Name of the modul we shall handle. Must be a hierarchy application! @type module: string @param rootNode: The repository we shall display. If none, we try to select one. @type rootNode: String or None """ super(HierarchyWidget, self).__init__() self.module = module self.rootNode = rootNode self.actionBar = ActionBar(module, "hierarchy") self.appendChild(self.actionBar) self.entryFrame = html5.Ol() self.entryFrame["class"].append("hierarchy") self.appendChild(self.entryFrame) self.selectionChangedEvent = EventDispatcher("selectionChanged") self.selectionActivatedEvent = EventDispatcher("selectionActivated") self.rootNodeChangedEvent = EventDispatcher("rootNodeChanged") self._currentCursor = None self._currentRequests = [] self.addClass("supports_drop") self.isSelector = isSelector self._expandedNodes = [] self.context = context if self.rootNode: self.reloadData() else: NetworkService.request(self.module, "listRootNodes", self.context or {}, successHandler=self.onSetDefaultRootNode, failureHandler=self.showErrorMsg) self.path = [] self.sinkEvent("onClick", "onDblClick") ##Proxy some events and functions of the original table #for f in ["selectionChangedEvent","selectionActivatedEvent","cursorMovedEvent","getCurrentSelection"]: # setattr( self, f, getattr(self.table,f)) self.actionBar.setActions( ["selectrootnode", "add", "edit", "clone", "delete"] + (["select", "close"] if isSelector else []) + ["reload"]) self.sinkEvent("onDrop", "onDragOver")
def update(self): user = conf.get("currentUser") if not user: NetworkService.request("user", "view/self", successHandler=self.onCurrentUserAvailable, cacheable=False) return aa = html5.A() aa["title"] = user["name"] aa["class"].append("icon accountmgnt") aa.appendChild(html5.TextNode(user["name"])) self.appendChild(aa)
def doSave(self, closeOnSuccess=False): self.closeOnSuccess = closeOnSuccess data = { "count": self.count._getValue(), "kind": "2", "dtstart": self.dtstart # , "byweekday" : [box["name"] for box in self.byweekday if box["checked"]] } # r = rrule.rrule(2, dtstart=datetime(2014, 7,1, 18,00), count=7) NetworkService.request(self.module, "addrecurrent/%s" % self.key, data, secure=True, successHandler=self.setData, failureHandler=self.showErrorMsg)
def onClick(self, *args, **kwargs): conf["theApp"].setPath(self.moduleName + "/list") if self.mode == "normal" and not self.widgetsDomElm.children(): self.addWidget(self._createWidget()) if self.requestedViews is None and "views.request" in self.moduleInfo: conf["mainWindow"].lock() NetworkService.request( self.moduleName, self.moduleInfo["views.request"], successHandler=self._onRequestViewsAvailable) super(ListHandler, self).onClick(*args, **kwargs)
def fetchNext(self): if not self.sessionID: return if not self.request: if len(self.queue) > 0: self.request = NetworkService.request(self.queue[-1][1], extraHeaders={ "Authorization": "GoogleLogin auth=" + self.sessionID }) self.request.finished.connect(self.fetchNext) return return data = bytes(self.request.readAll()).decode("UTF-8") self.request.deleteLater() self.request = None currentRequestData = self.queue.pop() dom = parseString(data) try: self.data[currentRequestData[0]]["total"] = int( dom.getElementsByTagName('dxp:aggregates')[0]. getElementsByTagName("dxp:metric")[0].getAttribute("value")) except: # We somehow got invalid data return items = dom.getElementsByTagName('entry') for item in items: src = item.getElementsByTagName("dxp:dimension")[0].getAttribute( "value") visits = int( item.getElementsByTagName("dxp:metric")[0].getAttribute( "value")) self.data[currentRequestData[0]][src] = visits if len(self.queue) > 0: self.request = NetworkService.request(self.queue[-1][1], extraHeaders={ "Authorization": "GoogleLogin auth=" + self.sessionID }) self.request.finished.connect(self.fetchNext) if not self.isDisplayingStats: self.isDisplayingStats = True self.imgLbl.deleteLater() self.layout.addWidget(self.plot) self.layout.addWidget(self.tableView) self.model.setData(self.data) self.plot.setData(self.data)
def onSelectionDataAvailable(self, req): data = NetworkService.decode(req) assert self.data["dest"]["key"] == data["values"]["key"] self.data["dest"] = data["values"] self.updateLabel() self.previewImg.setFile(self.data["dest"])
def onSelectionDataAvailable(self, req): """ We just received the full information for this entry from the server and can start displaying it """ data = NetworkService.decode(req) assert self.selection["dest"]["key"] == data["values"]["key"] if self.using: res = (utils.formatString( utils.formatString(self.format, data["values"], data["structure"], prefix=["dest"], language=conf["currentlanguage"]), self.selection["rel"], self.using, prefix=["rel"], language=conf["currentlanguage"]) or data["values"]["key"]) else: res = (utils.formatString( utils.formatString(self.format, data["values"], data["structure"], prefix=["dest"], language=conf["currentlanguage"]), data["values"], data["structure"], language=conf["currentlanguage"]) or data["values"]["key"]) self.selectionTxt["value"] = res