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.

196 rivejä
7.4 KiB

  1. # -*- coding: utf-8 -*-
  2. """
  3. EarwigBot's Wiki Toolset: Misc Functions
  4. This module, a component of the wiki package, contains miscellaneous functions
  5. that are not methods of any class, like get_site().
  6. There's no need to import this module explicitly. All functions here are
  7. automatically available from wiki.
  8. """
  9. from cookielib import LWPCookieJar, LoadError
  10. import errno
  11. from getpass import getpass
  12. from os import chmod, path
  13. import platform
  14. import stat
  15. import config
  16. from wiki.exceptions import SiteNotFoundError
  17. from wiki.site import Site
  18. __all__ = ["get_site"]
  19. _cookiejar = None
  20. def _load_config():
  21. """Called by a config-requiring function, such as get_site(), when config
  22. has not been loaded. This will usually happen only if we're running code
  23. directly from Python's interpreter and not the bot itself, because
  24. earwigbot.py or core/main.py will already call these functions.
  25. """
  26. is_encrypted = config.load()
  27. if is_encrypted: # passwords in the config file are encrypted
  28. key = getpass("Enter key to unencrypt bot passwords: ")
  29. config.decrypt(key)
  30. def _get_cookiejar():
  31. """Returns a LWPCookieJar object loaded from our .cookies file. The same
  32. one is returned every time.
  33. The .cookies file is located in the project root, same directory as
  34. config.json and earwigbot.py. If it doesn't exist, we will create the file
  35. and set it to be readable and writeable only by us. If it exists but the
  36. information inside is bogus, we will ignore it.
  37. This is normally called by _get_site_object_from_dict() (in turn called by
  38. get_site()), and the cookiejar is passed to our Site's constructor, used
  39. when it makes API queries. This way, we can easily preserve cookies between
  40. sites (e.g., for CentralAuth), making logins easier.
  41. """
  42. global _cookiejar
  43. if _cookiejar is not None:
  44. return _cookiejar
  45. cookie_file = path.join(config.root_dir, ".cookies")
  46. _cookiejar = LWPCookieJar(cookie_file)
  47. try:
  48. _cookiejar.load()
  49. except LoadError:
  50. # file contains bad data, so ignore it completely
  51. pass
  52. except IOError as e:
  53. if e.errno == errno.ENOENT: # "No such file or directory"
  54. # create the file and restrict reading/writing only to the owner,
  55. # so others can't peak at our cookies
  56. open(cookie_file, "w").close()
  57. chmod(cookie_file, stat.S_IRUSR|stat.S_IWUSR)
  58. else:
  59. raise
  60. return _cookiejar
  61. def _get_site_object_from_dict(name, d):
  62. """Return a Site object based on the contents of a dict, probably acquired
  63. through our config file, and a separate name.
  64. """
  65. project = d.get("project")
  66. lang = d.get("lang")
  67. base_url = d.get("baseURL")
  68. article_path = d.get("articlePath")
  69. script_path = d.get("scriptPath")
  70. sql = (d.get("sqlServer"), d.get("sqlDB"))
  71. namespaces = d.get("namespaces", {})
  72. login = (config.wiki.get("username"), config.wiki.get("password"))
  73. cookiejar = _get_cookiejar()
  74. user_agent = config.wiki.get("userAgent")
  75. assert_edit = config.wiki.get("assert")
  76. maxlag = config.wiki.get("maxlag")
  77. if user_agent:
  78. user_agent = user_agent.replace("$1", platform.python_version())
  79. for key, value in namespaces.items(): # Convert string keys to integers
  80. del namespaces[key]
  81. try:
  82. namespaces[int(key)] = value
  83. except ValueError: # Data is broken, ignore it
  84. namespaces = None
  85. break
  86. return Site(name=name, project=project, lang=lang, base_url=base_url,
  87. article_path=article_path, script_path=script_path, sql=sql,
  88. namespaces=namespaces, login=login, cookiejar=cookiejar,
  89. user_agent=user_agent, assert_edit=assert_edit, maxlag=maxlag)
  90. def get_site(name=None, project=None, lang=None):
  91. """Returns a Site instance based on information from our config file.
  92. With no arguments, returns the default site as specified by our config
  93. file. This is default = config.wiki["defaultSite"];
  94. config.wiki["sites"][default].
  95. With `name` specified, returns the site specified by
  96. config.wiki["sites"][name].
  97. With `project` and `lang` specified, returns the site specified by the
  98. member of config.wiki["sites"], `s`, for which s["project"] == project and
  99. s["lang"] == lang.
  100. We will attempt to login to the site automatically
  101. using config.wiki["username"] and config.wiki["password"] if both are
  102. defined.
  103. Specifying a project without a lang or a lang without a project will raise
  104. TypeError. If all three args are specified, `name` will be first tried,
  105. then `project` and `lang`. If, with any number of args, a site cannot be
  106. found in the config, SiteNotFoundError is raised.
  107. """
  108. # check if config has been loaded, and load it if it hasn't
  109. if not config.is_loaded():
  110. _load_config()
  111. # someone specified a project without a lang (or a lang without a project)!
  112. if (project is None and lang is not None) or (project is not None and
  113. lang is None):
  114. e = "Keyword arguments 'lang' and 'project' must be specified together."
  115. raise TypeError(e)
  116. # no args given, so return our default site (project is None implies lang
  117. # is None, so we don't need to add that in)
  118. if name is None and project is None:
  119. try:
  120. default = config.wiki["defaultSite"]
  121. except KeyError:
  122. e = "Default site is not specified in config."
  123. raise SiteNotFoundError(e)
  124. try:
  125. site = config.wiki["sites"][default]
  126. except KeyError:
  127. e = "Default site specified by config is not in the config's sites list."
  128. raise SiteNotFoundError(e)
  129. return _get_site_object_from_dict(default, site)
  130. # name arg given, but don't look at others unless `name` isn't found
  131. if name is not None:
  132. try:
  133. site = config.wiki["sites"][name]
  134. except KeyError:
  135. if project is None: # implies lang is None, so only name was given
  136. e = "Site '{0}' not found in config.".format(name)
  137. raise SiteNotFoundError(e)
  138. for sitename, site in config.wiki["sites"].items():
  139. if site["project"] == project and site["lang"] == lang:
  140. return _get_site_object_from_dict(sitename, site)
  141. e = "Neither site '{0}' nor site '{1}:{2}' found in config."
  142. e.format(name, project, lang)
  143. raise SiteNotFoundError(e)
  144. else:
  145. return _get_site_object_from_dict(name, site)
  146. # if we end up here, then project and lang are both not None
  147. for sitename, site in config.wiki["sites"].items():
  148. if site["project"] == project and site["lang"] == lang:
  149. return _get_site_object_from_dict(sitename, site)
  150. e = "Site '{0}:{1}' not found in config.".format(project, lang)
  151. raise SiteNotFoundError(e)
  152. def add_site():
  153. """STUB: config editing is required first.
  154. Returns True if the site was added successfully or False if the site was
  155. already in our config. Raises ConfigError if saving the updated file failed
  156. for some reason."""
  157. pass
  158. def del_site(name):
  159. """STUB: config editing is required first.
  160. Returns True if the site was removed successfully or False if the site was
  161. not in our config originally. Raises ConfigError if saving the updated file
  162. failed for some reason."""
  163. pass