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.

пре 12 година
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  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. from hashlib import sha256
  23. from os.path import expanduser
  24. from threading import Lock
  25. from urllib import quote
  26. import oursql
  27. from earwigbot.tasks import Task
  28. class AFCCopyvios(Task):
  29. """A task to check newly-edited [[WP:AFC]] submissions for copyright
  30. violations."""
  31. name = "afc_copyvios"
  32. number = 1
  33. def setup(self):
  34. cfg = self.config.tasks.get(self.name, {})
  35. self.template = cfg.get("template", "AfC suspected copyvio")
  36. self.ignore_list = cfg.get("ignoreList", [])
  37. self.min_confidence = cfg.get("minConfidence", 0.5)
  38. self.max_queries = cfg.get("maxQueries", 10)
  39. self.cache_results = cfg.get("cacheResults", False)
  40. default_summary = "Tagging suspected [[WP:COPYVIO|copyright violation]] of {url}."
  41. self.summary = self.make_summary(cfg.get("summary", default_summary))
  42. # Connection data for our SQL database:
  43. kwargs = cfg.get("sql", {})
  44. kwargs["read_default_file"] = expanduser("~/.my.cnf")
  45. self.conn_data = kwargs
  46. self.db_access_lock = Lock()
  47. def run(self, **kwargs):
  48. """Entry point for the bot task.
  49. Takes a page title in kwargs and checks it for copyvios, adding
  50. {{self.template}} at the top if a copyvio has been detected. A page is
  51. only checked once (processed pages are stored by page_id in an SQL
  52. database).
  53. """
  54. if self.shutoff_enabled():
  55. return
  56. title = kwargs["page"]
  57. page = self.bot.wiki.get_site().get_page(title)
  58. with self.db_access_lock:
  59. self.conn = oursql.connect(**self.conn_data)
  60. self.process(page)
  61. def process(self, page):
  62. """Detect copyvios in 'page' and add a note if any are found."""
  63. title = page.title
  64. if title in self.ignore_list:
  65. msg = u"Skipping page in ignore list: [[{0}]]"
  66. self.logger.info(msg.format(title))
  67. return
  68. pageid = page.pageid
  69. if self.has_been_processed(pageid):
  70. msg = u"Skipping check on already processed page [[{0}]]"
  71. self.logger.info(msg.format(title))
  72. return
  73. self.logger.info(u"Checking [[{0}]]".format(title))
  74. result = page.copyvio_check(self.min_confidence, self.max_queries)
  75. url = result.url
  76. orig_conf = "{0}%".format(round(result.confidence * 100, 2))
  77. if result.violation:
  78. # Things can change in the minute that it takes to do a check.
  79. # Confirm that a violation still holds true:
  80. page.load()
  81. confirm = page.copyvio_compare(url, self.min_confidence)
  82. new_conf = "{0}%".format(round(confirm.confidence * 100, 2))
  83. if not confirm.violation:
  84. msg = u"A violation was detected in [[{0}]], but couldn't be confirmed."
  85. msg += u" It may have just been edited (best: {1} at {2} -> {3} confidence)"
  86. self.logger.info(msg.format(title, url, orig_conf, new_conf))
  87. safeurl = quote(url.encode("utf8"), safe="/:").decode("utf8")
  88. content = page.get()
  89. template = u"\{\{{0}|url={1}|confidence={2}\}\}\n"
  90. template = template.format(self.template, safeurl, new_conf)
  91. newtext = template + content
  92. if "{url}" in self.summary:
  93. page.edit(newtext, self.summary.format(url=url))
  94. else:
  95. page.edit(newtext, self.summary)
  96. msg = u"Found violation: [[{0}]] -> {1} ({2} confidence)"
  97. self.logger.info(msg.format(title, url, new_conf))
  98. else:
  99. msg = u"No violations detected in [[{0}]] (best: {1} at {2} confidence)"
  100. self.logger.info(msg.format(title, url, orig_conf))
  101. self.log_processed(pageid)
  102. if self.cache_results:
  103. self.cache_result(page, result)
  104. def has_been_processed(self, pageid):
  105. """Returns True if pageid was processed before, otherwise False."""
  106. query = "SELECT 1 FROM processed WHERE page_id = ?"
  107. with self.conn.cursor() as cursor:
  108. cursor.execute(query, (pageid,))
  109. results = cursor.fetchall()
  110. return True if results else False
  111. def log_processed(self, pageid):
  112. """Adds pageid to our database of processed pages.
  113. Raises an exception if the page has already been processed.
  114. """
  115. query = "INSERT INTO processed VALUES (?)"
  116. with self.conn.cursor() as cursor:
  117. cursor.execute(query, (pageid,))
  118. def cache_result(self, page, result):
  119. """Store the check's result in a cache table temporarily.
  120. The cache contains the page's ID, a hash of its content, the URL of the
  121. best match, the time of caching, and the number of queries used. It
  122. will replace any existing cache entries for that page.
  123. The cache is intended for EarwigBot's complementary Toolserver web
  124. interface, in which copyvio checks can be done separately from the bot.
  125. The cache saves time and money by saving the result of the web search
  126. but neither the result of the comparison nor any actual text (which
  127. could violate data retention policy). Cache entries are (intended to
  128. be) retained for three days; this task does not remove old entries
  129. (that is handled by the Toolserver component).
  130. This will only be called if ``cache_results == True`` in the task's
  131. config, which is ``False`` by default.
  132. """
  133. pageid = page.pageid
  134. hash = sha256(page.get()).hexdigest()
  135. query1 = "SELECT 1 FROM cache WHERE cache_id = ?"
  136. query2 = "DELETE FROM cache WHERE cache_id = ?"
  137. query3 = "INSERT INTO cache VALUES (?, ?, ?, CURRENT_TIMESTAMP, ?, ?)"
  138. with self.conn.cursor() as cursor:
  139. cursor.execute(query1, (pageid,))
  140. if cursor.fetchall():
  141. cursor.execute(query2, (pageid,))
  142. args = (pageid, hash, result.url, result.queries, 0)
  143. cursor.execute(query3, args)