暫無描述
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

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