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.2KB

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