No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

components.py 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. #-*- coding: utf-8 -*-
  2. import itertools
  3. import warnings
  4. import copy
  5. import hashlib
  6. from lodel.utils.mlstring import MlString
  7. from lodel.editorial_model.exceptions import *
  8. ##@brief Abstract class to represent editorial model components
  9. # @see EmClass EmField
  10. # @todo forbid '.' in uid
  11. class EmComponent(object):
  12. ##@brief Instanciate an EmComponent
  13. # @param uid str : uniq identifier
  14. # @param display_name MlString|str|dict : component display_name
  15. # @param help_text MlString|str|dict : help_text
  16. def __init__(self, uid, display_name = None, help_text = None, group = None):
  17. if self.__class__ == EmComponent:
  18. raise NotImplementedError('EmComponent is an abstract class')
  19. self.uid = uid
  20. self.display_name = None if display_name is None else MlString(display_name)
  21. self.help_text = None if help_text is None else MlString(help_text)
  22. self.group = group
  23. def __str__(self):
  24. if self.display_name is None:
  25. return str(self.uid)
  26. return str(self.display_name)
  27. def d_hash(self):
  28. m = hashlib.md5()
  29. for data in (
  30. self.uid,
  31. 'NODISPNAME' if self.display_name is None else str(self.display_name.d_hash()),
  32. 'NOHELP' if self.help_text is None else str(self.help_text.d_hash()),
  33. 'NOGROUP' if self.group is None else str(self.group.d_hash()),
  34. ):
  35. m.update(bytes(data, 'utf-8'))
  36. return int.from_bytes(m.digest(), byteorder='big')
  37. ##@brief Handles editorial model objects classes
  38. class EmClass(EmComponent):
  39. ##@brief Instanciate a new EmClass
  40. # @param uid str : uniq identifier
  41. # @param display_name MlString|str|dict : component display_name
  42. # @param abstract bool : set the class as asbtract if True
  43. # @param pure_abstract bool : if True the EmClass will not be represented in leapi dyncode
  44. # @param parents list: parent EmClass list or uid list
  45. # @param help_text MlString|str|dict : help_text
  46. def __init__(self, uid, display_name = None, help_text = None, abstract = False, parents = None, group = None, pure_abstract = False):
  47. super().__init__(uid, display_name, help_text, group)
  48. self.abstract = bool(abstract)
  49. self.pure_abstract = bool(pure_abstract)
  50. if self.pure_abstract:
  51. self.abtract = True
  52. if parents is not None:
  53. if not isinstance(parents, list):
  54. parents = [parents]
  55. for parent in parents:
  56. if not isinstance(parent, EmClass):
  57. raise ValueError("<class EmClass> expected in parents list, but %s found" % type(parent))
  58. else:
  59. parents = list()
  60. self.parents = parents
  61. ##@brief Stores EmFields instances indexed by field uid
  62. self.__fields = dict()
  63. ##@brief Property that represent a dict of all fields (the EmField defined in this class and all its parents)
  64. @property
  65. def __all_fields(self):
  66. res = dict()
  67. for pfields in [ p.__all_fields for p in self.parents]:
  68. res.update(pfields)
  69. res.update(self.__fields)
  70. return res
  71. ##@brief Return the list of all dependencies
  72. #
  73. # Reccursive parents listing
  74. @property
  75. def parents_recc(self):
  76. if len(self.parents) == 0:
  77. return set()
  78. res = set(self.parents)
  79. for parent in self.parents:
  80. res |= parent.parents_recc
  81. return res
  82. ##@brief EmField getter
  83. # @param uid None | str : If None returns an iterator on EmField instances else return an EmField instance
  84. # @param no_parents bool : If True returns only fields defined is this class and not the one defined in parents classes
  85. # @return A list on EmFields instances (if uid is None) else return an EmField instance
  86. def fields(self, uid = None, no_parents = False):
  87. fields = self.__fields if no_parents else self.__all_fields
  88. try:
  89. return list(fields.values()) if uid is None else fields[uid]
  90. except KeyError:
  91. raise EditorialModelError("No such EmField '%s'" % uid)
  92. ##@brief Add a field to the EmClass
  93. # @param emfield EmField : an EmField instance
  94. # @warning do not add an EmField allready in another class !
  95. # @throw EditorialModelException if an EmField with same uid allready in this EmClass (overwritting allowed from parents)
  96. # @todo End the override checks (needs methods in data_handlers)
  97. def add_field(self, emfield):
  98. if emfield.uid in self.__fields:
  99. raise EditorialModelError("Duplicated uid '%s' for EmField in this class ( %s )" % (emfield.uid, self))
  100. # Incomplete field override check
  101. if emfield.uid in self.__all_fields:
  102. parent_field = self.__all_fields[emfield.uid]
  103. if not emfield.data_handler_instance.can_override(parent_field.data_handler_instance):
  104. raise AttributeError("'%s' field override a parent field, but data_handles are not compatible" % emfield.uid)
  105. self.__fields[emfield.uid] = emfield
  106. emfield._emclass = self
  107. return emfield
  108. ##@brief Create a new EmField and add it to the EmClass
  109. # @param data_handler str : A DataHandler name
  110. # @param uid str : the EmField uniq id
  111. # @param **field_kwargs : EmField constructor parameters ( see @ref EmField.__init__() )
  112. def new_field(self, uid, data_handler, **field_kwargs):
  113. return self.add_field(EmField(uid, data_handler, **field_kwargs))
  114. def d_hash(self):
  115. m = hashlib.md5()
  116. payload = str(super().d_hash()) + ("1" if self.abstract else "0")
  117. for p in sorted(self.parents):
  118. payload += str(p.d_hash())
  119. for fuid in sorted(self.__fields.keys()):
  120. payload += str(self.__fields[fuid].d_hash())
  121. m.update(bytes(payload, 'utf-8'))
  122. return int.from_bytes(m.digest(), byteorder='big')
  123. def __str__(self):
  124. return "<class EmClass %s>" % self.uid
  125. def __repr__(self):
  126. if not self.abstract:
  127. abstract = ''
  128. elif self.pure_abstract:
  129. abstract = 'PureAbstract'
  130. else:
  131. abstract = 'Abstract'
  132. return "<class %s EmClass uid=%s>" % (abstract, repr(self.uid) )
  133. ##@brief Handles editorial model classes fields
  134. class EmField(EmComponent):
  135. ##@brief Instanciate a new EmField
  136. # @param uid str : uniq identifier
  137. # @param display_name MlString|str|dict : field display_name
  138. # @param data_handler str : A DataHandler name
  139. # @param help_text MlString|str|dict : help text
  140. # @param group EmGroup :
  141. # @param **handler_kwargs : data handler arguments
  142. def __init__(self, uid, data_handler, display_name = None, help_text = None, group = None, **handler_kwargs):
  143. from lodel.leapi.datahandlers.base_classes import DataHandler
  144. super().__init__(uid, display_name, help_text, group)
  145. ##@brief The data handler name
  146. self.data_handler_name = data_handler
  147. ##@brief The data handler class
  148. self.data_handler_cls = DataHandler.from_name(data_handler)
  149. ##@brief The data handler instance associated with this EmField
  150. self.data_handler_instance = self.data_handler_cls(**handler_kwargs)
  151. ##@brief Stores data handler instanciation options
  152. self.data_handler_options = handler_kwargs
  153. ##@brief Stores the emclass that contains this field (set by EmClass.add_field() method)
  154. self._emclass = None
  155. ##@brief Returns data_handler_name attribute
  156. def get_data_handler_name(self):
  157. return copy.copy(self.data_handler_name)
  158. ##@brief Returns data_handler_cls attribute
  159. def get_data_handler_cls(self):
  160. return copy.copy(selfdata_handler_cls)
  161. # @warning Not complete !
  162. # @todo Complete the hash when data handlers becomes available
  163. def d_hash(self):
  164. return int.from_bytes(hashlib.md5(
  165. bytes(
  166. "%s%s%s" % ( super().d_hash(),
  167. self.data_handler_name,
  168. self.data_handler_options),
  169. 'utf-8')
  170. ).digest(), byteorder='big')
  171. ##@brief Handles functionnal group of EmComponents
  172. class EmGroup(object):
  173. ##@brief Create a new EmGroup
  174. # @note you should NEVER call the constructor yourself. Use Model.add_group instead
  175. # @param uid str : Uniq identifier
  176. # @param depends list : A list of EmGroup dependencies
  177. # @param display_name MlString|str :
  178. # @param help_text MlString|str :
  179. def __init__(self, uid, depends = None, display_name = None, help_text = None):
  180. self.uid = uid
  181. ##@brief Stores the list of groups that depends on this EmGroup indexed by uid
  182. self.required_by = dict()
  183. ##@brief Stores the list of dependencies (EmGroup) indexed by uid
  184. self.require = dict()
  185. ##@brief Stores the list of EmComponent instances contained in this group
  186. self.__components = set()
  187. self.display_name = None if display_name is None else MlString(display_name)
  188. self.help_text = None if help_text is None else MlString(help_text)
  189. if depends is not None:
  190. for grp in depends:
  191. if not isinstance(grp, EmGroup):
  192. raise ValueError("EmGroup expected in depends argument but %s found" % grp)
  193. self.add_dependencie(grp)
  194. ##@brief Returns EmGroup dependencie
  195. # @param recursive bool : if True return all dependencies and their dependencies
  196. # @return a dict of EmGroup identified by uid
  197. def dependencies(self, recursive = False):
  198. res = copy.copy(self.require)
  199. if not recursive:
  200. return res
  201. to_scan = list(res.values())
  202. while len(to_scan) > 0:
  203. cur_dep = to_scan.pop()
  204. for new_dep in cur_dep.require.values():
  205. if new_dep not in res:
  206. to_scan.append(new_dep)
  207. res[new_dep.uid] = new_dep
  208. return res
  209. ##@brief Returns EmGroup applicants
  210. # @param recursive bool : if True return all dependencies and their dependencies
  211. # @returns a dict of EmGroup identified by uid
  212. def applicants(self, recursive = False):
  213. res = copy.copy(self.required_by)
  214. if not recursive:
  215. return res
  216. to_scan = list(res.values())
  217. while len(to_scan) > 0:
  218. cur_app = to_scan.pop()
  219. for new_app in cur_app.required_by.values():
  220. if new_app not in res:
  221. to_scan.append(new_app)
  222. res[new_app.uid] = new_app
  223. return res
  224. ##@brief Returns EmGroup components
  225. # @returns a copy of the set of components
  226. def components(self):
  227. return (self.__components).copy()
  228. ##@brief Returns EmGroup display_name
  229. # @param lang str | None : If None return default lang translation
  230. # @returns None if display_name is None, a str for display_name else
  231. def get_display_name(self, lang=None):
  232. name=self.display_name
  233. if name is None : return None
  234. return name.get(lang);
  235. ##@brief Returns EmGroup help_text
  236. # @param lang str | None : If None return default lang translation
  237. # @returns None if display_name is None, a str for display_name else
  238. def get_help_text(self, lang=None):
  239. help=self.help_text
  240. if help is None : return None
  241. return help.get(lang);
  242. ##@brief Add components in a group
  243. # @param components list : EmComponent instances list
  244. def add_components(self, components):
  245. for component in components:
  246. if isinstance(component, EmField):
  247. if component._emclass is None:
  248. warnings.warn("Adding an orphan EmField to an EmGroup")
  249. elif not isinstance(component, EmClass):
  250. raise EditorialModelError("Expecting components to be a list of EmComponent, but %s found in the list" % type(component))
  251. self.__components |= set(components)
  252. ##@brief Add a dependencie
  253. # @param em_group EmGroup|iterable : an EmGroup instance or list of instance
  254. def add_dependencie(self, grp):
  255. try:
  256. for group in grp:
  257. self.add_dependencie(group)
  258. return
  259. except TypeError: pass
  260. if grp.uid in self.require:
  261. return
  262. if self.__circular_dependencie(grp):
  263. raise EditorialModelError("Circular dependencie detected, cannot add dependencie")
  264. self.require[grp.uid] = grp
  265. grp.required_by[self.uid] = self
  266. ##@brief Add a applicant
  267. # @param em_group EmGroup|iterable : an EmGroup instance or list of instance
  268. def add_applicant(self, grp):
  269. try:
  270. for group in grp:
  271. self.add_applicant(group)
  272. return
  273. except TypeError: pass
  274. if grp.uid in self.required_by:
  275. return
  276. if self.__circular_applicant(grp):
  277. raise EditorialModelError("Circular applicant detected, cannot add applicant")
  278. self.required_by[grp.uid] = grp
  279. grp.require[self.uid] = self
  280. ##@brief Search for circular dependencie
  281. # @return True if circular dep found else False
  282. def __circular_dependencie(self, new_dep):
  283. return self.uid in new_dep.dependencies(True)
  284. ##@brief Search for circular applicant
  285. # @return True if circular app found else False
  286. def __circular_applicant(self, new_app):
  287. return self.uid in new_app.applicants(True)
  288. ##@brief Fancy string representation of an EmGroup
  289. # @return a string
  290. def __str__(self):
  291. if self.display_name is None:
  292. return self.uid
  293. else:
  294. return self.display_name.get()
  295. def d_hash(self):
  296. payload = "%s%s%s" % (
  297. self.uid,
  298. 'NODNAME' if self.display_name is None else self.display_name.d_hash(),
  299. 'NOHELP' if self.help_text is None else self.help_text.d_hash()
  300. )
  301. for recurs in (False, True):
  302. deps = self.dependencies(recurs)
  303. for dep_uid in sorted(deps.keys()):
  304. payload += str(deps[dep_uid].d_hash())
  305. for req_by_uid in self.required_by:
  306. payload += req_by_uid
  307. return int.from_bytes(
  308. bytes(payload, 'utf-8'),
  309. byteorder = 'big'
  310. )
  311. ##@brief Complete string representation of an EmGroup
  312. # @return a string
  313. def __repr__(self):
  314. return "<class EmGroup '%s' depends : [%s]>" % (self.uid, ', '.join([duid for duid in self.dependencies(False)]) )