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

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