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

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