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

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