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.

components.py 9.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. # -*- coding: utf-8 -*-
  2. ## @package EditorialModel.components
  3. # @brief Base objects for all EditorialModel components
  4. #
  5. # Defines the EditorialModel::components::EmComponent class
  6. import datetime
  7. import hashlib
  8. import EditorialModel
  9. from Lodel.utils.mlstring import MlString
  10. ## This class is the mother class of all editorial model objects
  11. #
  12. # It gather all the properties and mechanism that are common to every editorial model objects
  13. # @see EditorialModel::classes::EmClass, EditorialModel::types::EmType, EditorialModel::fieldgroups::EmFieldGroup, EditorialModel::fields::EmField
  14. # @pure
  15. class EmComponent(object):
  16. ## Used by EmComponent::modify_rank
  17. ranked_in = None
  18. def __init__(self, model, uid, name, string=None, help_text=None, date_update=None, date_create=None, rank=None):
  19. if type(self) == EmComponent:
  20. raise NotImplementedError('Abstract class')
  21. if model.__class__.__name__ != 'Model':
  22. raise TypeError("Excepted type for 'model' arg is <class 'Model'> but got {} instead".format(type(model)))
  23. self.model = model
  24. self.uid = uid
  25. self.check_type('uid', int)
  26. self.name = name
  27. self.check_type('name', str)
  28. self.string = MlString() if string is None else string
  29. self.check_type('string', MlString)
  30. self.help_text = MlString() if help_text is None else help_text
  31. self.check_type('help_text', MlString)
  32. self.date_update = datetime.datetime.now() if date_update is None else date_update # WARNING timezone !
  33. self.check_type('date_update', datetime.datetime)
  34. self.date_create = datetime.datetime.now() if date_create is None else date_create # WARNING timezone !
  35. self.check_type('date_create', datetime.datetime)
  36. self._inited = False
  37. #Handling specials ranks for component creation
  38. self.rank = rank
  39. ## @brief Return a dict with attributes name as key and attributes value as value
  40. # @note Used at creation and deletion to call the migration handler
  41. def attr_dump(self):
  42. return {fname: fval for fname, fval in self.__dict__.items() if not (fname.startswith('_') or (fname == 'uid') or (fname == 'model'))}
  43. ## @brief Return a dict with attributes name as key and attributes value flattened
  44. def attr_flat(self):
  45. attributes_dump = self.attr_dump()
  46. for attr_name in list(attributes_dump.keys()):
  47. if isinstance(attributes_dump[attr_name], EmComponent):
  48. attributes_dump[attr_name] = attributes_dump[attr_name].uid
  49. elif isinstance(attributes_dump[attr_name], MlString):
  50. attributes_dump[attr_name] = attributes_dump[attr_name].__str__()
  51. attributes_dump['component'] = 'EmField' if isinstance(self, EditorialModel.fields.EmField) else self.__class__.__name__
  52. return attributes_dump
  53. @property
  54. ## @brief Provide a uniq name
  55. #
  56. # Identify a component with his type and name
  57. def uniq_name(self):
  58. uname = self.__class__.__name__
  59. if not isinstance(self, EditorialModel.fields.EmField): # WARNING this could crash with fieldtypes
  60. try:
  61. uname += '_' + self.em_class.name # TODO Ajouter la propriété
  62. except AttributeError:
  63. pass
  64. uname += '_' + self.name
  65. return uname
  66. ## @brief This function has to be called after the instanciation, checks, and init manipulations are done
  67. # @note Create a new attribute _inited that allow __setattr__ to know if it has or not to call the migration handler
  68. def init_ended(self):
  69. self._inited = True
  70. ## @brief Reimplementation for calling the migration handler to register the change
  71. def __setattr__(self, attr_name, value):
  72. inited = '_inited' in self.__dict__ and self.__dict__['_inited']
  73. if inited:
  74. # if fails raise MigrationHandlerChangeError
  75. self.model.migration_handler.register_change(self.model, self.uid, {attr_name: getattr(self, attr_name)}, {attr_name: value})
  76. super(EmComponent, self).__setattr__(attr_name, value)
  77. if inited:
  78. self.model.migration_handler.register_model_state(self.model, hash(self.model))
  79. ## Check the type of attribute named var_name
  80. # @param var_name str : the attribute name
  81. # @param excepted_type tuple|type : Tuple of type or a type
  82. # @throw AttributeError if wrong type detected
  83. def check_type(self, var_name, excepted_type):
  84. var = getattr(self, var_name)
  85. if not isinstance(var, excepted_type):
  86. raise AttributeError("Excepted %s to be an %s but got %s instead" % (var_name, str(excepted_type), str(type(var))))
  87. ## @brief Hash function that allows to compare two EmComponent
  88. # @return EmComponent+ClassName+uid
  89. def __hash__(self):
  90. # flatten list of attributes of the component to an ordered list
  91. # so every time we have the same string representation
  92. attributes_flat = self.attr_flat()
  93. ordered_attributes = sorted(list(attributes_flat.keys()))
  94. component_dump = []
  95. for attr_name in ordered_attributes:
  96. if isinstance(attributes_flat[attr_name], datetime.datetime): # drop date values
  97. continue
  98. component_dump.append((attr_name, attributes_flat[attr_name]))
  99. return int(hashlib.md5(str(component_dump).encode('utf-8')).hexdigest(), 16)
  100. ## @brief Test if two EmComponent are "equals"
  101. # @return True or False
  102. def __eq__(self, other):
  103. return hash(self) == hash(other)
  104. ## Check if the EmComponent is valid
  105. # This function has to check that rank are correct and continuous other checks are made in childs classes
  106. # @warning Hardcoded minimum rank
  107. # @warning Rank modified by _fields['rank'].value
  108. # @throw EmComponentCheckError if fails
  109. def check(self):
  110. self.model.sort_components(self.__class__)
  111. if self.get_max_rank() != len(self.same_rank_group()) or self.rank <= 0:
  112. #Non continuous ranks
  113. for i, component in enumerate(self.same_rank_group()):
  114. component.rank = i + 1
  115. # No need to sort again here
  116. ## @brief Delete predicate. Indicates if a component can be deleted
  117. # @return True if deletion OK else return False
  118. def delete_check(self):
  119. raise NotImplementedError("Virtual method")
  120. ## @brief Get the maximum rank given an EmComponent child class and a ranked_in filter
  121. # @return The max rank is the rank group or -1 if no components in that group
  122. def get_max_rank(self):
  123. same_rgroup = self.same_rank_group()
  124. return max([comp.rank for comp in same_rgroup]) if len(same_rgroup) > 0 else -1
  125. ## Return an array of instances that are concerned by the same rank
  126. # @return An array of instances that are concerned by the same rank
  127. def same_rank_group(self):
  128. components = self.model.components(self.__class__)
  129. ranked_in = self.__class__.ranked_in
  130. return [c for c in components if getattr(c, ranked_in) == getattr(self, ranked_in)]
  131. ## Set a new rank for this component
  132. # @note This function assume that ranks are properly set from 1 to x with no gap
  133. #
  134. # @warning Hardcoded minimum rank
  135. # @warning Rank modified by _fields['rank'].value
  136. #
  137. # @param new_rank int: The new rank
  138. #
  139. # @throw TypeError If bad argument type
  140. # @throw ValueError if out of bound value
  141. def set_rank(self, new_rank):
  142. if not isinstance(new_rank, int):
  143. raise TypeError("Excepted <class int> but got " + str(type(new_rank)))
  144. if new_rank <= 0 or (new_rank > 1 and new_rank > self.get_max_rank()):
  145. raise ValueError("Invalid new rank : " + str(new_rank))
  146. mod = new_rank - self.rank # Indicates the "direction" of the "move"
  147. if mod == 0:
  148. return True
  149. limits = [self.rank + (1 if mod > 0 else -1), new_rank] # The range of modified ranks
  150. limits.sort()
  151. for component in [c for c in self.same_rank_group() if c.rank >= limits[0] and c.rank <= limits[1]]:
  152. component.rank = component.rank + (-1 if mod > 0 else 1)
  153. self.rank = new_rank
  154. self.model.sort_components(self.__class__)
  155. ## Modify a rank given an integer modifier
  156. # @note this method always tries to make the modification : if modifier is too big put
  157. # the component in last position, if modifier is to small put the component
  158. # in first position
  159. # @param rank_mod int : can be a negative positive or zero integer
  160. # @return True if the modification was made as wanted else return false
  161. # @throw TypeError if rank_mod is not an integer
  162. def modify_rank(self, rank_mod):
  163. if not isinstance(rank_mod, int):
  164. raise TypeError("Excepted <class int>. But got %s" % str(type(rank_mod)))
  165. ret = True
  166. new_rank = self.rank + rank_mod
  167. if new_rank < 1:
  168. ret = False
  169. new_rank = 1
  170. elif new_rank > self.get_max_rank():
  171. ret = False
  172. new_rank = self.get_max_rank()
  173. self.set_rank(new_rank)
  174. return ret
  175. ## @brief Return a string representation of the component
  176. # @return A string representation of the component
  177. def __repr__(self):
  178. if self.name is None:
  179. return "<%s #%s, 'non populated'>" % (type(self).__name__, self.uid)
  180. else:
  181. return "<%s #%s, '%s'>" % (type(self).__name__, self.uid, self.name)