A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

184 řádky
7.7 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. for url in re.findall(regex, data, re.I|re.M):
  86. if url.strip():
  87. urls.add(url.lower().strip())
  88. return urls
  89. def _update(self, sitename):
  90. """Update the database from listed sources in the index."""
  91. query1 = "SELECT source_page FROM sources WHERE source_sitename = ?"
  92. query2 = "SELECT exclusion_url FROM exclusions WHERE exclusion_sitename = ?"
  93. query3 = "DELETE FROM exclusions WHERE exclusion_sitename = ? AND exclusion_url = ?"
  94. query4 = "INSERT INTO exclusions VALUES (?, ?)"
  95. query5 = "SELECT 1 FROM updates WHERE update_sitename = ?"
  96. query6 = "UPDATE updates SET update_time = ? WHERE update_sitename = ?"
  97. query7 = "INSERT INTO updates VALUES (?, ?)"
  98. if sitename == "all":
  99. site = self._sitesdb.get_site("enwiki")
  100. else:
  101. site = self._sitesdb.get_site(sitename)
  102. with sqlite.connect(self._dbfile) as conn, self._db_access_lock:
  103. urls = set()
  104. for (source,) in conn.execute(query1, (sitename,)):
  105. urls |= self._load_source(site, source)
  106. for (url,) in conn.execute(query2, (sitename,)):
  107. if url in urls:
  108. urls.remove(url)
  109. else:
  110. conn.execute(query3, (sitename, url))
  111. conn.executemany(query4, [(sitename, url) for url in urls])
  112. if conn.execute(query5, (sitename,)).fetchone():
  113. conn.execute(query6, (int(time()), sitename))
  114. else:
  115. conn.execute(query7, (sitename, int(time())))
  116. def _get_last_update(self, sitename):
  117. """Return the UNIX timestamp of the last time the db was updated."""
  118. query = "SELECT update_time FROM updates WHERE update_sitename = ?"
  119. with sqlite.connect(self._dbfile) as conn, self._db_access_lock:
  120. try:
  121. result = conn.execute(query, (sitename,)).fetchone()
  122. except sqlite.OperationalError:
  123. self._create()
  124. return 0
  125. return result[0] if result else 0
  126. def sync(self, sitename):
  127. """Update the database if it hasn't been updated in the past day.
  128. This only updates the exclusions database for the *sitename* site.
  129. """
  130. max_staleness = 60 * 60 * 24
  131. time_since_update = int(time() - self._get_last_update(sitename))
  132. if time_since_update > max_staleness:
  133. log = u"Updating stale database: {0} (last updated {1} seconds ago)"
  134. self._logger.info(log.format(sitename, time_since_update))
  135. self._update(sitename)
  136. else:
  137. log = u"Database for {0} is still fresh (last updated {1} seconds ago)"
  138. self._logger.debug(log.format(sitename, time_since_update))
  139. if sitename != "all":
  140. self.sync("all")
  141. def check(self, sitename, url):
  142. """Check whether a given URL is in the exclusions database.
  143. Return ``True`` if the URL is in the database, or ``False`` otherwise.
  144. """
  145. normalized = re.sub(r"^https?://(www\.)?", "", url.lower())
  146. query = """SELECT exclusion_url FROM exclusions
  147. WHERE exclusion_sitename = ? OR exclusion_sitename = ?"""
  148. with sqlite.connect(self._dbfile) as conn, self._db_access_lock:
  149. for (excl,) in conn.execute(query, (sitename, "all")):
  150. if excl.startswith("*."):
  151. matches = excl[2:] in urlparse(url.lower()).netloc
  152. elif excl.startswith("re:"):
  153. matches = re.match(excl[3:], normalized)
  154. else:
  155. matches = normalized.startswith(excl)
  156. if matches:
  157. log = u"Exclusion detected in {0} for {1}"
  158. self._logger.debug(log.format(sitename, url))
  159. return True
  160. log = u"No exclusions in {0} for {1}".format(sitename, url)
  161. self._logger.debug(log)
  162. return False