A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
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.

360 lines
13 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2009-2015 Ben Kurtovic <ben.kurtovic@gmail.com>
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a copy
  6. # of this software and associated documentation files (the "Software"), to deal
  7. # in the Software without restriction, including without limitation the rights
  8. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. # copies of the Software, and to permit persons to whom the Software is
  10. # furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. # SOFTWARE.
  22. import base64
  23. from collections import OrderedDict
  24. from getpass import getpass
  25. import logging
  26. import logging.handlers
  27. from os import mkdir, path
  28. import stat
  29. import yaml
  30. from earwigbot import importer
  31. from earwigbot.config.formatter import BotFormatter
  32. from earwigbot.config.node import ConfigNode
  33. from earwigbot.config.ordered_yaml import OrderedLoader
  34. from earwigbot.config.permissions import PermissionsDB
  35. from earwigbot.config.script import ConfigScript
  36. from earwigbot.exceptions import NoConfigError
  37. fernet = importer.new("cryptography.fernet")
  38. hashes = importer.new("cryptography.hazmat.primitives.hashes")
  39. pbkdf2 = importer.new("cryptography.hazmat.primitives.kdf.pbkdf2")
  40. __all__ = ["BotConfig"]
  41. class BotConfig:
  42. """
  43. **EarwigBot: YAML Config File Manager**
  44. This handles all tasks involving reading and writing to our config file,
  45. including encrypting and decrypting passwords and making a new config file
  46. from scratch at the inital bot run.
  47. BotConfig has a few attributes and methods, including the following:
  48. - :py:attr:`root_dir`: bot's working directory; contains
  49. :file:`config.yml`, :file:`logs/`
  50. - :py:attr:`path`: path to the bot's config file
  51. - :py:attr:`components`: enabled components
  52. - :py:attr:`wiki`: information about wiki-editing
  53. - :py:attr:`irc`: information about IRC
  54. - :py:attr:`commands`: information about IRC commands
  55. - :py:attr:`tasks`: information for bot tasks
  56. - :py:attr:`metadata`: miscellaneous information
  57. - :py:meth:`schedule`: tasks scheduled to run at a given time
  58. BotConfig also has some methods used in config loading:
  59. - :py:meth:`load`: loads (or reloads) and parses our config file
  60. - :py:meth:`decrypt`: decrypts an object in the config tree
  61. """
  62. def __init__(self, bot, root_dir, level):
  63. self._bot = bot
  64. self._root_dir = root_dir
  65. self._logging_level = level
  66. self._config_path = path.join(self.root_dir, "config.yml")
  67. self._log_dir = path.join(self.root_dir, "logs")
  68. perms_file = path.join(self.root_dir, "permissions.db")
  69. self._permissions = PermissionsDB(perms_file)
  70. self._decryption_cipher = None
  71. self._data = None
  72. self._components = ConfigNode()
  73. self._wiki = ConfigNode()
  74. self._irc = ConfigNode()
  75. self._commands = ConfigNode()
  76. self._tasks = ConfigNode()
  77. self._metadata = ConfigNode()
  78. self._nodes = [self._components, self._wiki, self._irc, self._commands,
  79. self._tasks, self._metadata]
  80. self._decryptable_nodes = [ # Default nodes to decrypt
  81. (self._wiki, ("password",)),
  82. (self._wiki, ("search", "credentials", "key")),
  83. (self._wiki, ("search", "credentials", "secret")),
  84. (self._irc, ("frontend", "nickservPassword")),
  85. (self._irc, ("watcher", "nickservPassword")),
  86. ]
  87. def __repr__(self):
  88. """Return the canonical string representation of the BotConfig."""
  89. res = "BotConfig(root_dir={0!r}, level={1!r})"
  90. return res.format(self.root_dir, self.logging_level)
  91. def __str__(self):
  92. """Return a nice string representation of the BotConfig."""
  93. return "<BotConfig at {0}>".format(self.root_dir)
  94. def _handle_missing_config(self):
  95. print("Config file missing or empty:", self._config_path)
  96. msg = "Would you like to create a config file now? [Y/n] "
  97. choice = input(msg)
  98. if choice.lower().startswith("n"):
  99. raise NoConfigError()
  100. else:
  101. try:
  102. ConfigScript(self).make_new()
  103. except KeyboardInterrupt:
  104. raise NoConfigError()
  105. def _load(self):
  106. """Load data from our JSON config file (config.yml) into self._data."""
  107. filename = self._config_path
  108. with open(filename, 'r') as fp:
  109. try:
  110. self._data = yaml.load(fp, OrderedLoader)
  111. except yaml.YAMLError:
  112. print("Error parsing config file {0}:".format(filename))
  113. raise
  114. def _setup_logging(self):
  115. """Configures the logging module so it works the way we want it to."""
  116. log_dir = self._log_dir
  117. logger = logging.getLogger("earwigbot")
  118. logger.handlers = [] # Remove any handlers already attached to us
  119. logger.setLevel(logging.DEBUG)
  120. color_formatter = BotFormatter(color=True)
  121. formatter = BotFormatter()
  122. if self.metadata.get("enableLogging"):
  123. hand = logging.handlers.TimedRotatingFileHandler
  124. logfile = lambda f: path.join(log_dir, f)
  125. if not path.isdir(log_dir):
  126. if not path.exists(log_dir):
  127. mkdir(log_dir, stat.S_IWUSR|stat.S_IRUSR|stat.S_IXUSR)
  128. else:
  129. msg = "log_dir ({0}) exists but is not a directory!"
  130. print(msg.format(log_dir))
  131. return
  132. main_handler = hand(logfile("bot.log"), "midnight", 1, 7)
  133. error_handler = hand(logfile("error.log"), "W6", 1, 4)
  134. debug_handler = hand(logfile("debug.log"), "H", 1, 6)
  135. main_handler.setLevel(logging.INFO)
  136. error_handler.setLevel(logging.WARNING)
  137. debug_handler.setLevel(logging.DEBUG)
  138. for h in (main_handler, error_handler, debug_handler):
  139. h.setFormatter(formatter)
  140. logger.addHandler(h)
  141. self._stream_handler = stream = logging.StreamHandler()
  142. stream.setLevel(self._logging_level)
  143. stream.setFormatter(color_formatter)
  144. logger.addHandler(stream)
  145. def _decrypt(self, node, nodes):
  146. """Try to decrypt the contents of a config node. Use self.decrypt()."""
  147. try:
  148. node._decrypt(self._decryption_cipher, nodes[:-1], nodes[-1])
  149. except ValueError:
  150. print("Error decrypting passwords:")
  151. raise
  152. @property
  153. def bot(self):
  154. """The config's Bot object."""
  155. return self._bot
  156. @property
  157. def root_dir(self):
  158. """The bot's root directory containing its config file and more."""
  159. return self._root_dir
  160. @property
  161. def logging_level(self):
  162. """The minimum logging level for messages logged via stdout."""
  163. return self._logging_level
  164. @logging_level.setter
  165. def logging_level(self, level):
  166. self._logging_level = level
  167. self._stream_handler.setLevel(level)
  168. @property
  169. def path(self):
  170. """The path to the bot's config file."""
  171. return self._config_path
  172. @property
  173. def log_dir(self):
  174. """The directory containing the bot's logs."""
  175. return self._log_dir
  176. @property
  177. def data(self):
  178. """The entire config file as a decoded JSON object."""
  179. return self._data
  180. @property
  181. def components(self):
  182. """A dict of enabled components."""
  183. return self._components
  184. @property
  185. def wiki(self):
  186. """A dict of information about wiki-editing."""
  187. return self._wiki
  188. @property
  189. def irc(self):
  190. """A dict of information about IRC."""
  191. return self._irc
  192. @property
  193. def commands(self):
  194. """A dict of information for IRC commands."""
  195. return self._commands
  196. @property
  197. def tasks(self):
  198. """A dict of information for bot tasks."""
  199. return self._tasks
  200. @property
  201. def metadata(self):
  202. """A dict of miscellaneous information."""
  203. return self._metadata
  204. def is_loaded(self):
  205. """Return ``True`` if our config file has been loaded, or ``False``."""
  206. return self._data is not None
  207. def is_encrypted(self):
  208. """Return ``True`` if passwords are encrypted, otherwise ``False``."""
  209. return self.metadata.get("encryptPasswords", False)
  210. def load(self):
  211. """Load, or reload, our config file.
  212. First, check if we have a valid config file, and if not, notify the
  213. user. If there is no config file at all, offer to make one, otherwise
  214. exit.
  215. Data from the config file is stored in six
  216. :py:class:`~earwigbot.config.ConfigNode`\\ s (:py:attr:`components`,
  217. :py:attr:`wiki`, :py:attr:`irc`, :py:attr:`commands`, :py:attr:`tasks`,
  218. :py:attr:`metadata`) for easy access (as well as the lower-level
  219. :py:attr:`data` attribute). If passwords are encrypted, we'll use
  220. :py:func:`~getpass.getpass` for the key and then decrypt them. If the
  221. config is being reloaded, encrypted items will be automatically
  222. decrypted if they were decrypted earlier.
  223. """
  224. if not path.exists(self._config_path):
  225. self._handle_missing_config()
  226. self._load()
  227. if not self._data:
  228. self._handle_missing_config()
  229. self._load()
  230. self.components._load(self._data.get("components", OrderedDict()))
  231. self.wiki._load(self._data.get("wiki", OrderedDict()))
  232. self.irc._load(self._data.get("irc", OrderedDict()))
  233. self.commands._load(self._data.get("commands", OrderedDict()))
  234. self.tasks._load(self._data.get("tasks", OrderedDict()))
  235. self.metadata._load(self._data.get("metadata", OrderedDict()))
  236. self._setup_logging()
  237. if self.is_encrypted():
  238. if not self._decryption_cipher:
  239. try:
  240. salt = self.metadata["salt"]
  241. kdf = pbkdf2.PBKDF2HMAC(
  242. algorithm=hashes.SHA256(),
  243. length=32,
  244. salt=salt,
  245. iterations=ConfigScript.PBKDF_ROUNDS,
  246. )
  247. except ImportError:
  248. e = "Encryption requires the 'cryptography' package: https://cryptography.io/"
  249. raise NoConfigError(e)
  250. key = getpass("Enter key to decrypt bot passwords: ")
  251. self._decryption_cipher = fernet.Fernet(
  252. base64.urlsafe_b64encode(kdf.derive(key.encode())))
  253. for node, nodes in self._decryptable_nodes:
  254. self._decrypt(node, nodes)
  255. if self.irc:
  256. self.irc["permissions"] = self._permissions
  257. self._permissions.load()
  258. def decrypt(self, node, *nodes):
  259. """Decrypt an object in our config tree.
  260. :py:attr:`_decryption_cipher` is used as our key, retrieved using
  261. :py:func:`~getpass.getpass` in :py:meth:`load` if it wasn't already
  262. specified. If this is called when passwords are not encrypted (check
  263. with :py:meth:`is_encrypted`), nothing will happen. We'll also keep
  264. track of this node if :py:meth:`load` is called again (i.e. to reload)
  265. and automatically decrypt it.
  266. Example usage::
  267. >>> config.decrypt(config.irc, "frontend", "nickservPassword")
  268. # decrypts config.irc["frontend"]["nickservPassword"]
  269. """
  270. signature = (node, nodes)
  271. if signature in self._decryptable_nodes:
  272. return # Already decrypted
  273. self._decryptable_nodes.append(signature)
  274. if self.is_encrypted():
  275. self._decrypt(node, nodes)
  276. def schedule(self, minute, hour, month_day, month, week_day):
  277. """Return a list of tasks scheduled to run at the specified time.
  278. The schedule data comes from our config file's ``schedule`` field,
  279. which is stored as :py:attr:`self.data["schedule"] <data>`.
  280. """
  281. # Tasks to run this turn, each as a list of either [task_name, kwargs],
  282. # or just the task_name:
  283. tasks = []
  284. now = {"minute": minute, "hour": hour, "month_day": month_day,
  285. "month": month, "week_day": week_day}
  286. data = self._data.get("schedule", [])
  287. for event in data:
  288. do = True
  289. for key, value in now.items():
  290. try:
  291. requirement = event[key]
  292. except KeyError:
  293. continue
  294. if requirement != value:
  295. do = False
  296. break
  297. if do:
  298. try:
  299. tasks.extend(event["tasks"])
  300. except KeyError:
  301. pass
  302. return tasks