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

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