Additional IRC commands and bot tasks for EarwigBot 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.

218 regels
9.3 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. from hashlib import sha256
  23. from os.path import expanduser
  24. from threading import Lock
  25. from urllib import quote
  26. import mwparserfromhell
  27. import oursql
  28. from earwigbot.tasks import Task
  29. class AFCCopyvios(Task):
  30. """A task to check newly-edited [[WP:AFC]] submissions for copyright
  31. violations."""
  32. name = "afc_copyvios"
  33. number = 1
  34. def setup(self):
  35. cfg = self.config.tasks.get(self.name, {})
  36. self.template = cfg.get("template", "AfC suspected copyvio")
  37. self.ignore_list = cfg.get("ignoreList", [])
  38. self.min_confidence = cfg.get("minConfidence", 0.75)
  39. self.max_queries = cfg.get("maxQueries", 10)
  40. self.max_time = cfg.get("maxTime", 150)
  41. self.cache_results = cfg.get("cacheResults", False)
  42. default_summary = "Tagging suspected [[WP:COPYVIO|copyright violation]] of {url}."
  43. self.summary = self.make_summary(cfg.get("summary", default_summary))
  44. default_tags = [
  45. "Db-g12", "Db-copyvio", "Copyvio", "Copyviocore" "Copypaste"]
  46. self.tags = default_tags + cfg.get("tags", [])
  47. # Connection data for our SQL database:
  48. kwargs = cfg.get("sql", {})
  49. kwargs["read_default_file"] = expanduser("~/.my.cnf")
  50. self.conn_data = kwargs
  51. self.db_access_lock = Lock()
  52. def run(self, **kwargs):
  53. """Entry point for the bot task.
  54. Takes a page title in kwargs and checks it for copyvios, adding
  55. {{self.template}} at the top if a copyvio has been detected. A page is
  56. only checked once (processed pages are stored by page_id in an SQL
  57. database).
  58. """
  59. if self.shutoff_enabled():
  60. return
  61. title = kwargs["page"]
  62. page = self.bot.wiki.get_site().get_page(title)
  63. with self.db_access_lock:
  64. self.conn = oursql.connect(**self.conn_data)
  65. self.process(page)
  66. def process(self, page):
  67. """Detect copyvios in 'page' and add a note if any are found."""
  68. title = page.title
  69. if title in self.ignore_list:
  70. msg = u"Skipping [[{0}]], in ignore list"
  71. self.logger.info(msg.format(title))
  72. return
  73. pageid = page.pageid
  74. if self.has_been_processed(pageid):
  75. msg = u"Skipping [[{0}]], already processed"
  76. self.logger.info(msg.format(title))
  77. return
  78. code = mwparserfromhell.parse(page.get())
  79. if not self.is_pending(code):
  80. msg = u"Skipping [[{0}]], not a pending submission"
  81. self.logger.info(msg.format(title))
  82. return
  83. tag = self.is_tagged(code)
  84. if tag:
  85. msg = u"Skipping [[{0}]], already tagged with '{1}'"
  86. self.logger.info(msg.format(title, tag))
  87. return
  88. self.logger.info(u"Checking [[{0}]]".format(title))
  89. result = page.copyvio_check(self.min_confidence, self.max_queries,
  90. self.max_time)
  91. url = result.url
  92. orig_conf = "{0}%".format(round(result.confidence * 100, 2))
  93. if result.violation:
  94. if self.handle_violation(title, page, url, orig_conf):
  95. self.log_processed(pageid)
  96. return
  97. else:
  98. msg = u"No violations detected in [[{0}]] (best: {1} at {2} confidence)"
  99. self.logger.info(msg.format(title, url, orig_conf))
  100. self.log_processed(pageid)
  101. if self.cache_results:
  102. self.cache_result(page, result)
  103. def handle_violation(self, title, page, url, orig_conf):
  104. """Handle a page that passed its initial copyvio check."""
  105. # Things can change in the minute that it takes to do a check.
  106. # Confirm that a violation still holds true:
  107. page.load()
  108. content = page.get()
  109. tag = self.is_tagged(mwparserfromhell.parse(content))
  110. if tag:
  111. msg = u"A violation was detected in [[{0}]], but it was tagged"
  112. msg += u" in the mean time with '{1}' (best: {2} at {3} confidence)"
  113. self.logger.info(msg.format(title, tag, url, orig_conf))
  114. return True
  115. confirm = page.copyvio_compare(url, self.min_confidence)
  116. new_conf = "{0}%".format(round(confirm.confidence * 100, 2))
  117. if not confirm.violation:
  118. msg = u"A violation was detected in [[{0}]], but couldn't be confirmed."
  119. msg += u" It may have just been edited (best: {1} at {2} -> {3} confidence)"
  120. self.logger.info(msg.format(title, url, orig_conf, new_conf))
  121. return True
  122. msg = u"Found violation: [[{0}]] -> {1} ({2} confidence)"
  123. self.logger.info(msg.format(title, url, new_conf))
  124. safeurl = quote(url.encode("utf8"), safe="/:").decode("utf8")
  125. template = u"\{\{{0}|url={1}|confidence={2}\}\}\n"
  126. template = template.format(self.template, safeurl, new_conf)
  127. newtext = template + content
  128. if "{url}" in self.summary:
  129. page.edit(newtext, self.summary.format(url=url))
  130. else:
  131. page.edit(newtext, self.summary)
  132. def is_tagged(self, code):
  133. """Return whether a page contains a copyvio check template."""
  134. for template in code.ifilter_templates():
  135. for tag in self.tags:
  136. if template.name.matches(tag):
  137. return tag
  138. def is_pending(self, code):
  139. """Return whether a page is a pending AFC submission."""
  140. other_statuses = ["r", "t", "d"]
  141. tmpls = ["submit", "afc submission/submit", "afc submission/pending"]
  142. for template in code.ifilter_templates():
  143. name = template.name.strip().lower()
  144. if name == "afc submission":
  145. if not template.has(1):
  146. return True
  147. if template.get(1).value.strip().lower() not in other_statuses:
  148. return True
  149. elif name in tmpls:
  150. return True
  151. return False
  152. def has_been_processed(self, pageid):
  153. """Returns True if pageid was processed before, otherwise False."""
  154. query = "SELECT 1 FROM processed WHERE page_id = ?"
  155. with self.conn.cursor() as cursor:
  156. cursor.execute(query, (pageid,))
  157. results = cursor.fetchall()
  158. return True if results else False
  159. def log_processed(self, pageid):
  160. """Adds pageid to our database of processed pages.
  161. Raises an exception if the page has already been processed.
  162. """
  163. query = "INSERT INTO processed VALUES (?)"
  164. with self.conn.cursor() as cursor:
  165. cursor.execute(query, (pageid,))
  166. def cache_result(self, page, result):
  167. """Store the check's result in a cache table temporarily.
  168. The cache contains some data associated with the hash of the page's
  169. contents. This data includes the number of queries used, the time to
  170. detect a violation, and a list of sources, which store their respective
  171. URLs, confidence values, and skipped states.
  172. The cache is intended for EarwigBot's complementary Tool Labs web
  173. interface, in which copyvio checks can be done separately from the bot.
  174. The cache saves time and money by saving the result of the web search
  175. but neither the result of the comparison nor any actual text (which
  176. could violate data retention policy). Cache entries are (intended to
  177. be) retained for three days; this task does not remove old entries
  178. (that is handled by the Tool Labs component).
  179. This will only be called if ``cache_results == True`` in the task's
  180. config, which is ``False`` by default.
  181. """
  182. query1 = "DELETE FROM cache WHERE cache_id = ?"
  183. query2 = "INSERT INTO cache VALUES (?, DEFAULT, ?, ?)"
  184. query3 = "INSERT INTO cache_data VALUES (DEFAULT, ?, ?, ?, ?)"
  185. cache_id = buffer(sha256("1:1:" + page.get().encode("utf8")).digest())
  186. data = [(cache_id, source.url, source.confidence, source.skipped)
  187. for source in result.sources]
  188. with self.conn.cursor() as cursor:
  189. cursor.execute("START TRANSACTION")
  190. cursor.execute(query1, (cache_id,))
  191. cursor.execute(query2, (cache_id, result.queries, result.time))
  192. cursor.executemany(query3, data)
  193. cursor.execute("COMMIT")