Exemple #1
0
    def update(self):
        user = conf.get("currentUser")
        if not user:
            NetworkService.request("user",
                                   "view/self",
                                   successHandler=self.onCurrentUserAvailable,
                                   cacheable=False)
            return

        aitem = html5.Div()
        aitem["class"] = ["item", "has-hover", "item--small"]
        # userinfo
        usrinfo = html5.Div()
        usermail = html5.Span()
        usermail.appendChild(html5.TextNode(user["name"]))
        aitem.appendChild(usermail)
        self.popoutlist.appendChild(aitem)

        self["title"] = user["name"]
        self.currentUser = user["key"] or None
        self.addClass("vi-tb-accountmgnt")
        try:
            self.btn["text"] = "%s. %s" % (user["firstname"][0],
                                           user["lastname"])
        except:
            self.btn["text"] = user["name"]
Exemple #2
0
    def __init__(self,
                 module,
                 rootNode=None,
                 node=None,
                 context=None,
                 *args,
                 **kwargs):
        """
			:param module: Name of the module we shall handle. Must be a hierarchy application!
			:type module: str
			:param rootNode: The repository we shall display. If none, we try to select one.
			:type rootNode: str or None
		"""
        super(TreeWidget, self).__init__()
        self.addClass("vi-widget vi-widget--hierarchy is-drop-target")
        self.sinkEvent("onKeyDown", "onKeyUp", "onDrop", "onDragOver")

        self.module = module
        self.rootNode = rootNode
        self.node = node or rootNode
        self.context = context

        # Action bar
        self.actionBar = ActionBar(module, "tree")
        self.actionBar.setActions(self.getActions(), widget=self)
        self.appendChild(self.actionBar)

        # Entry frame
        self.entryFrame = html5.Ol()
        self.entryFrame.addClass("hierarchy")
        self.appendChild(self.entryFrame)

        # States
        self._isCtrlPressed = False
        self._expandedNodes = []
        self._currentRequests = []
        self.path = []

        # Selection
        self.selectionCallback = None
        self.selectionAllow = TreeItemWidget
        self.selectionMulti = True
        self.selection = []

        # Events
        self.selectionChangedEvent = EventDispatcher("selectionChanged")
        self.selectionActivatedEvent = EventDispatcher("selectionActivated")
        self.rootNodeChangedEvent = EventDispatcher("rootNodeChanged")
        self.nodeChangedEvent = EventDispatcher("nodeChanged")

        # Either load content or get root Nodes
        if self.rootNode:
            self.reloadData()
        else:
            NetworkService.request(self.module,
                                   "listRootNodes",
                                   self.context or {},
                                   successHandler=self.onSetDefaultRootNode,
                                   failureHandler=self.showErrorMsg)
Exemple #3
0
 def editDir(self, dialog, dirName):
     NetworkService.request(self.parent().parent().module,
                            "edit/node", {
                                "key": dialog.dirKey,
                                "name": dirName
                            },
                            secure=True,
                            modifies=True)
Exemple #4
0
 def doDelete(self, dialog):
     deleteList = dialog.deleteList
     for x in deleteList:
         NetworkService.request(self.parent().parent().module,
                                "delete", {"key": x},
                                secure=True,
                                modifies=True,
                                successHandler=self.deletedSuccess,
                                failureHandler=self.deletedFailed)
Exemple #5
0
    def rebuildPath(self):
        """
			Rebuild the displayed path-list.
		"""
        self.pathList.removeAllChildren()

        NetworkService.request(self.module,
                               "view/node/%s" % self.node,
                               successHandler=self.onPathRequestSucceded)
Exemple #6
0
    def nextChunk(self, cursor=None):
        if cursor:
            self.params["cursor"] = cursor

        NetworkService.request(self.module,
                               "list",
                               self.params,
                               successHandler=self.nextChunkComplete,
                               failureHandler=self.nextChunkFailure)
Exemple #7
0
    def startPolling(self, *args, **kwargs):
        """
			Start querying the server
		"""
        NetworkService.request("user",
                               "view/self",
                               successHandler=self.onUserTestSuccess,
                               failureHandler=self.onUserTestFail,
                               cacheable=False)
Exemple #8
0
	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 )
Exemple #9
0
 def fetchNext(self):
     if not self.pendingFetches:
         return
     from vi.network import NetworkService  # Circular import otherwise
     url = self.pendingFetches.pop()
     NetworkService.request(None,
                            url,
                            secure=True,
                            successHandler=self.fetchSucceeded,
                            failureHandler=self.fetchFailed)
Exemple #10
0
    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()
Exemple #11
0
 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)
Exemple #12
0
    def __init__(self, *args, **kwargs):
        super(Tasks, self).__init__(icon="icons-settings", *args, **kwargs)
        self.sinkEvent("onClick")
        self.hide()
        self.addClass("btn vi-tb-tasks")
        self.appendChild(html5.TextNode(translate("System")))

        if not conf["tasks"]["server"]:
            NetworkService.request(None,
                                   "/vi/_tasks/list",
                                   successHandler=self.onTaskListAvailable,
                                   cacheable=False)

        self.update()
Exemple #13
0
 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)
Exemple #14
0
    def reloadData(self):
        """
			Removes all currently displayed data and refetches the first batch from the server.
		"""
        self.table.clear()
        self.loadedPages = 0
        self.targetPage = 1
        self.currentPage = 0
        self._currentCursor = None
        self._currentRequests = []

        filter = {}
        if self.context:
            filter.update(self.context)

        filter.update(self.filter)
        filter["limit"] = self._batchSize

        self._currentRequests.append(
            NetworkService.request(self.module,
                                   "list",
                                   filter,
                                   successHandler=self.onCompletion,
                                   failureHandler=self.showErrorMsg,
                                   cacheable=True))
Exemple #15
0
    def loadNode(self, node, cursor=None, overrideParams=None, reqType=None):
        """
			Fetch the (direct) children of the given node.
			Once the list is received, append them to their parent node.
			:param node: Key of the node to fetch
			:type node: str
		"""
        self.node = node

        if reqType is None:
            self.loadNode(node, cursor, overrideParams, "node")

            if self.leafWidget:
                self.loadNode(node, cursor, overrideParams, "leaf")
            return

        params = {"parententry": node, "orderby": "sortindex", "amount": 99}

        if cursor:
            params.update({"cursor": cursor})

        if overrideParams:
            params.update(overrideParams)

        if self.context:
            params.update(self.context)

        r = NetworkService.request(self.module,
                                   "list/" + reqType,
                                   params,
                                   successHandler=self.onRequestSucceded,
                                   failureHandler=self.showErrorMsg)
        r.reqType = reqType
        r.node = node
        self._currentRequests.append(r)
Exemple #16
0
    def onDrop(self, event):
        """
			We got a drop event. Make that item a direct child of our rootNode
		"""
        if event.target == self.element:  # only move if droped
            srcKey, skelType = event.dataTransfer.getData("Text").split("/")

            NetworkService.request(self.module,
                                   "move", {
                                       "skelType": skelType,
                                       "key": srcKey,
                                       "parentNode": self.rootNode
                                   },
                                   secure=True,
                                   modifies=True)
            event.stopPropagation()
Exemple #17
0
    def onNextBatchNeeded(self):
        """
			Requests the next rows from the server and feed them to the table.
		"""
        if self._currentCursor and not self.isDetaching:
            filter = {}

            if self.context:
                filter.update(self.context)

            filter.update(self.filter)
            filter["limit"] = self._batchSize
            filter["cursor"] = self._currentCursor

            self._currentRequests.append(
                NetworkService.request(self.module,
                                       "list",
                                       filter,
                                       successHandler=self.onCompletion,
                                       failureHandler=self.showErrorMsg,
                                       cacheable=True))
            self._currentCursor = None
        else:
            self.actionBar.resetLoadingState()
            self.entryActionBar.resetLoadingState()
            self.tableBottomActionBar.resetLoadingState()
            self.table.setDataProvider(None)
Exemple #18
0
	def __init__(self, file, node, context=None, *args, **kwargs):
		"""
			:param file: The file to upload
			:type file: A javascript "File" Object
			:param node: Key of the desired node of our parents tree application or None for an anonymous upload.
			:type node: str or None
		"""
		super(Uploader, self).__init__()
		self.uploadSuccess = EventDispatcher("uploadSuccess")
		self.responseValue = None
		self.targetKey = None

		self.context = context

		r = NetworkService.request("file", "getUploadURL",
			params={"node": node} if node else {},
			successHandler=self.onUploadUrlAvailable,
			failureHandler=self.onFailed,
			secure=True
		)
		r.file = file
		r.node = node
		self.node = node

		conf["mainWindow"].log("progress", self)
		self.parent().addClass("is-uploading")
Exemple #19
0
 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)
Exemple #20
0
    def onClick(self, *args, **kwargs):
        if self.mode == "normal" and not self.widgetsDomElm.children():
            self.addWidget(self.createWidget())
        ''' no time right now...
		if self.childDomElem is None and "views" in self.moduleInfo:
			self.lock()
			self._buildViewPanes(self.moduleInfo["views"])
			self.unlock()
		'''

        if self.requestedViews is None and "views.request" in self.moduleInfo:
            self.lock()

            NetworkService.request(
                self.moduleName,
                self.moduleInfo["views.request"],
                successHandler=self._onRequestViewsAvailable)

        super(ListHandler, self).onClick(*args, **kwargs)
Exemple #21
0
 def createDir(self, dialog, dirName):
     if len(dirName) == 0:
         return
     r = NetworkService.request(self.parent().parent().module,
                                "add/node", {
                                    "node": self.parent().parent().node,
                                    "name": dirName
                                },
                                secure=True,
                                modifies=True,
                                successHandler=self.onMkDir)
     r.dirName = dirName
Exemple #22
0
    def onPathRequestSucceded(self, req):
        """
			Rebuild the displayed path-list according to request data
		"""
        answ = NetworkService.decode(req)
        skel = answ["values"]

        if skel["parententry"] and skel["parententry"] != skel["key"]:
            c = BreadcrumbNodeWidget(self.module, skel, [], self)

            NetworkService.request(self.module,
                                   "view/node/%s" % skel["parententry"],
                                   successHandler=self.onPathRequestSucceded)

        else:
            c = BreadcrumbNodeWidget(self.module, {
                "key": self.rootNode,
                "name": "root"
            }, [], self)
            c.addClass("is-rootnode")

        self.pathList.prependChild(c)
Exemple #23
0
	def onLoad(self, *args, **kwargs):
		"""
			Internal callback - The state of our upload changed.
		"""
		if conf["core.version"][0] == 3:
			if self.xhr.status in [200, 204]:
				NetworkService.request(
					"file", "add", {
						"key": self.targetKey,
						"node": self.node,
						"skelType": "leaf"
					},
				    successHandler=self.onUploadAdded,
					secure=True
				)
			else:
				DeferredCall(self.onFailed, self.xhr.status, _delay=1000)
		else:

			if self.xhr.status == 200:
				self.responseValue = json.loads(self.xhr.responseText)
				DeferredCall(self.onSuccess, _delay=1000)
			else:
				DeferredCall(self.onFailed, self.xhr.status, _delay=1000)
Exemple #24
0
	def onUploadUrlAvailable(self, req):
		"""
			Internal callback - the actual upload url (retrieved by calling /file/getUploadURL) is known.
		"""
		if conf["core.version"][0] == 3:

			params = NetworkService.decode(req)["values"]

			formData = html5.jseval("new FormData();")

			#if self.context:
			#	for k, v in self.context.items():
			#		formData.append(k, v)

			#if req.node and str(req.node) != "null":
			#	formData.append("node", req.node)

			for key, value in params["params"].items():
				if key == "key":
					self.targetKey = value[:-16]  # Truncate source/file.dat
					fileName = req.file.name
					value = value.replace("file.dat", fileName)

				formData.append(key, value)
			formData.append("file", req.file)

			self.xhr = html5.jseval("new XMLHttpRequest()")
			self.xhr.open("POST", params["url"])
			self.xhr.onload = self.onLoad
			self.xhr.upload.onprogress = self.onProgress
			self.xhr.send(formData)

		else:
			r = NetworkService.request("", "/vi/skey", successHandler=self.onSkeyAvailable)
			r.file = req.file
			r.node = req.node
			r.destUrl = req.result
Exemple #25
0
	def save(self, data):
		"""
			Creates the actual NetworkService request used to transmit our data.
			If data is None, it fetches a clean add/edit form.

			:param data: The values to transmit or None to fetch a new, clean add/edit form.
			:type data: dict or None
		"""
		self.wasInitialRequest = not len(data) > 0

		if self.context:
			# Data takes precedence over context.
			ndata = self.context.copy()
			ndata.update(data.copy())
			data = ndata

		if self.module=="_tasks":
			NetworkService.request(None, "/vi/%s/execute/%s" % (self.module, self.key), data,
			                        secure=not self.wasInitialRequest,
			                        successHandler=self.setData,
			                        failureHandler=self.showErrorMsg)

		elif self.applicationType == EditWidget.appList: ## Application: List
			if self.key and (not self.clone or self.wasInitialRequest):
				NetworkService.request(self.module, "edit/%s" % self.key, data,
				                       secure=not self.wasInitialRequest,
				                       successHandler=self.setData,
				                       failureHandler=self.showErrorMsg)
			else:
				NetworkService.request(self.module, "add", data,
				                       secure=not self.wasInitialRequest,
				                       successHandler=self.setData,
				                       failureHandler=self.showErrorMsg )

		elif False and self.applicationType == EditWidget.appHierarchy: ## Application: Hierarchy
			if self.key and (not self.clone or self.wasInitialRequest):
				NetworkService.request(self.module, "edit/%s" % self.key, data,
				                       secure=not self.wasInitialRequest,
				                       successHandler=self.setData,
				                       failureHandler=self.showErrorMsg)
			else:
				NetworkService.request(self.module, "add/%s" % self.node, data,
				                       secure=not self.wasInitialRequest,
				                       successHandler=self.setData,
				                       failureHandler=self.showErrorMsg)

		elif self.applicationType == EditWidget.appTree or self.applicationType == EditWidget.appHierarchy: ## Application: Tree
			if self.key and not self.clone:
				NetworkService.request(self.module, "edit/%s/%s" % (self.skelType, self.key), data,
				                       secure=not self.wasInitialRequest,
				                       successHandler=self.setData,
				                       failureHandler=self.showErrorMsg)
			else:
				NetworkService.request(self.module, "add/%s/%s" % (self.skelType, self.node), data,
				                       secure=not self.wasInitialRequest,
				                       successHandler=self.setData,
				                       failureHandler=self.showErrorMsg)

		elif self.applicationType == EditWidget.appSingleton: ## Application: Singleton
			NetworkService.request(self.module, "edit", data,
			                       secure=not self.wasInitialRequest,
			                       successHandler=self.setData,
			                       failureHandler=self.showErrorMsg)
		else:
			raise NotImplementedError() #Should never reach this
Exemple #26
0
 def update(self):
     self.removeAllChildren()
     NetworkService.request(self.parent().parent().module,
                            "listRootNodes",
                            successHandler=self.onRootNodesAvailable,
                            cacheable=True)
Exemple #27
0
    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()
        srcKey, skelType = event.dataTransfer.getData("Text").split("/")

        if self.currentStatus == "inner":
            NetworkService.request(self.module,
                                   "move", {
                                       "skelType": skelType,
                                       "key": srcKey,
                                       "parentNode": self.data["key"]
                                   },
                                   secure=True,
                                   modifies=True)

        elif self.currentStatus == "top":
            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 = float(c.data["sortindex"])
                newIdx = str((lastIdx + float(self.data["sortindex"])) / 2.0)
                req = NetworkService.request(self.module,
                                             "move", {
                                                 "skelType": skelType,
                                                 "key": srcKey,
                                                 "parentNode": parentID,
                                                 "sortindex": newIdx
                                             },
                                             secure=True,
                                             modifies=True)

        elif self.currentStatus == "bottom":
            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 = float(c.data["sortindex"])
                            break
                        if c == self:
                            doUseNextChild = True

                newIdx = str((lastIdx + float(self.data["sortindex"])) / 2.0)
                req = NetworkService.request(self.module,
                                             "move", {
                                                 "skelType": skelType,
                                                 "key": srcKey,
                                                 "parentNode": parentID,
                                                 "sortindex": newIdx
                                             },
                                             secure=True,
                                             modifies=True)
Exemple #28
0
 def setPayed(self, order):
     NetworkService.request(self.parent().parent().module,
                            self.action, {"key": order["key"]},
                            secure=True,
                            successHandler=self.setPayedSucceeded,
                            failureHandler=self.setPayedFailed)