gooderp18绿色标准版
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.

640 lines
21KB

  1. ##########################################################################
  2. #
  3. # pgAdmin 4 - PostgreSQL Tools
  4. #
  5. # Copyright (C) 2013 - 2020, The pgAdmin Development Team
  6. # This software is released under the PostgreSQL Licence
  7. #
  8. ##########################################################################
  9. """
  10. Utility classes to register, getter, setter functions for the preferences of a
  11. module within the system.
  12. """
  13. import decimal
  14. import simplejson as json
  15. import dateutil.parser as dateutil_parser
  16. from flask import current_app
  17. from flask_babelex import gettext
  18. from flask_security import current_user
  19. from pgadmin.model import db, Preferences as PrefTable, \
  20. ModulePreference as ModulePrefTable, UserPreference as UserPrefTable, \
  21. PreferenceCategory as PrefCategoryTbl
  22. class _Preference(object):
  23. """
  24. Internal class representing module, and categoy bound preference.
  25. """
  26. def __init__(
  27. self, cid, name, label, _type, default, **kwargs
  28. ):
  29. """
  30. __init__
  31. Constructor/Initializer for the internal _Preference object.
  32. It creates a new entry for this preference in configuration table based
  33. on the name (if not exists), and keep the id of it for on demand value
  34. fetching from the configuration table in later stage. Also, keeps track
  35. of type of the preference/option, and other supporting parameters like
  36. min, max, options, etc.
  37. :param cid: configuration id
  38. :param name: Name of the preference (must be unique for each
  39. configuration)
  40. :param label: Display name of the options/preference
  41. :param _type: Type for proper validation on value
  42. :param default: Default value
  43. :param help_str: Help string to be shown in preferences dialog.
  44. :param min_val: minimum value
  45. :param max_val: maximum value
  46. :param options: options (Array of list objects)
  47. :param select2: select2 options (object)
  48. :param fields: field schema (if preference has more than one field to
  49. take input from user e.g. keyboardshortcut preference)
  50. :param allow_blanks: Flag specify whether to allow blank value.
  51. :returns: nothing
  52. """
  53. self.cid = cid
  54. self.name = name
  55. self.default = default
  56. self.label = label
  57. self._type = _type
  58. self.help_str = kwargs.get('help_str', None)
  59. self.min_val = kwargs.get('min_val', None)
  60. self.max_val = kwargs.get('max_val', None)
  61. self.options = kwargs.get('options', None)
  62. self.select2 = kwargs.get('select2', None)
  63. self.fields = kwargs.get('fields', None)
  64. self.allow_blanks = kwargs.get('allow_blanks', None)
  65. # Look into the configuration table to find out the id of the specific
  66. # preference.
  67. res = PrefTable.query.filter_by(
  68. name=name, cid=cid
  69. ).first()
  70. if res is None:
  71. # Could not find in the configuration table, we will create new
  72. # entry for it.
  73. res = PrefTable(name=self.name, cid=cid)
  74. db.session.add(res)
  75. db.session.commit()
  76. res = PrefTable.query.filter_by(
  77. name=name
  78. ).first()
  79. # Save this id for letter use.
  80. self.pid = res.id
  81. def get(self):
  82. """
  83. get
  84. Fetch the value from the server for the current user from the
  85. configuration table (if available), otherwise returns the default value
  86. for it.
  87. :returns: value for this preference.
  88. """
  89. res = UserPrefTable.query.filter_by(
  90. pid=self.pid
  91. ).filter_by(uid=current_user.id).first()
  92. # Could not find any preference for this user, return default value.
  93. if res is None:
  94. return self.default
  95. # The data stored in the configuration will be in string format, we
  96. # need to convert them in proper format.
  97. if self._type == 'boolean' or self._type == 'switch' or \
  98. self._type == 'node':
  99. return res.value == 'True'
  100. if self._type == 'integer':
  101. try:
  102. return int(res.value)
  103. except Exception as e:
  104. current_app.logger.exception(e)
  105. return self.default
  106. if self._type == 'numeric':
  107. try:
  108. return decimal.Decimal(res.value)
  109. except Exception as e:
  110. current_app.logger.exception(e)
  111. return self.default
  112. if self._type == 'date' or self._type == 'datetime':
  113. try:
  114. return dateutil_parser.parse(res.value)
  115. except Exception as e:
  116. current_app.logger.exception(e)
  117. return self.default
  118. if self._type == 'options':
  119. for opt in self.options:
  120. if 'value' in opt and opt['value'] == res.value:
  121. return res.value
  122. if self.select2 and self.select2['tags']:
  123. return res.value
  124. return self.default
  125. if self._type == 'text' and res.value == '' and \
  126. (self.allow_blanks is None or not self.allow_blanks):
  127. return self.default
  128. if self._type == 'keyboardshortcut':
  129. try:
  130. return json.loads(res.value)
  131. except Exception as e:
  132. current_app.logger.exception(e)
  133. return self.default
  134. return res.value
  135. def set(self, value):
  136. """
  137. set
  138. Set the value into the configuration table for this current user.
  139. :param value: Value to be set
  140. :returns: nothing.
  141. """
  142. # We can't store the values in the given format, we need to convert
  143. # them in string first. We also need to validate the value type.
  144. if self._type == 'boolean' or self._type == 'switch' or \
  145. self._type == 'node':
  146. if type(value) != bool:
  147. return False, gettext("Invalid value for a boolean option.")
  148. elif self._type == 'integer':
  149. value = int(value)
  150. if self.min_val is not None and value < self.min_val:
  151. value = self.min_val
  152. if self.max_val is not None and value > self.max_val:
  153. value = self.max_val
  154. if type(value) != int:
  155. return False, gettext("Invalid value for an integer option.")
  156. elif self._type == 'numeric':
  157. value = float(value)
  158. if self.min_val is not None and value < self.min_val:
  159. value = self.min_val
  160. if self.max_val is not None and value > self.max_val:
  161. value = self.max_val
  162. t = type(value)
  163. if t != float and t != int and t != decimal.Decimal:
  164. return False, gettext("Invalid value for a numeric option.")
  165. elif self._type == 'date':
  166. try:
  167. value = dateutil_parser.parse(value).date()
  168. except Exception as e:
  169. current_app.logger.exception(e)
  170. return False, gettext("Invalid value for a date option.")
  171. elif self._type == 'datetime':
  172. try:
  173. value = dateutil_parser.parse(value)
  174. except Exception as e:
  175. current_app.logger.exception(e)
  176. return False, gettext("Invalid value for a datetime option.")
  177. elif self._type == 'options':
  178. has_value = False
  179. for opt in self.options:
  180. if 'value' in opt and opt['value'] == value:
  181. has_value = True
  182. if not has_value and self.select2 and not self.select2['tags']:
  183. return False, gettext("Invalid value for an options option.")
  184. elif self._type == 'keyboardshortcut':
  185. try:
  186. value = json.dumps(value)
  187. except Exception as e:
  188. current_app.logger.exception(e)
  189. return False, gettext(
  190. "Invalid value for a keyboard shortcut option."
  191. )
  192. pref = UserPrefTable.query.filter_by(
  193. pid=self.pid
  194. ).filter_by(uid=current_user.id).first()
  195. value = u"{}".format(value)
  196. if pref is None:
  197. pref = UserPrefTable(
  198. uid=current_user.id, pid=self.pid, value=value
  199. )
  200. db.session.add(pref)
  201. else:
  202. pref.value = value
  203. db.session.commit()
  204. return True, None
  205. def to_json(self):
  206. """
  207. to_json
  208. Returns the JSON object representing this preferences.
  209. :returns: the JSON representation for this preferences
  210. """
  211. res = {
  212. 'id': self.pid,
  213. 'cid': self.cid,
  214. 'name': self.name,
  215. 'label': self.label or self.name,
  216. 'type': self._type,
  217. 'help_str': self.help_str,
  218. 'min_val': self.min_val,
  219. 'max_val': self.max_val,
  220. 'options': self.options,
  221. 'select2': self.select2,
  222. 'value': self.get(),
  223. 'fields': self.fields,
  224. }
  225. return res
  226. class Preferences(object):
  227. """
  228. class Preferences
  229. It helps to manage all the preferences/options related to a specific
  230. module.
  231. It keeps track of all the preferences registered with it using this class
  232. in the group of categories.
  233. Also, create the required entries for each module, and categories in the
  234. preferences tables (if required). If it is already present, it will refer
  235. to the existing data from those tables.
  236. class variables:
  237. ---------------
  238. modules:
  239. Dictionary of all the modules, can be refered by its name.
  240. Keeps track of all the modules in it, so that - only one object per module
  241. gets created. If the same module refered by different object, the
  242. categories dictionary within it will be shared between them to keep the
  243. consistent data among all the object.
  244. Instance Definitions:
  245. -------- -----------
  246. """
  247. modules = dict()
  248. def __init__(self, name, label=None):
  249. """
  250. __init__
  251. Constructor/Initializer for the Preferences class.
  252. :param name: Name of the module
  253. :param label: Display name of the module, it will be displayed in the
  254. preferences dialog.
  255. :returns nothing
  256. """
  257. self.name = name
  258. self.label = label
  259. self.categories = dict()
  260. # Find the entry for this module in the configuration database.
  261. module = ModulePrefTable.query.filter_by(name=name).first()
  262. # Can't find the reference for it in the configuration database,
  263. # create on for it.
  264. if module is None:
  265. module = ModulePrefTable(name=name)
  266. db.session.add(module)
  267. db.session.commit()
  268. module = ModulePrefTable.query.filter_by(name=name).first()
  269. self.mid = module.id
  270. if name in Preferences.modules:
  271. m = Preferences.modules[name]
  272. self.categories = m.categories
  273. else:
  274. Preferences.modules[name] = self
  275. def to_json(self):
  276. """
  277. to_json
  278. Converts the preference object to the JSON Format.
  279. :returns: a JSON object contains information.
  280. """
  281. res = {
  282. 'id': self.mid,
  283. 'label': self.label or self.name,
  284. 'name': self.name,
  285. 'categories': []
  286. }
  287. for c in self.categories:
  288. cat = self.categories[c]
  289. interm = {
  290. 'id': cat['id'],
  291. 'label': cat['label'] or cat['name'],
  292. 'preferences': []
  293. }
  294. res['categories'].append(interm)
  295. for p in cat['preferences']:
  296. pref = (cat['preferences'][p]).to_json().copy()
  297. pref.update({'mid': self.mid, 'cid': cat['id']})
  298. interm['preferences'].append(pref)
  299. return res
  300. def __category(self, name, label):
  301. """
  302. __category
  303. A private method to create/refer category for/of this module.
  304. :param name: Name of the category
  305. :param label: Display name of the category, it will be send to
  306. client/front end to list down in the preferences/options
  307. dialog.
  308. :returns: A dictionary object reprenting this category.
  309. """
  310. if name in self.categories:
  311. res = self.categories[name]
  312. # Update the category label (if not yet defined)
  313. res['label'] = res['label'] or label
  314. return res
  315. cat = PrefCategoryTbl.query.filter_by(
  316. mid=self.mid
  317. ).filter_by(name=name).first()
  318. if cat is None:
  319. cat = PrefCategoryTbl(name=name, mid=self.mid)
  320. db.session.add(cat)
  321. db.session.commit()
  322. cat = PrefCategoryTbl.query.filter_by(
  323. mid=self.mid
  324. ).filter_by(name=name).first()
  325. self.categories[name] = res = {
  326. 'id': cat.id,
  327. 'name': name,
  328. 'label': label,
  329. 'preferences': dict()
  330. }
  331. return res
  332. def register(
  333. self, category, name, label, _type, default, **kwargs
  334. ):
  335. """
  336. register
  337. Register/Refer the particular preference in this module.
  338. :param category: name of the category, in which this preference/option
  339. will be displayed.
  340. :param name: name of the preference/option
  341. :param label: Display name of the preference
  342. :param _type: [optional] Type of the options.
  343. It is an optional argument, only if this
  344. option/preference is registered earlier.
  345. :param default: [optional] Default value of the options
  346. It is an optional argument, only if this
  347. option/preference is registered earlier.
  348. :param min_val:
  349. :param max_val:
  350. :param options:
  351. :param help_str:
  352. :param category_label:
  353. :param select2: select2 control extra options
  354. :param fields: field schema (if preference has more than one field to
  355. take input from user e.g. keyboardshortcut preference)
  356. :param allow_blanks: Flag specify whether to allow blank value.
  357. """
  358. min_val = kwargs.get('min_val', None)
  359. max_val = kwargs.get('max_val', None)
  360. options = kwargs.get('options', None)
  361. help_str = kwargs.get('help_str', None)
  362. category_label = kwargs.get('category_label', None)
  363. select2 = kwargs.get('select2', None)
  364. fields = kwargs.get('fields', None)
  365. allow_blanks = kwargs.get('allow_blanks', None)
  366. cat = self.__category(category, category_label)
  367. if name in cat['preferences']:
  368. return (cat['preferences'])[name]
  369. assert label is not None, "Label for a preference cannot be none!"
  370. assert _type is not None, "Type for a preference cannot be none!"
  371. assert _type in (
  372. 'boolean', 'integer', 'numeric', 'date', 'datetime',
  373. 'options', 'multiline', 'switch', 'node', 'text', 'radioModern',
  374. 'keyboardshortcut'
  375. ), "Type cannot be found in the defined list!"
  376. (cat['preferences'])[name] = res = _Preference(
  377. cat['id'], name, label, _type, default, help_str=help_str,
  378. min_val=min_val, max_val=max_val, options=options,
  379. select2=select2, fields=fields, allow_blanks=allow_blanks
  380. )
  381. return res
  382. def preference(self, name):
  383. """
  384. preference
  385. Refer the particular preference in this module.
  386. :param name: name of the preference/option
  387. """
  388. for key in self.categories:
  389. cat = self.categories[key]
  390. if name in cat['preferences']:
  391. return (cat['preferences'])[name]
  392. return None
  393. @classmethod
  394. def preferences(cls):
  395. """
  396. preferences
  397. Convert all the module preferences in the JSON format.
  398. :returns: a list of the preferences for each of the modules.
  399. """
  400. res = []
  401. for m in Preferences.modules:
  402. res.append(Preferences.modules[m].to_json())
  403. return res
  404. @classmethod
  405. def register_preference(
  406. cls, module, category, name, label, _type, default, **kwargs
  407. ):
  408. """
  409. register
  410. Register/Refer a preference in the system for any module.
  411. :param module: Name of the module
  412. :param category: Name of category
  413. :param name: Name of the option
  414. :param label: Label of the option, shown in the preferences dialog.
  415. :param _type: Type of the option.
  416. Allowed type of options are as below:
  417. boolean, integer, numeric, date, datetime,
  418. options, multiline, switch, node
  419. :param default: Default value for the preference/option
  420. :param min_val: Minimum value for integer, and numeric type
  421. :param max_val: Maximum value for integer, and numeric type
  422. :param options: Allowed list of options for 'option' type
  423. :param help_str: Help string show for that preference/option.
  424. :param module_label: Label for the module
  425. :param category_label: Label for the category
  426. """
  427. min_val = kwargs.get('min_val', None)
  428. max_val = kwargs.get('max_val', None)
  429. options = kwargs.get('options', None)
  430. help_str = kwargs.get('help_str', None)
  431. module_label = kwargs.get('module_label', None)
  432. category_label = kwargs.get('category_label', None)
  433. m = None
  434. if module in Preferences.modules:
  435. m = Preferences.modules[module]
  436. # Update the label (if not defined yet)
  437. m.label = m.label or module_label
  438. else:
  439. m = Preferences(module, module_label)
  440. return m.register(
  441. category, name, label, _type, default, min_val=min_val,
  442. max_val=max_val, options=options, help_str=help_str,
  443. category_label=category_label
  444. )
  445. @staticmethod
  446. def raw_value(_module, _preference, _category=None, _user_id=None):
  447. # Find the entry for this module in the configuration database.
  448. module = ModulePrefTable.query.filter_by(name=_module).first()
  449. if module is None:
  450. return None
  451. if _category is None:
  452. _category = _module
  453. if _user_id is None:
  454. _user_id = getattr(current_user, 'id', None)
  455. if _user_id is None:
  456. return None
  457. cat = PrefCategoryTbl.query.filter_by(
  458. mid=module.id).filter_by(name=_category).first()
  459. if cat is None:
  460. return None
  461. pref = PrefTable.query.filter_by(
  462. name=_preference).filter_by(cid=cat.id).first()
  463. if pref is None:
  464. return None
  465. user_pref = UserPrefTable.query.filter_by(
  466. pid=pref.id
  467. ).filter_by(uid=_user_id).first()
  468. if user_pref is not None:
  469. return user_pref.value
  470. return None
  471. @classmethod
  472. def module(cls, name, create=True):
  473. """
  474. module (classmethod)
  475. Get the module preferences object
  476. :param name: Name of the module
  477. :param create: Flag to create Preferences object
  478. :returns: a Preferences object representing for the module.
  479. """
  480. if name in Preferences.modules:
  481. m = Preferences.modules[name]
  482. # Update the label (if not defined yet)
  483. if m.label is None:
  484. m.label = name
  485. return m
  486. if create:
  487. return Preferences(name, None)
  488. return None
  489. @classmethod
  490. def save(cls, mid, cid, pid, value):
  491. """
  492. save
  493. Update the value for the preference in the configuration database.
  494. :param mid: Module ID
  495. :param cid: Category ID
  496. :param pid: Preference ID
  497. :param value: Value for the options
  498. """
  499. # Find the entry for this module in the configuration database.
  500. module = ModulePrefTable.query.filter_by(id=mid).first()
  501. # Can't find the reference for it in the configuration database,
  502. # create on for it.
  503. if module is None:
  504. return False, gettext("Could not find the specified module.")
  505. m = cls.modules[module.name]
  506. if m is None:
  507. return False, gettext(
  508. "Module '{0}' is no longer in use."
  509. ).format(module.name)
  510. category = None
  511. for c in m.categories:
  512. cat = m.categories[c]
  513. if cid == cat['id']:
  514. category = cat
  515. break
  516. if category is None:
  517. return False, gettext(
  518. "Module '{0}' does not have category with id '{1}'"
  519. ).format(module.name, cid)
  520. preference = None
  521. for p in category['preferences']:
  522. pref = (category['preferences'])[p]
  523. if pref.pid == pid:
  524. preference = pref
  525. break
  526. if preference is None:
  527. return False, gettext(
  528. "Could not find the specified preference."
  529. )
  530. try:
  531. pref.set(value)
  532. except Exception as e:
  533. current_app.logger.exception(e)
  534. return False, str(e)
  535. return True, None
上海开阖软件有限公司 沪ICP备12045867号-1