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.

model.py 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. #-*- coding:utf-8 -*-
  2. import hashlib
  3. import importlib
  4. import copy
  5. from lodel.context import LodelContext
  6. LodelContext.expose_modules(globals(), {
  7. 'lodel.utils.mlstring': ['MlString'],
  8. 'lodel.mlnamedobject.mlnamedobject': ['MlNamedObject'],
  9. 'lodel.logger': 'logger',
  10. 'lodel.settings': ['Settings'],
  11. 'lodel.settings.utils': ['SettingsError'],
  12. 'lodel.editorial_model.exceptions': ['EditorialModelError', 'assert_edit'],
  13. 'lodel.editorial_model.components': ['EmClass', 'EmField', 'EmGroup']})
  14. ##@brief Describe an editorial model
  15. #@ingroup lodel2_em
  16. class EditorialModel(MlNamedObject):
  17. ##@brief Create a new editorial model
  18. # @param name MlString|str|dict : the editorial model name
  19. # @param description MlString|str|dict : the editorial model description
  20. def __init__(self, name, description = None, display_name = None, help_text = None):
  21. self.name = MlString(name)
  22. self.description = MlString(description)
  23. ##@brief Stores all groups indexed by id
  24. self.__groups = dict()
  25. ##@brief Stores all classes indexed by id
  26. self.__classes = dict()
  27. ## @brief Stores all activated groups indexed by id
  28. self.__active_groups = dict()
  29. ## @brief Stores all activated classes indexed by id
  30. self.__active_classes = dict()
  31. self.__set_actives()
  32. if display_name is None:
  33. display_name = name
  34. if help_text is None:
  35. help_text = description
  36. super().__init__(display_name, help_text)
  37. ##@brief EmClass uids accessor
  38. #@return a dict of emclasses
  39. def all_classes(self, uid = None):
  40. if uid is None:
  41. return copy.copy(self.__classes)
  42. else:
  43. try:
  44. return copy.copy(self.__classes[uid])
  45. except KeyError:
  46. raise EditorialModelException("EmClass not found : '%s'" % uid)
  47. def all_classes_ref(self, uid = None):
  48. if uid is None:
  49. return self.__classes
  50. else:
  51. try:
  52. return self.__classes[uid]
  53. except KeyError:
  54. raise EditorialModelException("EmGroup not found : '%s'" % uid)
  55. ##@brief active EmClass uids accessor
  56. #@return a list of class uids
  57. def active_classes_uids(self):
  58. return list(self.__active_classes.keys())
  59. ##@brief EmGroups accessor
  60. #@return a dict of groups
  61. def all_groups(self, uid = None):
  62. if uid is None:
  63. return copy.copy(self.__groups)
  64. else:
  65. try:
  66. return copy.copy(self.__groups[uid])
  67. except KeyError:
  68. raise EditorialModelException("EmGroup not found : '%s'" % uid)
  69. ##@brief EmGroups accessor
  70. #@return a dict of groups
  71. def all_groups_ref(self, uid = None):
  72. if uid is None:
  73. return self.__groups
  74. else:
  75. try:
  76. return self.__groups[uid]
  77. except KeyError:
  78. raise EditorialModelException("EmGroup not found : '%s'" % uid)
  79. ##@brief active EmClass uids accessor
  80. #@return a list of class uids
  81. def active_groups_uids(self):
  82. return list(self.__active_groups.keys())
  83. ##@brief EmClass accessor
  84. #@param uid None | str : give this argument to get a specific EmClass
  85. #@return if uid is given returns an EmClass else returns an EmClass
  86. # iterator
  87. #@todo use Settings.editorialmodel.groups to determine wich classes should
  88. # be returned
  89. def classes(self, uid = None):
  90. try:
  91. return self.__elt_getter( self.__active_classes,
  92. uid)
  93. except KeyError:
  94. raise EditorialModelException("EmClass not found : '%s'" % uid)
  95. ##@brief EmClass child list accessor
  96. #@param uid str : the EmClass uid
  97. #@return a set of EmClass
  98. def get_class_childs(self, uid):
  99. res = list()
  100. cur = self.classes(uid)
  101. for cls in self.classes():
  102. if cur in cls.parents_recc:
  103. res.append(cls)
  104. return set(res)
  105. ##@brief EmGroup getter
  106. # @param uid None | str : give this argument to get a specific EmGroup
  107. # @return if uid is given returns an EmGroup else returns an EmGroup iterator
  108. def groups(self, uid = None):
  109. try:
  110. return self.__elt_getter( self.__active_groups,
  111. uid)
  112. except KeyError:
  113. raise EditorialModelException("EmGroup not found : '%s'" % uid)
  114. ##@brief Private getter for __groups or __classes
  115. # @see classes() groups()
  116. def __elt_getter(self, elts, uid):
  117. return list(elts.values()) if uid is None else elts[uid]
  118. ##@brief Update the EditorialModel.__active_groups and
  119. #EditorialModel.__active_classes attibutes
  120. def __set_actives(self):
  121. if Settings.editorialmodel.editormode:
  122. logger.warning("All EM groups active because editormode in ON")
  123. # all groups & classes actives because we are in editor mode
  124. self.__active_groups = self.__groups
  125. self.__active_classes = self.__classes
  126. else:
  127. #determine groups first
  128. self.__active_groups = dict()
  129. self.__active_classes = dict()
  130. for agrp in Settings.editorialmodel.groups:
  131. if agrp not in self.__groups:
  132. raise SettingsError('Invalid group found in settings : %s' % agrp)
  133. logger.debug("Set group '%s' as active" % agrp)
  134. grp = self.__groups[agrp]
  135. self.__active_groups[grp.uid] = grp
  136. for acls in [cls for cls in grp.components() if isinstance(cls, EmClass)]:
  137. self.__active_classes[acls.uid] = acls
  138. if len(self.__active_groups) == 0:
  139. raise RuntimeError("No groups activated, abording...")
  140. if len(self.__active_classes) == 0:
  141. raise RuntimeError("No active class found. Abording")
  142. for clsname, acls in self.__active_classes.items():
  143. acls._set_active_fields(self.__active_groups)
  144. ##@brief EmField getter
  145. # @param uid str : An EmField uid represented by "CLASSUID.FIELDUID"
  146. # @return Fals or an EmField instance
  147. #
  148. # @todo delete it, useless...
  149. def field(self, uid = None):
  150. spl = uid.split('.')
  151. if len(spl) != 2:
  152. raise ValueError("Malformed EmField identifier : '%s'" % uid)
  153. cls_uid = spl[0]
  154. field_uid = spl[1]
  155. try:
  156. emclass = self.classes(cls_uid)
  157. except KeyError:
  158. return False
  159. try:
  160. return emclass.fields(field_uid)
  161. except KeyError:
  162. pass
  163. return False
  164. ##@brief Add a class to the editorial model
  165. # @param emclass EmClass : the EmClass instance to add
  166. # @return emclass
  167. def add_class(self, emclass):
  168. assert_edit()
  169. if not isinstance(emclass, EmClass):
  170. raise ValueError("<class EmClass> expected but got %s " % type(emclass))
  171. if emclass.uid in self.classes():
  172. raise EditorialModelException('Duplicated uid "%s"' % emclass.uid)
  173. self.__classes[emclass.uid] = emclass
  174. return emclass
  175. ##@brief Add a group to the editorial model
  176. # @param emgroup EmGroup : the EmGroup instance to add
  177. # @return emgroup
  178. def add_group(self, emgroup):
  179. assert_edit()
  180. if not isinstance(emgroup, EmGroup):
  181. raise ValueError("<class EmGroup> expected but got %s" % type(emgroup))
  182. if emgroup.uid in self.groups():
  183. raise EditorialModelException('Duplicated uid "%s"' % emgroup.uid)
  184. self.__groups[emgroup.uid] = emgroup
  185. return emgroup
  186. ##@brief Add a new EmClass to the editorial model
  187. #@param uid str : EmClass uid
  188. #@param **kwargs : EmClass constructor options (
  189. # see @ref lodel.editorial_model.component.EmClass.__init__() )
  190. def new_class(self, uid, **kwargs):
  191. assert_edit()
  192. return self.add_class(EmClass(uid, **kwargs))
  193. ##@brief Add a new EmGroup to the editorial model
  194. #@param uid str : EmGroup uid
  195. #@param *kwargs : EmGroup constructor keywords arguments (
  196. # see @ref lodel.editorial_model.component.EmGroup.__init__() )
  197. def new_group(self, uid, **kwargs):
  198. assert_edit()
  199. return self.add_group(EmGroup(uid, **kwargs))
  200. ##@brief Save a model
  201. # @param translator module : The translator module to use
  202. # @param **translator_args
  203. def save(self, translator, **translator_kwargs):
  204. assert_edit()
  205. if isinstance(translator, str):
  206. translator = self.translator_from_name(translator)
  207. return translator.save(self, **translator_kwargs)
  208. ##@brief Raise an error if lodel is not in EM edition mode
  209. @staticmethod
  210. def raise_if_ro():
  211. if not Settings.editorialmodel.editormode:
  212. raise EditorialModelError("Lodel in not in EM editor mode. The EM is in read only state")
  213. ##@brief Load a model
  214. # @param translator module : The translator module to use
  215. # @param **translator_args
  216. @classmethod
  217. def load(cls, translator, **translator_kwargs):
  218. if isinstance(translator, str):
  219. translator = cls.translator_from_name(translator)
  220. res = translator.load(**translator_kwargs)
  221. res.__set_actives()
  222. return res
  223. ##@brief Return a translator module given a translator name
  224. # @param translator_name str : The translator name
  225. # @return the translator python module
  226. # @throw NameError if the translator does not exists
  227. @staticmethod
  228. def translator_from_name(translator_name):
  229. pkg_name = 'lodel.editorial_model.translator.%s' % translator_name
  230. try:
  231. mod = importlib.import_module(pkg_name)
  232. except ImportError:
  233. raise NameError("No translator named %s")
  234. return mod
  235. ##@brief Lodel hash
  236. def d_hash(self):
  237. payload = "%s%s" % (
  238. self.name,
  239. 'NODESC' if self.description is None else self.description.d_hash()
  240. )
  241. for guid in sorted(self.__groups):
  242. payload += str(self.__groups[guid].d_hash())
  243. for cuid in sorted(self.__classes):
  244. payload += str(self.__classes[cuid].d_hash())
  245. return int.from_bytes(
  246. hashlib.md5(bytes(payload, 'utf-8')).digest(),
  247. byteorder='big'
  248. )