utils.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. # -*- coding: utf-8 -*-
  2. """
  3. flaskbb.plugins.utils
  4. ~~~~~~~~~~~~~~~~~~~~~
  5. This module provides registration and a basic DB backed key-value
  6. store for plugins.
  7. :copyright: (c) 2017 by the FlaskBB Team.
  8. :license: BSD, see LICENSE for more details.
  9. """
  10. from flask import current_app, flash, redirect, url_for
  11. from jinja2 import Markup
  12. from flask_babelplus import gettext as _
  13. from flaskbb.extensions import db
  14. from flaskbb.utils.datastructures import TemplateEventResult
  15. from flaskbb.plugins.models import PluginRegistry
  16. def template_hook(name, silent=True, is_markup=True, **kwargs):
  17. """Calls the given template hook.
  18. :param name: The name of the hook.
  19. :param silent: If set to ``False``, it will raise an exception if a hook
  20. doesn't exist. Defauls to ``True``.
  21. :param is_markup: Determines if the hook should return a Markup object or
  22. not. Setting to False returns a TemplateEventResult object.
  23. The default is True.
  24. :param kwargs: Additional kwargs that should be passed to the hook.
  25. """
  26. try:
  27. hook = getattr(current_app.pluggy.hook, name)
  28. result = TemplateEventResult(hook(**kwargs))
  29. except AttributeError: # raised if hook doesn't exist
  30. if silent:
  31. return ""
  32. raise
  33. if is_markup:
  34. return Markup(result)
  35. return result
  36. def validate_plugin(name):
  37. """Tries to look up the plugin by name. Upon failure it will flash
  38. a message and abort. Returns the plugin module on success.
  39. """
  40. plugin_module = current_app.pluggy.get_plugin(name)
  41. if plugin_module is None:
  42. flash(_("Plugin %(plugin)s not found.", plugin=name), "error")
  43. return redirect(url_for("management.plugins"))
  44. return plugin_module
  45. def remove_zombie_plugins_from_db():
  46. """Removes 'zombie' plugins from the db. A zombie plugin is a plugin
  47. which exists in the database but isn't installed in the env anymore.
  48. Returns the names of the deleted plugins.
  49. """
  50. d_fs_plugins = [p[0] for p in current_app.pluggy.list_disabled_plugins()]
  51. d_db_plugins = [p.name for p in PluginRegistry.query.filter_by(enabled=False).all()] # noqa
  52. plugin_names = [p.name for p in PluginRegistry.query.all()]
  53. remove_me = []
  54. for p in plugin_names:
  55. if p in d_db_plugins and p not in d_fs_plugins:
  56. remove_me.append(p)
  57. if len(remove_me) > 0:
  58. PluginRegistry.query.filter(
  59. PluginRegistry.name.in_(remove_me)
  60. ).delete(synchronize_session='fetch')
  61. db.session.commit()
  62. return remove_me