PluginSupport.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. # The contents of this file are subject to the BitTorrent Open Source License
  2. # Version 1.1 (the License). You may not copy or use this file, in either
  3. # source code or executable form, except in compliance with the License. You
  4. # may obtain a copy of the License at http://www.bittorrent.com/license/.
  5. #
  6. # Software distributed under the License is distributed on an AS IS basis,
  7. # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  8. # for the specific language governing rights and limitations under the
  9. # License.
  10. #
  11. # Written by Matt Chisholm
  12. import os
  13. import imp
  14. import traceback
  15. import threading
  16. from BitTorrent.platform import plugin_path
  17. from BitTorrent import version
  18. class BasePlugin(object):
  19. def __init__(self, main):
  20. self.main = main
  21. def _supports(version):
  22. return False
  23. supports = staticmethod(_supports)
  24. class DownloadPlugin(BasePlugin):
  25. pass
  26. PLUGIN_EXTENSION = '.py'
  27. class PluginManager(object):
  28. kind = ''
  29. def __init__(self, config, ui_wrap_func):
  30. self.config = config
  31. self.ui_wrap_func = ui_wrap_func
  32. self.plugin_path = [os.path.join(x, self.kind) for x in plugin_path]
  33. self.plugins = []
  34. self._load_plugins()
  35. def _load_plugins(self):
  36. for p in self.plugin_path:
  37. files = os.listdir(p)
  38. for f in files:
  39. if f[0] != '_' and f.endswith(PLUGIN_EXTENSION):
  40. filename = f[:-len(PLUGIN_EXTENSION)]
  41. try:
  42. plugin_module = imp.load_module(filename, *imp.find_module(filename, [p]))
  43. except ImportError:
  44. self.show_status('Could not load %s plugin' % filename)
  45. traceback.print_exc()
  46. continue
  47. for c in dir(plugin_module):
  48. if c[0] != '_':
  49. plugin = getattr(plugin_module, c)
  50. if self._check_plugin(plugin):
  51. self.plugins.append(plugin)
  52. self.show_status("Loaded:", self.plugins)
  53. def _check_plugin(self, plugin):
  54. if not hasattr(plugin, 'supports'):
  55. return False
  56. if not plugin.supports(version):
  57. return False
  58. return True
  59. def _find_plugin(self, *args):
  60. for p in self.plugins:
  61. if p.matches_type(*args):
  62. self.show_status('Found', p, 'for', args)
  63. return p
  64. return None
  65. def run_ui_task(self, funcname, *args):
  66. self.show_status('Would run', funcname, 'with', args, 'using', self.ui_wrap_func)
  67. def show_status(self, *msg):
  68. if False:
  69. print ' '.join(map(str, msg))