Additional IRC commands and bot tasks for EarwigBot https://en.wikipedia.org/wiki/User:EarwigBot
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

222 linhas
9.2 KiB

  1. # Copyright (C) 2009-2014 Ben Kurtovic <ben.kurtovic@gmail.com>
  2. #
  3. # Permission is hereby granted, free of charge, to any person obtaining a copy
  4. # of this software and associated documentation files (the "Software"), to deal
  5. # in the Software without restriction, including without limitation the rights
  6. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. # copies of the Software, and to permit persons to whom the Software is
  8. # furnished to do so, subject to the following conditions:
  9. #
  10. # The above copyright notice and this permission notice shall be included in
  11. # all copies or substantial portions of the Software.
  12. #
  13. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  19. # SOFTWARE.
  20. from hashlib import sha256
  21. from os.path import expanduser
  22. from threading import Lock
  23. from urllib import quote
  24. import mwparserfromhell
  25. import oursql
  26. from earwigbot.tasks import Task
  27. class AfCCopyvios(Task):
  28. """A task to check newly-edited [[WP:AFC]] submissions for copyright
  29. violations."""
  30. name = "afc_copyvios"
  31. number = 1
  32. def setup(self):
  33. cfg = self.config.tasks.get(self.name, {})
  34. self.template = cfg.get("template", "AfC suspected copyvio")
  35. self.ignore_list = cfg.get("ignoreList", [])
  36. self.min_confidence = cfg.get("minConfidence", 0.75)
  37. self.max_queries = cfg.get("maxQueries", 10)
  38. self.max_time = cfg.get("maxTime", 150)
  39. self.cache_results = cfg.get("cacheResults", False)
  40. default_summary = (
  41. "Tagging suspected [[WP:COPYVIO|copyright violation]] of {url}."
  42. )
  43. self.summary = self.make_summary(cfg.get("summary", default_summary))
  44. default_tags = ["Db-g12", "Db-copyvio", "Copyvio", "Copyviocore" "Copypaste"]
  45. self.tags = default_tags + cfg.get("tags", [])
  46. # Connection data for our SQL database:
  47. kwargs = cfg.get("sql", {})
  48. kwargs["read_default_file"] = expanduser("~/.my.cnf")
  49. self.conn_data = kwargs
  50. self.db_access_lock = Lock()
  51. def run(self, **kwargs):
  52. """Entry point for the bot task.
  53. Takes a page title in kwargs and checks it for copyvios, adding
  54. {{self.template}} at the top if a copyvio has been detected. A page is
  55. only checked once (processed pages are stored by page_id in an SQL
  56. database).
  57. """
  58. if self.shutoff_enabled():
  59. return
  60. title = kwargs["page"]
  61. page = self.bot.wiki.get_site().get_page(title)
  62. with self.db_access_lock:
  63. self.conn = oursql.connect(**self.conn_data)
  64. self.process(page)
  65. def process(self, page):
  66. """Detect copyvios in 'page' and add a note if any are found."""
  67. title = page.title
  68. if title in self.ignore_list:
  69. msg = "Skipping [[{0}]], in ignore list"
  70. self.logger.info(msg.format(title))
  71. return
  72. pageid = page.pageid
  73. if self.has_been_processed(pageid):
  74. msg = "Skipping [[{0}]], already processed"
  75. self.logger.info(msg.format(title))
  76. return
  77. code = mwparserfromhell.parse(page.get())
  78. if not self.is_pending(code):
  79. msg = "Skipping [[{0}]], not a pending submission"
  80. self.logger.info(msg.format(title))
  81. return
  82. tag = self.is_tagged(code)
  83. if tag:
  84. msg = "Skipping [[{0}]], already tagged with '{1}'"
  85. self.logger.info(msg.format(title, tag))
  86. return
  87. self.logger.info(f"Checking [[{title}]]")
  88. result = page.copyvio_check(
  89. self.min_confidence, self.max_queries, self.max_time
  90. )
  91. url = result.url
  92. orig_conf = f"{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 = "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 = "A violation was detected in [[{0}]], but it was tagged"
  112. msg += " 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 = f"{round(confirm.confidence * 100, 2)}%"
  117. if not confirm.violation:
  118. msg = "A violation was detected in [[{0}]], but couldn't be confirmed."
  119. msg += " 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 = "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 = "\{\{{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 = sha256("1:1:" + page.get().encode("utf8")).digest()
  186. data = [
  187. (cache_id, source.url, source.confidence, source.skipped)
  188. for source in result.sources
  189. ]
  190. with self.conn.cursor() as cursor:
  191. cursor.execute("START TRANSACTION")
  192. cursor.execute(query1, (cache_id,))
  193. cursor.execute(query2, (cache_id, result.queries, result.time))
  194. cursor.executemany(query3, data)
  195. cursor.execute("COMMIT")