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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. #-*- coding:utf-8 -*-
  2. import hashlib
  3. import importlib
  4. import copy
  5. from lodel.utils.mlstring import MlString
  6. from lodel.logger 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. # all groups & classes actives because we are in editor mode
  114. self.__active_groups = self.__groups
  115. self.__active_classes = self.__classes
  116. else:
  117. #determine groups first
  118. self.__active_groups = dict()
  119. for agrp in Settings.editorialmodel.groups:
  120. if agrp not in self.__groups:
  121. raise SettingsError('Invalid group found in settings : %s' % agrp)
  122. grp = self.__groups[agrp]
  123. self.__active_groups[grp.uid] = grp
  124. for acls in grp.components():
  125. self.__active_classes[acls.uid] = acls
  126. ##@brief EmField getter
  127. # @param uid str : An EmField uid represented by "CLASSUID.FIELDUID"
  128. # @return Fals or an EmField instance
  129. #
  130. # @todo delete it, useless...
  131. def field(self, uid = None):
  132. spl = uid.split('.')
  133. if len(spl) != 2:
  134. raise ValueError("Malformed EmField identifier : '%s'" % uid)
  135. cls_uid = spl[0]
  136. field_uid = spl[1]
  137. try:
  138. emclass = self.classes(cls_uid)
  139. except KeyError:
  140. return False
  141. try:
  142. return emclass.fields(field_uid)
  143. except KeyError:
  144. pass
  145. return False
  146. ##@brief Add a class to the editorial model
  147. # @param emclass EmClass : the EmClass instance to add
  148. # @return emclass
  149. def add_class(self, emclass):
  150. self.raise_if_ro()
  151. if not isinstance(emclass, EmClass):
  152. raise ValueError("<class EmClass> expected but got %s " % type(emclass))
  153. if emclass.uid in self.classes():
  154. raise EditorialModelException('Duplicated uid "%s"' % emclass.uid)
  155. self.__classes[emclass.uid] = emclass
  156. return emclass
  157. ##@brief Add a group to the editorial model
  158. # @param emgroup EmGroup : the EmGroup instance to add
  159. # @return emgroup
  160. def add_group(self, emgroup):
  161. self.raise_if_ro()
  162. if not isinstance(emgroup, EmGroup):
  163. raise ValueError("<class EmGroup> expected but got %s" % type(emgroup))
  164. if emgroup.uid in self.groups():
  165. raise EditorialModelException('Duplicated uid "%s"' % emgroup.uid)
  166. self.__groups[emgroup.uid] = emgroup
  167. return emgroup
  168. ##@brief Add a new EmClass to the editorial model
  169. #@param uid str : EmClass uid
  170. #@param **kwargs : EmClass constructor options (
  171. # see @ref lodel.editorial_model.component.EmClass.__init__() )
  172. def new_class(self, uid, **kwargs):
  173. self.raise_if_ro()
  174. return self.add_class(EmClass(uid, **kwargs))
  175. ##@brief Add a new EmGroup to the editorial model
  176. #@param uid str : EmGroup uid
  177. #@param *kwargs : EmGroup constructor keywords arguments (
  178. # see @ref lodel.editorial_model.component.EmGroup.__init__() )
  179. def new_group(self, uid, **kwargs):
  180. self.raise_if_ro()
  181. return self.add_group(EmGroup(uid, **kwargs))
  182. ##@brief Save a model
  183. # @param translator module : The translator module to use
  184. # @param **translator_args
  185. def save(self, translator, **translator_kwargs):
  186. self.raise_if_ro()
  187. if isinstance(translator, str):
  188. translator = self.translator_from_name(translator)
  189. return translator.save(self, **translator_kwargs)
  190. ##@brief Raise an error if lodel is not in EM edition mode
  191. @staticmethod
  192. def raise_if_ro():
  193. if not Settings.editorialmodel.editormode:
  194. raise EditorialModelError("Lodel in not in EM editor mode. The EM is in read only state")
  195. ##@brief Load a model
  196. # @param translator module : The translator module to use
  197. # @param **translator_args
  198. @classmethod
  199. def load(cls, translator, **translator_kwargs):
  200. if isinstance(translator, str):
  201. translator = cls.translator_from_name(translator)
  202. res = translator.load(**translator_kwargs)
  203. res.__set_actives()
  204. return res
  205. ##@brief Return a translator module given a translator name
  206. # @param translator_name str : The translator name
  207. # @return the translator python module
  208. # @throw NameError if the translator does not exists
  209. @staticmethod
  210. def translator_from_name(translator_name):
  211. pkg_name = 'lodel.editorial_model.translator.%s' % translator_name
  212. try:
  213. mod = importlib.import_module(pkg_name)
  214. except ImportError:
  215. raise NameError("No translator named %s")
  216. return mod
  217. ##@brief Lodel hash
  218. def d_hash(self):
  219. payload = "%s%s" % (
  220. self.name,
  221. 'NODESC' if self.description is None else self.description.d_hash()
  222. )
  223. for guid in sorted(self.__groups):
  224. payload += str(self.__groups[guid].d_hash())
  225. for cuid in sorted(self.__classes):
  226. payload += str(self.__classes[cuid].d_hash())
  227. return int.from_bytes(
  228. hashlib.md5(bytes(payload, 'utf-8')).digest(),
  229. byteorder='big'
  230. )