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

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