Ejemplo n.º 1
0
 def singleValueFromClient(self, value, skel, name, origData):
     try:
         rawValue = str(value).replace(",", ".", 1)
     except:
         return self.getEmptyValue(), [
             ReadFromClientError(ReadFromClientErrorSeverity.Invalid, name,
                                 "Invalid Value")
         ]
     else:
         if self.precision and (str(rawValue).replace(".", "", 1).replace(
                 "-", "", 1).isdigit()) and float(
                     rawValue) >= self.min and float(rawValue) <= self.max:
             value = round(float(rawValue), self.precision)
         elif not self.precision and (
                 str(rawValue).replace("-", "", 1).isdigit()
         ) and int(rawValue) >= self.min and int(rawValue) <= self.max:
             value = int(rawValue)
         else:
             return self.getEmptyValue(), [
                 ReadFromClientError(ReadFromClientErrorSeverity.Invalid,
                                     name, "Invalid Value")
             ]
     err = self.isInvalid(value)
     if err:
         return self.getEmptyValue(), [
             ReadFromClientError(ReadFromClientErrorSeverity.Invalid, name,
                                 err)
         ]
     return value, None
Ejemplo n.º 2
0
    def fromClient(self, valuesCache, name, data):
        """
			Reads a value from the client.
			If this value is valid for this bone,
			store this value and return None.
			Otherwise our previous value is
			left unchanged and an error-message
			is returned.

			:param name: Our name in the skeleton
			:type name: str
			:param data: *User-supplied* request-data
			:type data: dict
			:returns: str or None
		"""
        if not name in data:
            return [
                ReadFromClientError(ReadFromClientErrorSeverity.NotSet, name,
                                    "Field not submitted")
            ]
        value = data[name]
        if str(value) in self.trueStrs:
            value = True
        else:
            value = False
        err = self.isInvalid(value)
        if not err:
            valuesCache[name] = value
            return False
        else:
            return [
                ReadFromClientError(ReadFromClientErrorSeverity.Empty, name,
                                    err)
            ]
Ejemplo n.º 3
0
	def fromClient(self, skel: 'SkeletonInstance', name: str, data: dict) -> Union[None, List[ReadFromClientError]]:
		"""
			Reads a value from the client.
			If this value is valid for this bone,
			store this value and return None.
			Otherwise our previous value is
			left unchanged and an error-message
			is returned.

			:param name: Our name in the skeleton
			:type name: str
			:param data: *User-supplied* request-data
			:type data: dict
			:returns: None or String
		"""
		if currentRequest.get().isDevServer:  # We dont enforce captchas on dev server
			return None
		user = utils.getCurrentUser()
		if user and "root" in user["access"]:
			return None  # Don't bother trusted users with this (not supported by admin/vi anyways)
		if not "g-recaptcha-response" in data:
			return [ReadFromClientError(ReadFromClientErrorSeverity.NotSet, "No Captcha given!")]
		data = {
			"secret": self.privateKey,
			"remoteip": currentRequest.get().request.remote_addr,
			"response": data["g-recaptcha-response"]
		}
		req = urllib.request.Request(url="https://www.google.com/recaptcha/api/siteverify",
									 data=urllib.parse.urlencode(data).encode(),
									 method="POST")
		response = urllib.request.urlopen(req)
		if json.loads(response.read()).get("success"):
			return None
		return [ReadFromClientError(ReadFromClientErrorSeverity.Invalid, "Invalid Captcha")]
Ejemplo n.º 4
0
 def fromClient(self, skel: 'SkeletonInstance', name: str,
                data: dict) -> Union[None, List[ReadFromClientError]]:
     if not name in data:
         return [
             ReadFromClientError(ReadFromClientErrorSeverity.NotSet,
                                 "Field not submitted")
         ]
     value = data.get(name)
     if not value:
         # Password-Bone is special: As it cannot be read don't set back no None if no value is given
         # This means an once set password can only be changed - but never deleted.
         return [
             ReadFromClientError(ReadFromClientErrorSeverity.Empty,
                                 "No value entered")
         ]
     err = self.isInvalid(value)
     if err:
         return [
             ReadFromClientError(ReadFromClientErrorSeverity.Invalid, err)
         ]
     # As we don't escape passwords and allow most special characters we'll hash it early on so we don't open
     # an XSS attack vector if a password is echoed back to the client (which should not happen)
     salt = utils.generateRandomString(self.saltLength)
     passwd = pbkdf2(value[:conf["viur.maxPasswordLength"]], salt)
     skel[name] = {"pwhash": passwd, "salt": salt}
Ejemplo n.º 5
0
	def singleValueFromClient(self, value, skel, name, origData):
		if not str(value):
			return self.getEmptyValue(), [ReadFromClientError(ReadFromClientErrorSeverity.Empty, "No value selected")]
		for key in self.values.keys():
			if str(key) == str(value):
				return key, None
		return self.getEmptyValue(), [
			ReadFromClientError(ReadFromClientErrorSeverity.Invalid, "Invalid value selected")]
Ejemplo n.º 6
0
    def fromClient(self, valuesCache, name, data):
        """
			Reads a value from the client.
			If this value is valid for this bone,
			store this value and return None.
			Otherwise our previous value is
			left unchanged and an error-message
			is returned.

			:param name: Our name in the skeleton
			:type name: str
			:param data: *User-supplied* request-data
			:type data: dict
			:returns: None or String
		"""
        if not name in data:
            return [
                ReadFromClientError(ReadFromClientErrorSeverity.NotSet, name,
                                    "Field not submitted")
            ]
        rawValue = data[name]
        value = None
        if rawValue:
            try:
                rawValue = str(rawValue).replace(",", ".", 1)
            except:
                value = None
            else:
                if self.precision and (str(rawValue).replace(
                        ".", "", 1).replace("-", "", 1).isdigit(
                        )) and float(rawValue) >= self.min and float(
                            rawValue) <= self.max:
                    value = round(float(rawValue), self.precision)
                elif not self.precision and (
                        str(rawValue).replace("-", "", 1).isdigit()
                ) and int(rawValue) >= self.min and int(rawValue) <= self.max:
                    value = int(rawValue)
                else:
                    value = None
        if value is None:
            return [
                ReadFromClientError(ReadFromClientErrorSeverity.Empty, name,
                                    "No value entered")
            ]
        if value != value:  # NaN
            return [
                ReadFromClientError(ReadFromClientErrorSeverity.Invalid, name,
                                    "Invalid value entered")
            ]
        err = self.isInvalid(value)
        if err:
            return [
                ReadFromClientError(ReadFromClientErrorSeverity.Invalid, name,
                                    err)
            ]
        valuesCache[name] = value
Ejemplo n.º 7
0
 def singleValueFromClient(self, value, skel, name, origData):
     err = self.isInvalid(value)
     if err:
         return self.getEmptyValue(), [
             ReadFromClientError(ReadFromClientErrorSeverity.Invalid, err)
         ]
     return value, None
Ejemplo n.º 8
0
 def singleValueFromClient(self, value, skel, name, origData):
     err = self.isInvalid(value)
     if not err:
         return utils.escapeString(value, 4 * 1024), None
     return self.getEmptyValue(), [
         ReadFromClientError(ReadFromClientErrorSeverity.Invalid, err)
     ]
Ejemplo n.º 9
0
 def singleValueFromClient(self, value, skel, name, origData):
     usingSkel = self.using()
     if not usingSkel.fromClient(value,
                                 not (self.required or self.multiple)):
         usingSkel.errors.append(
             ReadFromClientError(ReadFromClientErrorSeverity.Invalid,
                                 "Incomplete data"))
     return usingSkel, usingSkel.errors
Ejemplo n.º 10
0
    def fromClient(self, skel, name, data):
        """
			Reads a value from the client.
			If this value is valid for this bone,
			store this value and return None.
			Otherwise our previous value is
			left unchanged and an error-message
			is returned.
			:param name: Our name in the skeleton
			:type name: str
			:param data: *User-supplied* request-data
			:type data: dict
			:returns: None or String
		"""
        rawLat = data.get("%s.lat" % name, None)
        rawLng = data.get("%s.lng" % name, None)
        if rawLat is None and rawLng is None:
            return [
                ReadFromClientError(ReadFromClientErrorSeverity.NotSet, name,
                                    "Field not submitted")
            ]
        elif not rawLat or not rawLng:
            skel[name] = None
            return [
                ReadFromClientError(ReadFromClientErrorSeverity.Empty, name,
                                    "No value submitted")
            ]
        try:
            rawLat = float(rawLat)
            rawLng = float(rawLng)
            # Check for NaNs
            assert rawLat == rawLat
            assert rawLng == rawLng
        except:
            return [
                ReadFromClientError(ReadFromClientErrorSeverity.Invalid, name,
                                    "Invalid value entered")
            ]
        err = self.isInvalid((rawLat, rawLng))
        if err:
            return [
                ReadFromClientError(ReadFromClientErrorSeverity.Invalid, name,
                                    err)
            ]
        skel[name] = (rawLat, rawLng)
Ejemplo n.º 11
0
 def singleValueFromClient(self, value, skel, name, origData):
     err = self.isInvalid(
         value)  # Returns None on success, error-str otherwise
     if not err:
         return HtmlSerializer(self.validHtml).sanitize(value), None
     else:
         return self.getEmptyValue(), [
             ReadFromClientError(ReadFromClientErrorSeverity.Invalid, err)
         ]
Ejemplo n.º 12
0
 def fromClient(self, valuesCache, name, data):
     if not name in data:
         return [
             ReadFromClientError(ReadFromClientErrorSeverity.NotSet, name,
                                 "Field not submitted")
         ]
     value = data.get(name)
     if not value:
         return [
             ReadFromClientError(ReadFromClientErrorSeverity.Empty, name,
                                 "No value entered")
         ]
     err = self.isInvalid(value)
     if err:
         return [
             ReadFromClientError(ReadFromClientErrorSeverity.Invalid, name,
                                 err)
         ]
     valuesCache[name] = value
Ejemplo n.º 13
0
    def fromClient(self, valuesCache, name, data):
        """
			Reads a value from the client.
			If this value is valid for this bone,
			store this value and return None.
			Otherwise our previous value is
			left unchanged and an error-message
			is returned.

			:param name: Our name in the skeleton
			:type name: str
			:param data: *User-supplied* request-data
			:type data: dict
			:returns: None or String
		"""
        if request.current.get(
        ).isDevServer:  # We dont enforce captchas on dev server
            return None
        user = utils.getCurrentUser()
        if user and "root" in user["access"]:
            return None  # Don't bother trusted users with this (not supported by admin/vi anyways)
        if not "g-recaptcha-response" in data:
            return [
                ReadFromClientError(ReadFromClientErrorSeverity.NotSet, name,
                                    "No Captcha given!")
            ]
        data = {
            "secret": self.privateKey,
            "remoteip": request.current.get().request.remote_addr,
            "response": data["g-recaptcha-response"]
        }
        response = urlfetch.fetch(
            url="https://www.google.com/recaptcha/api/siteverify",
            payload=urllib.urlencode(data),
            method=urlfetch.POST,
            headers={"Content-Type": "application/x-www-form-urlencoded"})
        if json.loads(response.content.decode("UTF-8")).get("success"):
            return None
        return [
            ReadFromClientError(ReadFromClientErrorSeverity.Invalid, name,
                                "Invalid Captcha")
        ]
Ejemplo n.º 14
0
 def singleValueFromClient(self, value, skel, name, origData):
     value = value.lower()
     if value.count("#") > 1:
         return self.getEmptyValue(), [
             ReadFromClientError(ReadFromClientErrorSeverity.Invalid,
                                 "Invalid value entered")
         ]
     for char in value:
         if not char in "#0123456789abcdef":
             return self.getEmptyValue(), [
                 ReadFromClientError(ReadFromClientErrorSeverity.Invalid,
                                     "Invalid value entered")
             ]
     if self.mode == "rgb":
         if len(value) == 3:
             value = "#" + value
         if len(value) == 4:
             value = value[0:2] + value[1] + 2 * value[2] + 2 * value[3]
         if len(value) == 6 or len(value) == 7:
             if len(value) == 6:
                 value = "#" + value
         else:
             return self.getEmptyValue(), [
                 ReadFromClientError(ReadFromClientErrorSeverity.Invalid,
                                     "Invalid value entered")
             ]
     if self.mode == "rgba":
         if len(value) == 8 or len(value) == 9:
             if len(value) == 8:
                 value = "#" + value
         else:
             return self.getEmptyValue(), [
                 ReadFromClientError(ReadFromClientErrorSeverity.Invalid,
                                     "Invalid value entered")
             ]
     err = self.isInvalid(value)
     if not err:
         return value, None
     return self.getEmptyValue(), [
         ReadFromClientError(ReadFromClientErrorSeverity.Invalid, err)
     ]
Ejemplo n.º 15
0
 def fromClient(self, skel: 'SkeletonInstance', name: str,
                data: dict) -> Union[None, List[ReadFromClientError]]:
     if not name in data:
         return [
             ReadFromClientError(ReadFromClientErrorSeverity.NotSet, name,
                                 "Field not submitted")
         ]
     value = data.get(name)
     if not value:
         # Password-Bone is special: As it cannot be read don't set back no None if no value is given
         # This means an once set password can only be changed - but never deleted.
         return [
             ReadFromClientError(ReadFromClientErrorSeverity.Empty, name,
                                 "No value entered")
         ]
     err = self.isInvalid(value)
     if err:
         return [
             ReadFromClientError(ReadFromClientErrorSeverity.Invalid, name,
                                 err)
         ]
     skel[name] = value
Ejemplo n.º 16
0
 def fromClient(self, valuesCache, name, data):
     if not name in data:
         return [
             ReadFromClientError(ReadFromClientErrorSeverity.NotSet, name,
                                 "Field not submitted")
         ]
     values = data[name]
     if not values:
         return [
             ReadFromClientError(ReadFromClientErrorSeverity.Empty, name,
                                 "No value selected")
         ]
     # single case
     if not self.multiple:
         for key in self.values.keys():
             if str(key) == str(values):
                 err = self.isInvalid(key)
                 if err:
                     return [
                         ReadFromClientError(
                             ReadFromClientErrorSeverity.Invalid, name, err)
                     ]
                 valuesCache[name] = key
                 break
         else:
             return [
                 ReadFromClientError(ReadFromClientErrorSeverity.Invalid,
                                     name, "No or invalid value selected")
             ]
     # multiple case
     else:
         if not values:
             if not self.required:
                 valuesCache[name] = []
             return [
                 ReadFromClientError(ReadFromClientErrorSeverity.Empty,
                                     name, "No item selected")
             ]
         if not isinstance(values, list):
             if isinstance(values, str):
                 values = values.split(":")
             else:
                 values = []
         valuesCache[name] = []
         errors = []
         for key, value in self.values.items():
             if str(key) in [str(x) for x in values]:
                 err = self.isInvalid(key)
                 if not err:
                     valuesCache[name].append(key)
                 else:
                     errors.append([
                         ReadFromClientError(
                             ReadFromClientErrorSeverity.Invalid, name, err)
                     ])
         if errors:
             return errors
         elif not valuesCache[name]:
             return [
                 ReadFromClientError(ReadFromClientErrorSeverity.Empty,
                                     name, "No item selected")
             ]
Ejemplo n.º 17
0
    def fromClient(self, valuesCache, name, data):
        """
			Reads a value from the client.
			If this value is valid for this bone,
			store this rawValue and return None.
			Otherwise our previous value is
			left unchanged and an error-message
			is returned.

			:param name: Our name in the :class:`server.skeleton.Skeleton`
			:type name: str
			:param data: *User-supplied* request-data
			:type data: dict
			:returns: str or None
		"""
        if not name in data and not any(
                x.startswith("%s." % name) for x in data):
            return [
                ReadFromClientError(ReadFromClientErrorSeverity.NotSet, name,
                                    "Field not submitted")
            ]
        res = None
        errors = []
        if self.multiple and self.languages:
            res = LanguageWrapper(self.languages)
            for lang in self.languages:
                res[lang] = []
                if "%s.%s" % (name, lang) in data:
                    val = data["%s.%s" % (name, lang)]
                    if isinstance(val, str):
                        err = self.isInvalid(val)
                        if not err:
                            res[lang].append(utils.escapeString(val))
                        else:
                            errors.append(
                                ReadFromClientError(
                                    ReadFromClientErrorSeverity.Invalid, name,
                                    err))
                    elif isinstance(val, list):
                        for v in val:
                            err = self.isInvalid(v)
                            if not err:
                                res[lang].append(utils.escapeString(v))
                            else:
                                errors.append(
                                    ReadFromClientError(
                                        ReadFromClientErrorSeverity.Invalid,
                                        name, err))
            if not any(res.values()) and not errors:
                errors.append(
                    ReadFromClientError(ReadFromClientErrorSeverity.Empty,
                                        name, "No rawValue entered"))
        elif self.multiple and not self.languages:
            rawValue = data.get(name)
            res = []
            if not rawValue:
                errors.append(
                    ReadFromClientError(ReadFromClientErrorSeverity.Empty,
                                        name, "No rawValue entered"))
            else:
                if not isinstance(rawValue, list):
                    rawValue = [rawValue]
                for val in rawValue:
                    err = self.isInvalid(val)
                    if not err:
                        res.append(utils.escapeString(val))
                    else:
                        errors.append(
                            ReadFromClientError(
                                ReadFromClientErrorSeverity.Invalid, name,
                                err))
                if len(res) > 0:
                    res = res[0:254]  # Max 254 character
                else:
                    errors.append(
                        ReadFromClientError(ReadFromClientErrorSeverity.Empty,
                                            name, "No valid rawValue entered"))
        elif not self.multiple and self.languages:
            res = LanguageWrapper(self.languages)
            for lang in self.languages:
                if "%s.%s" % (name, lang) in data:
                    val = data["%s.%s" % (name, lang)]
                    err = self.isInvalid(val)
                    if not err:
                        res[lang] = utils.escapeString(val)
                    else:
                        errors.append(
                            ReadFromClientError(
                                ReadFromClientErrorSeverity.Invalid, name,
                                err))
            if len(res.keys()) == 0 and not errors:
                errors.append(
                    ReadFromClientError(ReadFromClientErrorSeverity.Empty,
                                        name, "No rawValue entered"))
        else:
            rawValue = data.get(name)
            err = self.isInvalid(rawValue)
            if not err:
                res = utils.escapeString(rawValue)
            else:
                errors.append(
                    ReadFromClientError(ReadFromClientErrorSeverity.Invalid,
                                        name, err))
            if not rawValue and not errors:
                errors.append(
                    ReadFromClientError(ReadFromClientErrorSeverity.Empty,
                                        name, "No rawValue entered"))
        valuesCache[name] = res
        if errors:
            return errors
Ejemplo n.º 18
0
    def fromClient(self, valuesCache, name, data):
        """
			Reads a value from the client.
			If this value is valid for this bone,
			store this value and return None.
			Otherwise our previous value is
			left unchanged and an error-message
			is returned.

			:param name: Our name in the skeleton
			:type name: str
			:param data: *User-supplied* request-data
			:type data: dict
			:returns: str or None
		"""
        if not name in data:
            return [
                ReadFromClientError(ReadFromClientErrorSeverity.NotSet, name,
                                    "Field not submitted")
            ]
        value = data[name]
        if not value:
            return [
                ReadFromClientError(ReadFromClientErrorSeverity.Empty, name,
                                    "No value selected")
            ]
        value = value.lower()
        if value.count("#") > 1:
            return [
                ReadFromClientError(ReadFromClientErrorSeverity.Invalid, name,
                                    "Invalid value entered")
            ]
        for char in value:
            if not char in "#0123456789abcdef":
                return [
                    ReadFromClientError(ReadFromClientErrorSeverity.Invalid,
                                        name, "Invalid value entered")
                ]
        if self.mode == "rgb":
            if len(value) == 3:
                value = "#" + value
            if len(value) == 4:
                value = value[0:2] + value[1] + 2 * value[2] + 2 * value[3]
            if len(value) == 6 or len(value) == 7:
                if len(value) == 6:
                    value = "#" + value
            else:
                return [
                    ReadFromClientError(ReadFromClientErrorSeverity.Invalid,
                                        name, "Invalid value entered")
                ]
        if self.mode == "rgba":
            if len(value) == 8 or len(value) == 9:
                if len(value) == 8:
                    value = "#" + value
            else:
                return [
                    ReadFromClientError(ReadFromClientErrorSeverity.Invalid,
                                        name, "Invalid value entered")
                ]
        err = self.isInvalid(value)
        if err:
            return [
                ReadFromClientError(ReadFromClientErrorSeverity.Invalid, name,
                                    err)
            ]
        valuesCache[name] = value
Ejemplo n.º 19
0
    def fromClient(self, valuesCache, name, data):
        #return [ReadFromClientError(ReadFromClientErrorSeverity.Invalid, name, "Not yet fixed")]
        if not name in data and not any(
                x.startswith("%s." % name) for x in data):
            return [
                ReadFromClientError(ReadFromClientErrorSeverity.NotSet, name,
                                    "Field not submitted")
            ]

        valuesCache[name] = []
        tmpRes = {}

        clientPrefix = "%s." % name

        for k, v in data.items():
            # print(k, v)

            if k.startswith(clientPrefix) or k == name:
                if k == name:
                    k = k.replace(name, "", 1)

                else:
                    k = k.replace(clientPrefix, "", 1)

                if "." in k:
                    try:
                        idx, bname = k.split(".", 1)
                        idx = int(idx)
                    except ValueError:
                        idx = 0

                        try:
                            bname = k.split(".", 1)
                        except ValueError:
                            # We got some garbage as input; don't try to parse it
                            continue

                else:
                    idx = 0
                    bname = k

                if not bname:
                    continue

                if not idx in tmpRes:
                    tmpRes[idx] = {}

                if bname in tmpRes[idx]:
                    if isinstance(tmpRes[idx][bname], list):
                        tmpRes[idx][bname].append(v)
                    else:
                        tmpRes[idx][bname] = [tmpRes[idx][bname], v]
                else:
                    tmpRes[idx][bname] = v

        tmpList = [tmpRes[k] for k in sorted(tmpRes.keys())]

        errors = []

        for i, r in enumerate(tmpList[:]):
            usingSkel = self._usingSkelCache
            #usingSkel.setValuesCache(Skeletccc)
            usingSkel.unserialize({})

            if not usingSkel.fromClient(r):
                for error in usingSkel.errors:
                    errors.append(
                        ReadFromClientError(
                            error.severity,
                            "%s.%s.%s" % (name, i, error.fieldPath),
                            error.errorMessage))
            tmpList[i] = usingSkel.getValuesCache()

        cleanList = []

        for item in tmpList:
            err = self.isInvalid(item)
            if err:
                errors.append(
                    ReadFromClientError(ReadFromClientErrorSeverity.Invalid,
                                        "%s.%s" % (name, tmpList.index(item)),
                                        err))
            else:
                cleanList.append(item)

        valuesCache[name] = tmpList

        if not cleanList:
            errors.append(
                ReadFromClientError(ReadFromClientErrorSeverity.Empty, name,
                                    "No value selected"))

        if errors:
            return errors
Ejemplo n.º 20
0
    def singleValueFromClient(self, value, skel, name, origData):
        """
			Reads a value from the client.
			If this value is valid for this bone,
			store this value and return None.
			Otherwise our previous value is
			left unchanged and an error-message
			is returned.

			Value is assumed to be in local time zone only if both self.date and self.time are set to True
			and self.localize is True.

			Value is valid if, when converted into String, it complies following formats:\n
			- is digit (may include one '-') and valid POSIX timestamp: converted from timestamp; assumes UTC timezone\n
			- is digit (may include one '-') and NOT valid POSIX timestamp and not date and time: interpreted as seconds after epoch\n
			- 'now': current time\n
			- 'nowX', where X converted into String is added as seconds to current time\n
			- '%H:%M:%S' if not date and time\n
			- '%M:%S' if not date and time\n
			- '%S' if not date and time\n
			- '%Y-%m-%d %H:%M:%S' (ISO date format)\n
			- '%Y-%m-%d %H:%M' (ISO date format)\n
			- '%Y-%m-%d' (ISO date format)\n
			- '%m/%d/%Y %H:%M:%S' (US date-format)\n
			- '%m/%d/%Y %H:%M' (US date-format)\n
			- '%m/%d/%Y' (US date-format)\n
			- '%d.%m.%Y %H:%M:%S' (EU date-format)\n
			- '%d.%m.%Y %H:%M' (EU date-format)\n
			- '%d.%m.%Y' (EU date-format)\n
			-  \n

			The resulting year must be >= 1900.

			:param name: Our name in the skeleton
			:type name: str
			:param value: *User-supplied* request-data
			:type value: str(value) has to be of valid format
			:returns: tuple[datetime or None, [Errors] or None]
		"""
        if self.date and self.time and self.localize:
            time_zone = self.guessTimeZone()
        else:
            time_zone = pytz.utc
        rawValue = value
        if str(rawValue).replace("-", "", 1).replace(".", "", 1).isdigit():
            if int(rawValue) < -1 * (2**30) or int(rawValue) > (2**31) - 2:
                value = False  # its invalid
            else:
                value = datetime.fromtimestamp(
                    float(rawValue), tz=time_zone).replace(microsecond=0)
        elif not self.date and self.time:
            try:
                value = time_zone.localize(datetime.fromisoformat(value))
            except:
                try:
                    if str(rawValue).count(":") > 1:
                        (hour, minute, second) = [
                            int(x.strip()) for x in str(rawValue).split(":")
                        ]
                        value = datetime(year=1970,
                                         month=1,
                                         day=1,
                                         hour=hour,
                                         minute=minute,
                                         second=second,
                                         tzinfo=time_zone)
                    elif str(rawValue).count(":") > 0:
                        (hour, minute) = [
                            int(x.strip()) for x in str(rawValue).split(":")
                        ]
                        value = datetime(year=1970,
                                         month=1,
                                         day=1,
                                         hour=hour,
                                         minute=minute,
                                         tzinfo=time_zone)
                    elif str(rawValue).replace("-", "", 1).isdigit():
                        value = datetime(year=1970,
                                         month=1,
                                         day=1,
                                         second=int(rawValue),
                                         tzinfo=time_zone)
                    else:
                        value = False  # its invalid
                except:
                    value = False
        elif str(rawValue).lower().startswith("now"):
            tmpRes = datetime.now(time_zone)
            if len(str(rawValue)) > 4:
                try:
                    tmpRes += timedelta(seconds=int(str(rawValue)[3:]))
                except:
                    pass
            value = tmpRes
        else:
            try:
                value = time_zone.localize(datetime.fromisoformat(value))
            except:
                try:
                    if " " in rawValue:  # Date with time
                        try:  # Times with seconds
                            if "-" in rawValue:  # ISO Date
                                value = time_zone.localize(
                                    datetime.strptime(str(rawValue),
                                                      "%Y-%m-%d %H:%M:%S"))
                            elif "/" in rawValue:  # Ami Date
                                value = time_zone.localize(
                                    datetime.strptime(str(rawValue),
                                                      "%m/%d/%Y %H:%M:%S"))
                            else:  # European Date
                                value = time_zone.localize(
                                    datetime.strptime(str(rawValue),
                                                      "%d.%m.%Y %H:%M:%S"))
                        except:
                            if "-" in rawValue:  # ISO Date
                                value = time_zone.localize(
                                    datetime.strptime(str(rawValue),
                                                      "%Y-%m-%d %H:%M"))
                            elif "/" in rawValue:  # Ami Date
                                value = time_zone.localize(
                                    datetime.strptime(str(rawValue),
                                                      "%m/%d/%Y %H:%M"))
                            else:  # European Date
                                value = time_zone.localize(
                                    datetime.strptime(str(rawValue),
                                                      "%d.%m.%Y %H:%M"))
                    else:
                        if "-" in rawValue:  # ISO (Date only)
                            value = time_zone.localize(
                                datetime.strptime(str(rawValue), "%Y-%m-%d"))
                        elif "/" in rawValue:  # Ami (Date only)
                            value = time_zone.localize(
                                datetime.strptime(str(rawValue), "%m/%d/%Y"))
                        else:  # European (Date only)
                            value = time_zone.localize(
                                datetime.strptime(str(rawValue), "%d.%m.%Y"))
                except:
                    value = False  # its invalid
        if value is False:
            return self.getEmptyValue(), [
                ReadFromClientError(ReadFromClientErrorSeverity.Invalid,
                                    "Invalid value entered")
            ]
        value = value.replace(microsecond=0)
        err = self.isInvalid(value)
        if err:
            return self.getEmptyValue(), [
                ReadFromClientError(ReadFromClientErrorSeverity.Invalid, err)
            ]
        return value, None
Ejemplo n.º 21
0
    def fromClient(self, valuesCache, name, data):
        """
			Reads a value from the client.
			If this value is valid for this bone,
			store this value and return None.
			Otherwise our previous value is
			left unchanged and an error-message
			is returned.

			:param name: Our name in the skeleton
			:type name: str
			:param data: *User-supplied* request-data
			:type data: dict
			:returns: str or None
		"""
        if not name in data:
            return [
                ReadFromClientError(ReadFromClientErrorSeverity.NotSet, name,
                                    "Field not submitted")
            ]
        rawValue = data[name]
        if not rawValue:
            return [
                ReadFromClientError(ReadFromClientErrorSeverity.Empty, name,
                                    "No value selected")
            ]
        elif str(rawValue).replace("-", "", 1).replace(".", "", 1).isdigit():
            if int(rawValue) < -1 * (2**30) or int(rawValue) > (2**31) - 2:
                value = False  # its invalid
            else:
                value = ExtendedDateTime.fromtimestamp(float(rawValue))
        elif not self.date and self.time:
            try:
                if str(rawValue).count(":") > 1:
                    (hour, minute, second) = [
                        int(x.strip()) for x in str(rawValue).split(":")
                    ]
                    value = time(hour=hour, minute=minute, second=second)
                elif str(rawValue).count(":") > 0:
                    (hour, minute) = [
                        int(x.strip()) for x in str(rawValue).split(":")
                    ]
                    value = time(hour=hour, minute=minute)
                elif str(rawValue).replace("-", "", 1).isdigit():
                    value = time(second=int(rawValue))
                else:
                    value = False  # its invalid
            except:
                value = False
        elif str(rawValue).lower().startswith("now"):
            tmpRes = ExtendedDateTime.now()
            if len(str(rawValue)) > 4:
                try:
                    tmpRes += timedelta(seconds=int(str(rawValue)[3:]))
                except:
                    pass
            value = tmpRes
        else:
            try:
                if " " in rawValue:  # Date with time
                    try:  # Times with seconds
                        if "-" in rawValue:  # ISO Date
                            value = ExtendedDateTime.strptime(
                                str(rawValue), "%Y-%m-%d %H:%M:%S")
                        elif "/" in rawValue:  # Ami Date
                            value = ExtendedDateTime.strptime(
                                str(rawValue), "%m/%d/%Y %H:%M:%S")
                        else:  # European Date
                            value = ExtendedDateTime.strptime(
                                str(rawValue), "%d.%m.%Y %H:%M:%S")
                    except:
                        if "-" in rawValue:  # ISO Date
                            value = ExtendedDateTime.strptime(
                                str(rawValue), "%Y-%m-%d %H:%M")
                        elif "/" in rawValue:  # Ami Date
                            value = ExtendedDateTime.strptime(
                                str(rawValue), "%m/%d/%Y %H:%M")
                        else:  # European Date
                            value = ExtendedDateTime.strptime(
                                str(rawValue), "%d.%m.%Y %H:%M")
                else:
                    if "-" in rawValue:  # ISO (Date only)
                        value = ExtendedDateTime.strptime(
                            str(rawValue), "%Y-%m-%d")
                    elif "/" in rawValue:  # Ami (Date only)
                        value = ExtendedDateTime.strptime(
                            str(rawValue), "%m/%d/%Y")
                    else:  # European (Date only)
                        value = ExtendedDateTime.strptime(
                            str(rawValue), "%d.%m.%Y")
            except:
                value = False  # its invalid
        if value is False:
            return [
                ReadFromClientError(ReadFromClientErrorSeverity.Invalid, name,
                                    "Invalid value entered")
            ]
        err = self.isInvalid(value)
        if err:
            return [
                ReadFromClientError(ReadFromClientErrorSeverity.Invalid, name,
                                    err)
            ]
        valuesCache[name] = value
Ejemplo n.º 22
0
    def singleValueFromClient(self, value, skel, name, origData):
        """
			Reads a value from the client.
			If this value is valid for this bone,
			store this value and return None.
			Otherwise our previous value is
			left unchanged and an error-message
			is returned.

			:param name: Our name in the skeleton
			:type name: str
			:param data: *User-supplied* request-data
			:type data: dict
			:returns: str or None
		"""
        rawValue = value
        if str(rawValue).replace("-", "", 1).replace(".", "", 1).isdigit():
            if int(rawValue) < -1 * (2**30) or int(rawValue) > (2**31) - 2:
                value = False  # its invalid
            else:
                value = datetime.fromtimestamp(float(rawValue))
        elif not self.date and self.time:
            try:
                if str(rawValue).count(":") > 1:
                    (hour, minute, second) = [
                        int(x.strip()) for x in str(rawValue).split(":")
                    ]
                    value = time(hour=hour, minute=minute, second=second)
                elif str(rawValue).count(":") > 0:
                    (hour, minute) = [
                        int(x.strip()) for x in str(rawValue).split(":")
                    ]
                    value = time(hour=hour, minute=minute)
                elif str(rawValue).replace("-", "", 1).isdigit():
                    value = time(second=int(rawValue))
                else:
                    value = False  # its invalid
            except:
                value = False
        elif str(rawValue).lower().startswith("now"):
            tmpRes = utcNow().astimezone(self.guessTimeZone())
            if len(str(rawValue)) > 4:
                try:
                    tmpRes += timedelta(seconds=int(str(rawValue)[3:]))
                except:
                    pass
            value = tmpRes
        else:
            try:
                timeZone = self.guessTimeZone()
                if " " in rawValue:  # Date with time
                    try:  # Times with seconds
                        if "-" in rawValue:  # ISO Date
                            value = datetime.strptime(str(rawValue),
                                                      "%Y-%m-%d %H:%M:%S")
                        elif "/" in rawValue:  # Ami Date
                            value = datetime.strptime(str(rawValue),
                                                      "%m/%d/%Y %H:%M:%S")
                        else:  # European Date
                            value = datetime.strptime(str(rawValue),
                                                      "%d.%m.%Y %H:%M:%S")
                    except:
                        if "-" in rawValue:  # ISO Date
                            value = datetime.strptime(str(rawValue),
                                                      "%Y-%m-%d %H:%M")
                        elif "/" in rawValue:  # Ami Date
                            value = datetime.strptime(str(rawValue),
                                                      "%m/%d/%Y %H:%M")
                        else:  # European Date
                            value = datetime.strptime(str(rawValue),
                                                      "%d.%m.%Y %H:%M")
                else:
                    if "-" in rawValue:  # ISO (Date only)
                        value = datetime.strptime(str(rawValue), "%Y-%m-%d")
                    elif "/" in rawValue:  # Ami (Date only)
                        value = datetime.strptime(str(rawValue), "%m/%d/%Y")
                    else:  # European (Date only)
                        value = datetime.strptime(str(rawValue), "%d.%m.%Y")
                value = datetime(value.year,
                                 value.month,
                                 value.day,
                                 value.hour,
                                 value.minute,
                                 value.second,
                                 tzinfo=timeZone)
            except:
                value = False  # its invalid
        if value is False:
            return self.getEmptyValue(), [
                ReadFromClientError(ReadFromClientErrorSeverity.Invalid, name,
                                    "Invalid value entered")
            ]
        err = self.isInvalid(value)
        if err:
            return self.getEmptyValue(), [
                ReadFromClientError(ReadFromClientErrorSeverity.Invalid, name,
                                    err)
            ]
        return value, None