comparison libervia/backend/memory/params.py @ 4270:0d7bb4df2343

Reformatted code base using black.
author Goffi <goffi@goffi.org>
date Wed, 19 Jun 2024 18:44:57 +0200
parents 4b842c1fb686
children
comparison
equal deleted inserted replaced
4269:64a85ce8be70 4270:0d7bb4df2343
225 if profile_key == "@DEFAULT@": 225 if profile_key == "@DEFAULT@":
226 default = self.host.memory.memory_data.get("Profile_default") 226 default = self.host.memory.memory_data.get("Profile_default")
227 if not default: 227 if not default:
228 log.info(_("No default profile, returning first one")) 228 log.info(_("No default profile, returning first one"))
229 try: 229 try:
230 default = self.host.memory.memory_data[ 230 default = self.host.memory.memory_data["Profile_default"] = (
231 "Profile_default" 231 self.storage.get_profiles_list()[0]
232 ] = self.storage.get_profiles_list()[0] 232 )
233 except IndexError: 233 except IndexError:
234 log.info(_("No profile exist yet")) 234 log.info(_("No profile exist yet"))
235 raise exceptions.ProfileUnknownError(profile_key) 235 raise exceptions.ProfileUnknownError(profile_key)
236 return ( 236 return default # FIXME: temporary, must use real default value, and fallback to first one if it doesn't exists
237 default
238 ) # FIXME: temporary, must use real default value, and fallback to first one if it doesn't exists
239 elif profile_key == C.PROF_KEY_NONE: 237 elif profile_key == C.PROF_KEY_NONE:
240 raise exceptions.ProfileNotSetError 238 raise exceptions.ProfileNotSetError
241 elif return_profile_keys and profile_key in [C.PROF_KEY_ALL]: 239 elif return_profile_keys and profile_key in [C.PROF_KEY_ALL]:
242 return profile_key # this value must be managed by the caller 240 return profile_key # this value must be managed by the caller
243 if not self.storage.has_profile(profile_key): 241 if not self.storage.has_profile(profile_key):
282 for cat_node in type_node.childNodes: 280 for cat_node in type_node.childNodes:
283 if cat_node.nodeName != "category": 281 if cat_node.nodeName != "category":
284 to_remove.append(cat_node) 282 to_remove.append(cat_node)
285 continue 283 continue
286 to_remove_count = ( 284 to_remove_count = (
287 0 285 0 # count the params to be removed from current category
288 ) # count the params to be removed from current category 286 )
289 for node in cat_node.childNodes: 287 for node in cat_node.childNodes:
290 if node.nodeName != "param" or not self.check_security_limit( 288 if node.nodeName != "param" or not self.check_security_limit(
291 node, security_limit 289 node, security_limit
292 ): 290 ):
293 to_remove.append(node) 291 to_remove.append(node)
380 % {"category": category, "name": name} 378 % {"category": category, "name": name}
381 ) 379 )
382 node = self._get_param_node(name, category, "@ALL@") 380 node = self._get_param_node(name, category, "@ALL@")
383 if not node: 381 if not node:
384 log.error( 382 log.error(
385 _( 383 _("Requested param [%(name)s] in category [%(category)s] doesn't exist !")
386 "Requested param [%(name)s] in category [%(category)s] doesn't exist !"
387 )
388 % {"name": name, "category": category} 384 % {"name": name, "category": category}
389 ) 385 )
390 return 386 return
391 if node[1].getAttribute("default_cb") == "yes": 387 if node[1].getAttribute("default_cb") == "yes":
392 # del node[1].attributes['default_cb'] # default_cb is not used anymore as a flag to know if we have to set the default value, 388 # del node[1].attributes['default_cb'] # default_cb is not used anymore as a flag to know if we have to set the default value,
524 if password is None: 520 if password is None:
525 raise exceptions.InternalError("password should never be None") 521 raise exceptions.InternalError("password should never be None")
526 return defer.succeed(password) 522 return defer.succeed(password)
527 523
528 def _type_to_str(self, result): 524 def _type_to_str(self, result):
529 """Convert result to string, according to its type """ 525 """Convert result to string, according to its type"""
530 if isinstance(result, bool): 526 if isinstance(result, bool):
531 return C.bool_const(result) 527 return C.bool_const(result)
532 elif isinstance(result, (list, set, tuple)): 528 elif isinstance(result, (list, set, tuple)):
533 return ', '.join(self._type_to_str(r) for r in result) 529 return ", ".join(self._type_to_str(r) for r in result)
534 else: 530 else:
535 return str(result) 531 return str(result)
536 532
537 def get_string_param_a(self, name, category, attr="value", profile_key=C.PROF_KEY_NONE): 533 def get_string_param_a(
538 """ Same as param_get_a but for bridge: convert non string value to string """ 534 self, name, category, attr="value", profile_key=C.PROF_KEY_NONE
535 ):
536 """Same as param_get_a but for bridge: convert non string value to string"""
539 return self._type_to_str( 537 return self._type_to_str(
540 self.param_get_a(name, category, attr, profile_key=profile_key) 538 self.param_get_a(name, category, attr, profile_key=profile_key)
541 ) 539 )
542 540
543 def param_get_a( 541 def param_get_a(
558 # FIXME: looks really dirty and buggy, need to be reviewed/refactored 556 # FIXME: looks really dirty and buggy, need to be reviewed/refactored
559 # FIXME: security_limit is not managed here ! 557 # FIXME: security_limit is not managed here !
560 node = self._get_param_node(name, category) 558 node = self._get_param_node(name, category)
561 if not node: 559 if not node:
562 log.error( 560 log.error(
563 _( 561 _("Requested param [%(name)s] in category [%(category)s] doesn't exist !")
564 "Requested param [%(name)s] in category [%(category)s] doesn't exist !"
565 )
566 % {"name": name, "category": category} 562 % {"name": name, "category": category}
567 ) 563 )
568 raise exceptions.NotFound 564 raise exceptions.NotFound
569 565
570 if attr == "value" and node[1].getAttribute("type") == "password": 566 if attr == "value" and node[1].getAttribute("type") == "password":
594 if value is None and attr == "value" and not use_default: 590 if value is None and attr == "value" and not use_default:
595 return value 591 return value
596 return self._get_attr(node[1], attr, value) 592 return self._get_attr(node[1], attr, value)
597 593
598 async def async_get_string_param_a( 594 async def async_get_string_param_a(
599 self, name, category, attr="value", security_limit=C.NO_SECURITY_LIMIT, 595 self,
600 profile=C.PROF_KEY_NONE): 596 name,
597 category,
598 attr="value",
599 security_limit=C.NO_SECURITY_LIMIT,
600 profile=C.PROF_KEY_NONE,
601 ):
601 value = await self.param_get_a_async( 602 value = await self.param_get_a_async(
602 name, category, attr, security_limit, profile_key=profile) 603 name, category, attr, security_limit, profile_key=profile
604 )
603 return self._type_to_str(value) 605 return self._type_to_str(value)
604 606
605 def param_get_a_async( 607 def param_get_a_async(
606 self, 608 self,
607 name, 609 name,
619 @return (defer.Deferred): parameter value, with corresponding type (bool, int, list, etc) 621 @return (defer.Deferred): parameter value, with corresponding type (bool, int, list, etc)
620 """ 622 """
621 node = self._get_param_node(name, category) 623 node = self._get_param_node(name, category)
622 if not node: 624 if not node:
623 log.error( 625 log.error(
624 _( 626 _("Requested param [%(name)s] in category [%(category)s] doesn't exist !")
625 "Requested param [%(name)s] in category [%(category)s] doesn't exist !"
626 )
627 % {"name": name, "category": category} 627 % {"name": name, "category": category}
628 ) 628 )
629 raise ValueError("Requested param doesn't exist") 629 raise ValueError("Requested param doesn't exist")
630 630
631 if not self.check_security_limit(node[1], security_limit): 631 if not self.check_security_limit(node[1], security_limit):
660 return d.addCallback( 660 return d.addCallback(
661 lambda value: self._async_get_attr(node[1], attr, value, profile) 661 lambda value: self._async_get_attr(node[1], attr, value, profile)
662 ) 662 )
663 663
664 def _get_params_values_from_category( 664 def _get_params_values_from_category(
665 self, category, security_limit, app, extra_s, profile_key): 665 self, category, security_limit, app, extra_s, profile_key
666 ):
666 client = self.host.get_client(profile_key) 667 client = self.host.get_client(profile_key)
667 extra = data_format.deserialise(extra_s) 668 extra = data_format.deserialise(extra_s)
668 return defer.ensureDeferred(self.get_params_values_from_category( 669 return defer.ensureDeferred(
669 client, category, security_limit, app, extra)) 670 self.get_params_values_from_category(
671 client, category, security_limit, app, extra
672 )
673 )
670 674
671 async def get_params_values_from_category( 675 async def get_params_values_from_category(
672 self, client, category, security_limit, app='', extra=None): 676 self, client, category, security_limit, app="", extra=None
677 ):
673 """Get all parameters "attribute" for a category 678 """Get all parameters "attribute" for a category
674 679
675 @param category(unicode): the desired category 680 @param category(unicode): the desired category
676 @param security_limit(int): NO_SECURITY_LIMIT (-1) to return all the params. 681 @param security_limit(int): NO_SECURITY_LIMIT (-1) to return all the params.
677 Otherwise sole the params which have a security level defined *and* 682 Otherwise sole the params which have a security level defined *and*
695 param_node.toxml() 700 param_node.toxml()
696 ) 701 )
697 ) 702 )
698 continue 703 continue
699 value = await self.async_get_string_param_a( 704 value = await self.async_get_string_param_a(
700 name, category, security_limit=security_limit, 705 name,
701 profile=client.profile) 706 category,
707 security_limit=security_limit,
708 profile=client.profile,
709 )
702 710
703 ret[name] = value 711 ret[name] = value
704 break 712 break
705 713
706 prof_xml.unlink() 714 prof_xml.unlink()
749 """ 757 """
750 profile = client.profile 758 profile = client.profile
751 759
752 def check_node(node): 760 def check_node(node):
753 """Check the node against security_limit, app and extra""" 761 """Check the node against security_limit, app and extra"""
754 return (self.check_security_limit(node, security_limit) 762 return (
755 and self.check_app(node, app) 763 self.check_security_limit(node, security_limit)
756 and self.check_extra(node, extra)) 764 and self.check_app(node, app)
765 and self.check_extra(node, extra)
766 )
757 767
758 if profile in self.params: 768 if profile in self.params:
759 profile_cache = self.params[profile] 769 profile_cache = self.params[profile]
760 else: 770 else:
761 # profile is not in cache, we load values in a short time cache 771 # profile is not in cache, we load values in a short time cache
826 option.removeAttribute("selected") 836 option.removeAttribute("selected")
827 except NotFoundErr: 837 except NotFoundErr:
828 pass 838 pass
829 elif dest_params[name].getAttribute("type") == "jids_list": 839 elif dest_params[name].getAttribute("type") == "jids_list":
830 jids = profile_value.split("\t") 840 jids = profile_value.split("\t")
831 for jid_elt in dest_params[name].getElementsByTagName( 841 for jid_elt in dest_params[name].getElementsByTagName("jid"):
832 "jid"
833 ):
834 dest_params[name].removeChild( 842 dest_params[name].removeChild(
835 jid_elt 843 jid_elt
836 ) # remove all default 844 ) # remove all default
837 for jid_ in jids: # rebuilt the children with use values 845 for jid_ in jids: # rebuilt the children with use values
838 try: 846 try:
864 for node in to_remove: 872 for node in to_remove:
865 prof_xml.documentElement.removeChild(node) 873 prof_xml.documentElement.removeChild(node)
866 874
867 return prof_xml 875 return prof_xml
868 876
869
870 def _get_params_ui(self, security_limit, app, extra_s, profile_key): 877 def _get_params_ui(self, security_limit, app, extra_s, profile_key):
871 client = self.host.get_client(profile_key) 878 client = self.host.get_client(profile_key)
872 extra = data_format.deserialise(extra_s) 879 extra = data_format.deserialise(extra_s)
873 return defer.ensureDeferred(self.param_ui_get(client, security_limit, app, extra)) 880 return defer.ensureDeferred(self.param_ui_get(client, security_limit, app, extra))
874 881
938 name = cat.getAttribute("name") 945 name = cat.getAttribute("name")
939 if name not in categories: 946 if name not in categories:
940 categories.append(cat.getAttribute("name")) 947 categories.append(cat.getAttribute("name"))
941 return categories 948 return categories
942 949
943 def param_set(self, name, value, category, security_limit=C.NO_SECURITY_LIMIT, 950 def param_set(
944 profile_key=C.PROF_KEY_NONE): 951 self,
952 name,
953 value,
954 category,
955 security_limit=C.NO_SECURITY_LIMIT,
956 profile_key=C.PROF_KEY_NONE,
957 ):
945 """Set a parameter, return None if the parameter is not in param xml. 958 """Set a parameter, return None if the parameter is not in param xml.
946 959
947 Parameter of type 'password' that are not the SàT profile password are 960 Parameter of type 'password' that are not the SàT profile password are
948 stored encrypted (if not empty). The profile password is stored hashed 961 stored encrypted (if not empty). The profile password is stored hashed
949 (if not empty). 962 (if not empty).
971 return defer.succeed(None) 984 return defer.succeed(None)
972 985
973 if not self.check_security_limit(node[1], security_limit): 986 if not self.check_security_limit(node[1], security_limit):
974 msg = _( 987 msg = _(
975 "{profile!r} is trying to set parameter {name!r} in category " 988 "{profile!r} is trying to set parameter {name!r} in category "
976 "{category!r} without authorization!!!").format( 989 "{category!r} without authorization!!!"
977 profile=repr(profile), 990 ).format(profile=repr(profile), name=repr(name), category=repr(category))
978 name=repr(name),
979 category=repr(category)
980 )
981 log.warning(msg) 991 log.warning(msg)
982 raise exceptions.PermissionError(msg) 992 raise exceptions.PermissionError(msg)
983 993
984 type_ = node[1].getAttribute("type") 994 type_ = node[1].getAttribute("type")
985 if type_ == "int": 995 if type_ == "int":
987 value = node[1].getAttribute("value") 997 value = node[1].getAttribute("value")
988 else: 998 else:
989 try: 999 try:
990 int(value) 1000 int(value)
991 except ValueError: 1001 except ValueError:
992 log.warning(_( 1002 log.warning(
993 "Trying to set parameter {name} in category {category} with" 1003 _(
994 "an non-integer value" 1004 "Trying to set parameter {name} in category {category} with"
995 ).format( 1005 "an non-integer value"
996 name=repr(name), 1006 ).format(name=repr(name), category=repr(category))
997 category=repr(category) 1007 )
998 ))
999 return defer.succeed(None) 1008 return defer.succeed(None)
1000 if node[1].hasAttribute("constraint"): 1009 if node[1].hasAttribute("constraint"):
1001 constraint = node[1].getAttribute("constraint") 1010 constraint = node[1].getAttribute("constraint")
1002 try: 1011 try:
1003 min_, max_ = [int(limit) for limit in constraint.split(";")] 1012 min_, max_ = [int(limit) for limit in constraint.split(";")]
1133 1142
1134 @param node: parameter node 1143 @param node: parameter node
1135 @param app: name of the frontend requesting the parameters, or '' to get all parameters 1144 @param app: name of the frontend requesting the parameters, or '' to get all parameters
1136 @return: True if node doesn't match category/name of extra['ignore'] list 1145 @return: True if node doesn't match category/name of extra['ignore'] list
1137 """ 1146 """
1138 ignore_list = extra.get('ignore') 1147 ignore_list = extra.get("ignore")
1139 if not ignore_list: 1148 if not ignore_list:
1140 return True 1149 return True
1141 category = node.parentNode.getAttribute('name') 1150 category = node.parentNode.getAttribute("name")
1142 name = node.getAttribute('name') 1151 name = node.getAttribute("name")
1143 ignore = [category, name] in ignore_list 1152 ignore = [category, name] in ignore_list
1144 if ignore: 1153 if ignore:
1145 log.debug(f"Ignoring parameter {category}/{name} as requested") 1154 log.debug(f"Ignoring parameter {category}/{name} as requested")
1146 return False 1155 return False
1147 return True 1156 return True
1162 for value, label in options.items(): 1171 for value, label in options.items():
1163 if value == selected: 1172 if value == selected:
1164 selected = 'selected="true"' 1173 selected = 'selected="true"'
1165 selected_found = True 1174 selected_found = True
1166 else: 1175 else:
1167 selected = '' 1176 selected = ""
1168 str_list.append( 1177 str_list.append(
1169 f'<option value={quoteattr(value)} label={quoteattr(label)} {selected}/>' 1178 f"<option value={quoteattr(value)} label={quoteattr(label)} {selected}/>"
1170 ) 1179 )
1171 if not selected_found: 1180 if not selected_found:
1172 raise ValueError(f"selected value ({selected}) not found in options") 1181 raise ValueError(f"selected value ({selected}) not found in options")
1173 return '\n'.join(str_list) 1182 return "\n".join(str_list)