説明なし
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

components.py 17KB

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