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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. #-*- coding: utf-8 -*-
  2. ## @file editorialmodel.py
  3. # Manage instance of an editorial model
  4. import random
  5. import time
  6. import EditorialModel
  7. from EditorialModel.migrationhandler.dummy import DummyMigrationHandler
  8. from EditorialModel.backend.dummy_backend import EmBackendDummy
  9. from EditorialModel.classes import EmClass
  10. from EditorialModel.fieldgroups import EmFieldGroup
  11. from EditorialModel.fields import EmField
  12. from EditorialModel.types import EmType
  13. from EditorialModel.classtypes import EmClassType
  14. from Lodel.utils.mlstring import MlString
  15. from EditorialModel.exceptions import EmComponentCheckError, EmComponentNotExistError, MigrationHandlerChangeError
  16. import hashlib
  17. ## Manages the Editorial Model
  18. class Model(object):
  19. components_class = [EmClass, EmType, EmFieldGroup, EmField]
  20. ## Constructor
  21. #
  22. # @param backend unknown: A backend object instanciated from one of the classes in the backend module
  23. def __init__(self, backend, migration_handler=None):
  24. self.migration_handler = DummyMigrationHandler() if migration_handler is None else migration_handler
  25. self.backend = backend
  26. self._components = {'uids': {}, 'EmClass': [], 'EmType': [], 'EmField': [], 'EmFieldGroup': []}
  27. self.load()
  28. def __hash__(self):
  29. components_dump = ""
  30. for _, comp in self._components['uids'].items():
  31. components_dump += str(hash(comp))
  32. hashstring = hashlib.new('sha512')
  33. hashstring.update(components_dump.encode('utf-8'))
  34. return int(hashstring.hexdigest(), 16)
  35. def __eq__(self, other):
  36. return self.__hash__() == other.__hash__()
  37. @staticmethod
  38. ## Given a name return an EmComponent child class
  39. # @param class_name str : The name to identify an EmComponent class
  40. # @return A python class or False if the class_name is not a name of an EmComponent child class
  41. def emclass_from_name(class_name):
  42. for cls in Model.components_class:
  43. if cls.__name__ == class_name:
  44. return cls
  45. return False
  46. @staticmethod
  47. ## Given a python class return a name
  48. # @param cls : The python class we want the name
  49. # @return A class name as string or False if cls is not an EmComponent child class
  50. # @todo réécrire le split, c'est pas bô
  51. def name_from_emclass(em_class):
  52. if em_class not in Model.components_class:
  53. spl = em_class.__module__.split('.')
  54. if spl[1] == 'fieldtypes':
  55. return 'EmField'
  56. return False
  57. return em_class.__name__
  58. ## Loads the structure of the Editorial Model
  59. #
  60. # Gets all the objects contained in that structure and creates a dict indexed by their uids
  61. # @todo Change the thrown exception when a components check fails
  62. # @throw ValueError When a component class don't exists
  63. def load(self):
  64. datas = self.backend.load()
  65. for uid, kwargs in datas.items():
  66. #Store and delete the EmComponent class name from datas
  67. cls_name = kwargs['component']
  68. del kwargs['component']
  69. if cls_name == 'EmField':
  70. #Special EmField process because of fieldtypes
  71. if not 'fieldtype' in kwargs:
  72. raise AttributeError("Missing 'fieldtype' from EmField instanciation")
  73. cls = EditorialModel.fields.EmField.get_field_class(kwargs['fieldtype'])
  74. else:
  75. cls = self.emclass_from_name(cls_name)
  76. if cls:
  77. kwargs['uid'] = uid
  78. # create a dict for the component and one indexed by uids, store instanciated component in it
  79. self._components['uids'][uid] = cls(model=self, **kwargs)
  80. self._components[cls_name].append(self._components['uids'][uid])
  81. else:
  82. raise ValueError("Unknow EmComponent class : '" + cls_name + "'")
  83. #Sorting by rank
  84. for component_class in Model.components_class:
  85. self.sort_components(component_class)
  86. #Check integrity
  87. for uid, component in self._components['uids'].items():
  88. try:
  89. component.check()
  90. except EmComponentCheckError as exception_object:
  91. raise EmComponentCheckError("The component with uid %d is not valid. Check returns the following error : \"%s\"" % (uid, str(exception_object)))
  92. #Everything is done. Indicating that the component initialisation is over
  93. component.init_ended()
  94. ## Saves data using the current backend
  95. # @param filename str | None : if None use the current backend file (provided at backend instanciation)
  96. def save(self, filename = None):
  97. return self.backend.save(self, filename)
  98. ## Given a EmComponent child class return a list of instances
  99. # @param cls EmComponent : A python class
  100. # @return a list of instances or False if the class is not an EmComponent child
  101. def components(self, cls=None):
  102. if cls is None:
  103. return [ self.component(uid) for uid in self._components['uids'] ]
  104. key_name = self.name_from_emclass(cls)
  105. return False if key_name is False else self._components[key_name]
  106. ## Return an EmComponent given an uid
  107. # @param uid int : An EmComponent uid
  108. # @return The corresponding instance or False if uid don't exists
  109. def component(self, uid):
  110. return False if uid not in self._components['uids'] else self._components['uids'][uid]
  111. ## Sort components by rank in Model::_components
  112. # @param emclass pythonClass : The type of components to sort
  113. # @throw AttributeError if emclass is not valid
  114. # @warning disabled the test on component_class because of EmField new way of working
  115. def sort_components(self, component_class):
  116. #if component_class not in self.components_class:
  117. # raise AttributeError("Bad argument emclass : '" + str(component_class) + "', excpeting one of " + str(self.components_class))
  118. self._components[self.name_from_emclass(component_class)] = sorted(self.components(component_class), key=lambda comp: comp.rank)
  119. ## Return a new uid
  120. # @return a new uid
  121. def new_uid(self):
  122. used_uid = [int(uid) for uid in self._components['uids'].keys()]
  123. return sorted(used_uid)[-1] + 1 if len(used_uid) > 0 else 1
  124. ## Create a component from a component type and datas
  125. #
  126. # @note if datas does not contains a rank the new component will be added last
  127. # @note datas['rank'] can be an integer or two specials strings 'last' or 'first'
  128. # @param component_type str : a component type ( component_class, component_fieldgroup, component_field or component_type )
  129. # @param datas dict : the options needed by the component creation
  130. # @throw ValueError if datas['rank'] is not valid (too big or too small, not an integer nor 'last' or 'first' )
  131. # @todo Handle a raise from the migration handler
  132. # @todo Transform the datas arg in **datas ?
  133. def create_component(self, component_type, datas, uid=None):
  134. if component_type == 'EmField':
  135. #special process for EmField
  136. if not 'fieldtype' in datas:
  137. raise AttributeError("Missing 'fieldtype' from EmField instanciation")
  138. em_obj = EditorialModel.fields.EmField.get_field_class(datas['fieldtype'])
  139. else:
  140. em_obj = self.emclass_from_name(component_type)
  141. rank = 'last'
  142. if 'rank' in datas:
  143. rank = datas['rank']
  144. del datas['rank']
  145. datas['uid'] = uid if uid else self.new_uid()
  146. em_component = em_obj(model=self, **datas)
  147. em_component.rank = em_component.get_max_rank() + 1 # Inserting last by default
  148. self._components['uids'][em_component.uid] = em_component
  149. self._components[component_type].append(em_component)
  150. if rank != 'last':
  151. em_component.set_rank(1 if rank == 'first' else rank)
  152. #everything done, indicating that initialisation is over
  153. em_component.init_ended()
  154. #register the creation in migration handler
  155. try:
  156. self.migration_handler.register_change(self, em_component.uid, None, em_component.attr_dump())
  157. except MigrationHandlerChangeError as exception_object:
  158. #Revert the creation
  159. self.components(em_component.__class__).remove(em_component)
  160. del self._components['uids'][em_component.uid]
  161. raise exception_object
  162. self.migration_handler.register_model_state(self, hash(self))
  163. return em_component
  164. ## Delete a component
  165. # @param uid int : Component identifier
  166. # @throw EmComponentNotExistError
  167. # @todo unable uid check
  168. # @todo Handle a raise from the migration handler
  169. def delete_component(self, uid):
  170. em_component = self.component(uid)
  171. if not em_component:
  172. raise EmComponentNotExistError()
  173. if em_component.delete_check():
  174. #register the deletion in migration handler
  175. self.migration_handler.register_change(self, uid, self.component(uid).attr_dump(), None)
  176. # delete internal lists
  177. self._components[self.name_from_emclass(em_component.__class__)].remove(em_component)
  178. del self._components['uids'][uid]
  179. #Register the new EM state
  180. self.migration_handler.register_model_state(self, hash(self))
  181. return True
  182. return False
  183. ## Changes the current backend
  184. #
  185. # @param backend unknown: A backend object
  186. def set_backend(self, backend):
  187. self.backend = backend
  188. ## Returns a list of all the EmClass objects of the model
  189. def classes(self):
  190. return list(self._components[self.name_from_emclass(EmClass)])
  191. ## Use a new migration handler, re-apply all the ME to this handler
  192. #
  193. # @param new_mh MigrationHandler: A migration_handler object
  194. # @warning : if a relational-attribute field (with 'rel_field_id') comes before it's relational field (with 'rel_to_type_id'), this will blow up
  195. def migrate_handler(self, new_mh):
  196. new_me = Model(EmBackendDummy(), new_mh)
  197. relations = {'fields_list': [], 'superiors_list': []}
  198. # re-create component one by one, in components_class[] order
  199. for cls in self.components_class:
  200. for component in self.components(cls):
  201. component_type = self.name_from_emclass(cls)
  202. component_dump = component.attr_dump()
  203. # Save relations between component to apply them later
  204. for relation in relations.keys():
  205. if relation in component_dump and component_dump[relation]:
  206. relations[relation].append((component.uid, component_dump[relation]))
  207. del component_dump[relation]
  208. new_me.create_component(component_type, component_dump, component.uid)
  209. # apply selected field to types
  210. for fields_list in relations['fields_list']:
  211. uid, fields = fields_list
  212. for field_id in fields:
  213. new_me.component(uid).select_field(new_me.component(field_id))
  214. # add superiors to types
  215. for superiors_list in relations['superiors_list']:
  216. uid, sup_list = superiors_list
  217. for nature, superiors_uid in sup_list.items():
  218. for superior_uid in superiors_uid:
  219. new_me.component(uid).add_superior(new_me.component(superior_uid), nature)
  220. del new_me
  221. self.migration_handler = new_mh
  222. @classmethod
  223. ## @brief Generate a random editorial model
  224. #
  225. # The random generator can be tuned with integer parameters
  226. # that represent probability or maximum numbers of items.
  227. # The probability (chances) works like 1/x chances to append
  228. # with x the tunable parameter
  229. # Tunable generator parameters :
  230. # - classtype : Chances for a classtype to be empty (default 0)
  231. # - nclass : Maximum number of classes per classtypes (default 5)
  232. # - nofg : Chances for a classe to have no fieldgroup associated to it (default 10)
  233. # - notype : Chances for a classe to have no type associated to it (default 5)
  234. # - seltype : Chances for a type to select an optionnal field (default 2)
  235. # - ntypesuperiors : Chances for a type to link with a superiors (default 3)
  236. # - nofields : Chances for a fieldgroup to be empty (default 10)
  237. # - nfields : Maximum number of field per fieldgroups (default 8)
  238. # - rfields : Maximum number of relation_to_type attributes fields (default 5)
  239. # - optfield : Chances for a field to be optionnal (default 2)
  240. # @param backend : A backend to use with the new EM
  241. # @param **kwargs dict : Provide tunable generation parameter
  242. # @return A randomly generate EM
  243. def random(cls, backend, **kwargs):
  244. em = Model(backend)
  245. chances = {
  246. 'classtype' : 0, # a class in classtype
  247. 'nclass': 5, #max number of classes per classtype
  248. 'nofg': 10, #no fieldgroup in a class
  249. 'nfg': 5, #max number of fieldgroups per classes
  250. 'notype': 5, # no types in a class
  251. 'ntype': 3, # max number of types in a class
  252. 'seltype': 2, #chances to select an optional field
  253. 'ntypesuperiors': 3, #chances to link with a superior
  254. 'nofields': 10, # no fields in a fieldgroup
  255. 'nfields' : 8, #max number of fields per fieldgroups
  256. 'rfields': 5,#max number of attributes relation fields
  257. 'optfield': 2, #chances to be optionnal
  258. }
  259. for name,value in kwargs.items():
  260. if name not in chances:
  261. #warning
  262. pass
  263. else:
  264. chances[name] = value
  265. #classes creation
  266. for classtype in EmClassType.getall():
  267. if random.randint(0,chances['classtype']) == 0:
  268. for _ in range(random.randint(1,chances['nclass'])):
  269. cdats = cls._rnd_component_datas()
  270. cdats['classtype'] = classtype['name']
  271. em.create_component('EmClass', cdats)
  272. for emclass in em.classes():
  273. #fieldgroups creation
  274. if random.randint(0, chances['nofg']) != 0:
  275. for _ in range(random.randint(1, chances['nfg'])):
  276. fgdats = cls._rnd_component_datas()
  277. fgdats['class_id'] = emclass.uid
  278. em.create_component('EmFieldGroup', fgdats)
  279. #types creation
  280. if random.randint(0, chances['notype']) != 0:
  281. for _ in range(random.randint(1, chances['ntype'])):
  282. tdats = cls._rnd_component_datas()
  283. tdats['class_id'] = emclass.uid
  284. em.create_component('EmType', tdats)
  285. #random type hierarchy
  286. for emtype in em.components(EmType):
  287. possible = emtype.possible_superiors()
  288. for nat in possible:
  289. while random.randint(0, chances['ntypesuperiors']) == 0 and len(possible[nat]) > 0:
  290. i = random.randint(0,len(possible[nat])-1)
  291. emtype.add_superior(possible[nat][i], nat)
  292. #fields creation
  293. ft_l = EmField.fieldtypes_list()
  294. for emfg in em.components(EmFieldGroup):
  295. if random.randint(0, chances['nofields']) != 0:
  296. for _ in range(random.randint(1, chances['nfields'])):
  297. ft = ft_l[random.randint(0,len(ft_l)-1)]
  298. fdats = cls._rnd_component_datas()
  299. fdats['fieldtype']=ft
  300. fdats['fieldgroup_id'] = emfg.uid
  301. if ft == 'rel2type':
  302. emtypes = em.components(EmType)
  303. fdats['rel_to_type_id'] = emtypes[random.randint(0,len(emtypes)-1)].uid
  304. if random.randint(0,chances['optfield']) == 0:
  305. fdats['optional'] = True
  306. em.create_component('EmField', fdats)
  307. #relationnal fiels creation
  308. ft_l = [ ft for ft in EmField.fieldtypes_list() if ft != 'rel2type' ]
  309. for emrelf in [ f for f in em.components(EmField) if f.ftype == 'rel2type' ]:
  310. for _ in range(0,chances['rfields']):
  311. ft = ft_l[random.randint(0, len(ft_l)-1)]
  312. fdats = cls._rnd_component_datas()
  313. fdats['fieldtype'] = ft
  314. fdats['fieldgroup_id'] = emrelf.fieldgroup_id
  315. if random.randint(0, chances['optfield']) == 0:
  316. fdats['optional'] = True
  317. em.create_component('EmField', fdats)
  318. #selection optionnal fields
  319. for emtype in em.components(EmType):
  320. selectable = [field for fieldgroup in emtype.fieldgroups() for field in fieldgroup.fields() if field.optional ]
  321. for field in selectable:
  322. if random.randint(0,chances['seltype']) == 0:
  323. emtype.select_field(field)
  324. return em
  325. @staticmethod
  326. ## @brief Generate a random string
  327. # @warning dirty cache trick with globals()
  328. # @return a randomly selected string
  329. def _rnd_str(words_src='/usr/share/dict/words'):
  330. if '_words' not in globals() or globals()['_words_fname'] != words_src:
  331. globals()['_words_fname'] = words_src
  332. with open(words_src, 'r') as fpw:
  333. globals()['_words'] = [ l for l in fpw ]
  334. words = globals()['_words']
  335. return words[random.randint(0,len(words)-1)]
  336. @classmethod
  337. ## @brief Generate a random MlString
  338. # @param nlng : Number of langs in the MlString
  339. # @return a random MlString with nlng translations
  340. # @todo use a dict to generated langages
  341. def _rnd_mlstr(cls, nlng):
  342. ret = MlString()
  343. for _ in range(nlng):
  344. ret.set(cls._rnd_str(), cls._rnd_str())
  345. return ret
  346. @classmethod
  347. ## @brief returns randomly generated datas for an EmComponent
  348. # @return a dict with name, string and help_text
  349. def _rnd_component_datas(cls):
  350. mlstr_nlang = 2;
  351. ret = dict()
  352. ret['name'] = cls._rnd_str()
  353. ret['string'] = cls._rnd_mlstr(mlstr_nlang)
  354. ret['help_text'] = cls._rnd_mlstr(mlstr_nlang)
  355. return ret