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.

172 lines
7.3 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2009-2012 Ben Kurtovic <ben.kurtovic@verizon.net>
  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 re
  23. import sqlite3 as sqlite
  24. from threading import Lock
  25. from time import time
  26. from urlparse import urlparse
  27. from earwigbot import exceptions
  28. __all__ = ["ExclusionsDB"]
  29. default_sources = {
  30. "enwiki": [
  31. "Wikipedia:Mirrors and forks/Abc", "Wikipedia:Mirrors and forks/Def",
  32. "Wikipedia:Mirrors and forks/Ghi", "Wikipedia:Mirrors and forks/Jkl",
  33. "Wikipedia:Mirrors and forks/Mno", "Wikipedia:Mirrors and forks/Pqr",
  34. "Wikipedia:Mirrors and forks/Stu", "Wikipedia:Mirrors and forks/Vwxyz",
  35. "User:EarwigBot/Copyvios/Exclusions"
  36. ]
  37. }
  38. class ExclusionsDB(object):
  39. """
  40. **EarwigBot: Wiki Toolset: Exclusions Database Manager**
  41. Controls the :file:`exclusions.db` file, which stores URLs excluded from
  42. copyright violation checks on account of being known mirrors, for example.
  43. """
  44. def __init__(self, sitesdb, dbfile, logger):
  45. self._sitesdb = sitesdb
  46. self._dbfile = dbfile
  47. self._logger = logger
  48. self._db_access_lock = Lock()
  49. def __repr__(self):
  50. """Return the canonical string representation of the ExclusionsDB."""
  51. res = "ExclusionsDB(sitesdb={0!r}, dbfile={1!r}, logger={2!r})"
  52. return res.format(self._sitesdb, self._dbfile, self._logger)
  53. def __str__(self):
  54. """Return a nice string representation of the ExclusionsDB."""
  55. return "<ExclusionsDB at {0}>".format(self._dbfile)
  56. def _create(self):
  57. """Initialize the exclusions database with its necessary tables."""
  58. script = """
  59. CREATE TABLE sources (source_sitename, source_page);
  60. CREATE TABLE updates (update_sitename, update_time);
  61. CREATE TABLE exclusions (exclusion_sitename, exclusion_url);
  62. """
  63. query = "INSERT INTO sources VALUES (?, ?);"
  64. sources = []
  65. for sitename, pages in default_sources.iteritems():
  66. [sources.append((sitename, page)) for page in pages]
  67. with sqlite.connect(self._dbfile) as conn:
  68. conn.executescript(script)
  69. conn.executemany(query, sources)
  70. def _load_source(self, site, source):
  71. """Load from a specific source and return a set of URLs."""
  72. urls = set()
  73. try:
  74. data = site.get_page(source).get()
  75. except exceptions.PageNotFoundError:
  76. return urls
  77. regexes = [
  78. "url\s*=\s*<nowiki>(?:https?:)?(?://)?(.*)</nowiki>",
  79. "\*\s*Site:\s*\[?(?:https?:)?(?://)?(.*)\]?"
  80. ]
  81. for regex in regexes:
  82. [urls.add(url.lower()) for (url,) in re.findall(regex, data, re.I)]
  83. return urls
  84. def _update(self, sitename):
  85. """Update the database from listed sources in the index."""
  86. query1 = "SELECT source_page FROM sources WHERE source_sitename = ?;"
  87. query2 = "SELECT exclusion_url FROM exclusions WHERE exclusion_sitename = ?"
  88. query3 = "DELETE FROM exclusions WHERE exclusion_sitename = ? AND exclusion_url = ?"
  89. query4 = "INSERT INTO exclusions VALUES (?, ?);"
  90. query5 = "SELECT 1 FROM updates WHERE update_sitename = ?;"
  91. query6 = "UPDATE updates SET update_time = ? WHERE update_sitename = ?;"
  92. query7 = "INSERT INTO updates VALUES (?, ?);"
  93. site = self._sitesdb.get_site(sitename)
  94. with sqlite.connect(self._dbfile) as conn, self._db_access_lock:
  95. urls = set()
  96. for (source,) in conn.execute(query1, (sitename,)):
  97. urls |= self._load_source(site, source)
  98. for (url,) in conn.execute(query2, (sitename,)):
  99. if url in urls:
  100. urls.remove(url)
  101. else:
  102. conn.execute(query3, (sitename, url))
  103. conn.executemany(query4, [(sitename, url) for url in urls])
  104. if conn.execute(query5, (sitename,)).fetchone():
  105. conn.execute(query6, (int(time()), sitename))
  106. else:
  107. conn.execute(query7, (sitename, int(time())))
  108. def _get_last_update(self, sitename):
  109. """Return the UNIX timestamp of the last time the db was updated."""
  110. query = "SELECT update_time FROM updates WHERE update_sitename = ?;"
  111. with sqlite.connect(self._dbfile) as conn, self._db_access_lock:
  112. try:
  113. result = conn.execute(query, (sitename,)).fetchone()
  114. except sqlite.OperationalError:
  115. self._create()
  116. return 0
  117. return result[0] if result else 0
  118. def sync(self, sitename):
  119. """Update the database if it hasn't been updated in the past week.
  120. This only updates the exclusions database for the *sitename* site.
  121. """
  122. max_staleness = 60 * 60 * 24 * 7
  123. time_since_update = int(time() - self._get_last_update(sitename))
  124. if time_since_update > max_staleness:
  125. log = u"Updating stale database: {0} (last updated {1} seconds ago)"
  126. self._logger.info(log.format(sitename, time_since_update))
  127. self._update(sitename)
  128. else:
  129. log = u"Database for {0} is still fresh (last updated {1} seconds ago)"
  130. self._logger.debug(log.format(sitename, time_since_update))
  131. def check(self, sitename, url):
  132. """Check whether a given URL is in the exclusions database.
  133. Return ``True`` if the URL is in the database, or ``False`` otherwise.
  134. """
  135. normalized = re.sub("https?://", "", url.lower())
  136. query = "SELECT exclusion_url FROM exclusions WHERE exclusion_sitename = ?"
  137. with sqlite.connect(self._dbfile) as conn, self._db_access_lock:
  138. for (excl,) in conn.execute(query, (sitename,)):
  139. if excl.startswith("*."):
  140. netloc = urlparse(url.lower()).netloc
  141. matches = True if excl[2:] in netloc else False
  142. else:
  143. matches = True if normalized.startswith(excl) else False
  144. if matches:
  145. log = u"Exclusion detected in {0} for {1}"
  146. self._logger.debug(log.format(sitename, url))
  147. return True
  148. log = u"No exclusions in {0} for {1}".format(sitename, url)
  149. self._logger.debug(log)
  150. return False