A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

181 lignes
7.6 KiB

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