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

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