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 17KB

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