A Python robot that edits Wikipedia and interacts with people over IRC 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.

401 lines
16 KiB

  1. # -*- coding: utf-8 -*-
  2. from datetime import datetime
  3. import logging
  4. import re
  5. from os.path import expanduser
  6. from threading import Lock
  7. import oursql
  8. from classes import BaseTask
  9. import config
  10. import wiki
  11. # Chart status number constants:
  12. CHART_NONE = 0
  13. CHART_PEND = 1
  14. CHART_DRAFT = 2
  15. CHART_REVIEW = 3
  16. CHART_ACCEPT = 4
  17. CHART_DECLINE = 5
  18. class Task(BaseTask):
  19. """A task to generate statistics for WikiProject Articles for Creation.
  20. Statistics are stored in a MySQL database ("u_earwig_afc_statistics")
  21. accessed with oursql. Statistics are updated live while watching the recent
  22. changes IRC feed and saved once an hour, on the hour, to self.pagename.
  23. In the live bot, this is "Template:AFC statistics".
  24. """
  25. name = "afc_statistics"
  26. number = 2
  27. def __init__(self):
  28. self.cfg = cfg = config.tasks.get(self.name, {})
  29. # Set some wiki-related attributes:
  30. self.pagename = cfg.get("page", "Template:AFC statistics")
  31. self.pending_cat = cfg.get("pending", "Pending AfC submissions")
  32. self.ignore_list = cfg.get("ignore_list", [])
  33. default_summary = "Updating statistics for [[WP:WPAFC|WikiProject Articles for creation]]."
  34. self.summary = self.make_summary(cfg.get("summary", default_summary))
  35. # Templates used in chart generation:
  36. templates = cfg.get("templates", {})
  37. self.tl_header = templates.get("header", "AFC statistics/header")
  38. self.tl_row = templates.get("row", "AFC statistics/row")
  39. self.tl_footer = templates.get("footer", "AFC statistics/footer")
  40. # Connection data for our SQL database:
  41. kwargs = cfg.get("sql", {})
  42. kwargs["read_default_file"] = expanduser("~/.my.cnf")
  43. self.conn_data = kwargs
  44. self.db_access_lock = Lock()
  45. def run(self, **kwargs):
  46. self.site = wiki.get_site()
  47. self.conn = oursql.connect(**self.conn_data)
  48. action = kwargs.get("action")
  49. try:
  50. if action == "save":
  51. self.save()
  52. elif action == "sync":
  53. self.sync()
  54. finally:
  55. self.conn.close()
  56. def save(self, **kwargs):
  57. self.logger.info("Saving chart")
  58. if kwargs.get("fromIRC"):
  59. summary = " ".join((self.summary, "(!earwigbot)"))
  60. else:
  61. if self.shutoff_enabled():
  62. return
  63. summary = self.summary
  64. statistics = self.compile_charts()
  65. page = self.site.get_page(self.pagename)
  66. text = page.get()
  67. newtext = re.sub("(<!-- stat begin -->)(.*?)(<!-- stat end -->)",
  68. statistics.join(("\\1\n", "\n\\3")), text,
  69. flags=re.DOTALL)
  70. if newtext == text:
  71. self.logger.info("Chart unchanged; not saving")
  72. return # Don't edit the page if we're not adding anything
  73. newtext = re.sub("(<!-- sig begin -->)(.*?)(<!-- sig end -->)",
  74. "\\1~~~ at ~~~~~\\3", newtext)
  75. page.edit(newtext, summary, minor=True, bot=True)
  76. self.logger.info("Chart saved to [[{0}]]".format(page.title()))
  77. def compile_charts(self):
  78. stats = ""
  79. with self.conn.cursor() as cursor, self.db_access_lock:
  80. cursor.execute("SELECT * FROM chart")
  81. for chart in cursor:
  82. stats += self.compile_chart(chart) + "\n"
  83. return stats[:-1] # Drop the last newline
  84. def compile_chart(self, chart_info):
  85. chart_id, chart_title, special_title = chart_info
  86. chart = "|".join((self.tl_header, chart_title))
  87. if special_title:
  88. chart += "".join(("|", special_title))
  89. chart = "".join(("{{", chart, "}}"))
  90. query = "SELECT * FROM page JOIN row ON page_id = row_id WHERE row_chart = ?"
  91. with self.conn.cursor(oursql.DictCursor) as cursor:
  92. cursor.execute(query, (chart_id,))
  93. for page in cursor:
  94. chart += "\n" + self.compile_chart_row(page)
  95. chart += "".join(("\n{{", self.tl_footer, "}}"))
  96. return chart
  97. def compile_chart_row(self, page):
  98. row = "{0}|s={page_status}|t={page_title}|h={page_short}|z={page_size}|"
  99. row += "cr={page_create_user}|cd={page_create_time}|ci={page_create_oldid}|"
  100. row += "mr={page_modify_user}|md={page_modify_time}|mi={page_modify_oldid}|"
  101. page["page_create_time"] = self.format_time(page["page_create_time"])
  102. page["page_modify_time"] = self.format_time(page["page_modify_time"])
  103. if page["page_special_user"]:
  104. row += "sr={page_special_user}|sd={page_special_time}|si={page_special_oldid}|"
  105. page["page_special_time"] = self.format_time(page["page_special_time"])
  106. if page["page_notes"]:
  107. row += "n=1{page_notes}"
  108. return "".join(("{{", row.format(self.tl_row, **page), "}}"))
  109. def format_time(self, timestamp):
  110. return timestamp.strftime("%H:%M, %d %B %Y")
  111. def sync(self, **kwargs):
  112. self.logger.info("Starting sync")
  113. replag = self.site.get_replag()
  114. self.logger.debug("Server replag is {0}".format(replag))
  115. if replag > 600:
  116. msg = "Sync canceled as replag ({0} secs) is greater than ten minutes."
  117. self.logger.warn(msg.format(replag))
  118. with self.conn.cursor() as cursor, self.db_access_lock:
  119. self.update_tracked(cursor)
  120. self.add_untracked(cursor)
  121. self.delete_old(cursor)
  122. self.logger.info("Sync completed")
  123. def update_tracked(self, cursor):
  124. self.logger.debug("Updating tracked submissions")
  125. query1 = "SELECT page_id, page_title, page_modify_oldid FROM page"
  126. query2 = """SELECT page_latest, page_title, page_namespace FROM page
  127. WHERE page_id = ?"""
  128. cursor.execute(query1)
  129. for pageid, title, oldid in cursor:
  130. msg = "Updating tracked page: [[{0}]] (id: {1}) @ {2}"
  131. self.logger.debug(msg.format(pageid, title, oldid))
  132. result = list(self.site.sql_query(query2, (pageid,)))
  133. try:
  134. real_oldid = result[0][0]
  135. except IndexError: # Page doesn't exist!
  136. self.untrack_page(cursor, pageid)
  137. continue
  138. if real_oldid != oldid:
  139. body = result[0][1].replace("_", " ")
  140. ns = self.site.namespace_id_to_name(result[0][2])
  141. real_title = ":".join(ns, body)
  142. self.update_page(cursor, pageid, real_title)
  143. def add_untracked(self, cursor):
  144. self.logger.debug("Adding untracked pending submissions")
  145. cursor.execute("SELECT page_id FROM page")
  146. tracked = [i[0] for i in cursor.fetchall()]
  147. category = self.site.get_category(self.pending_cat)
  148. pending = category.members(use_sql=True)
  149. for title, pageid in pending:
  150. if title in self.ignore_list:
  151. continue
  152. if pageid not in tracked:
  153. self.track_page(cursor, pageid, title)
  154. def delete_old(self, cursor):
  155. self.logger.debug("Removing old submissions from chart")
  156. query = """DELETE FROM page, row USING page JOIN row
  157. ON page_id = row_id WHERE row_chart IN ?
  158. AND ADDTIME(page_special_time, '36:00:00') < NOW()"""
  159. cursor.execute(query, ((CHART_ACCEPT, CHART_DECLINE),))
  160. def untrack_page(self, cursor, pageid):
  161. self.logger.debug("Untracking page (id: {0})".format(pageid))
  162. query = """DELETE FROM page, row USING page JOIN row
  163. ON page_id = row_id WHERE page_id = ?"""
  164. cursor.execute(query, (pageid,))
  165. def track_page(self, cursor, pageid, title):
  166. """Update hook for when page is not in our database."""
  167. msg = "Tracking page [[{0}]] (id: {1})".format(title, pageid)
  168. self.logger.debug(msg)
  169. content = self.get_content(title)
  170. status, chart = self.get_status_and_chart(content)
  171. if not status:
  172. msg = "Could not find a status for [[{0}]]".format(title)
  173. self.logger.error(msg)
  174. return
  175. short = self.get_short_title(title)
  176. size = len(content)
  177. notes = self.get_notes(pageid)
  178. c_user, c_time, c_id = self.get_create(pageid)
  179. m_user, m_time, m_id = self.get_modify(pageid)
  180. s_user, s_time, s_id = self.get_special(pageid, chart)
  181. query1 = "INSERT INTO row VALUES ?"
  182. query2 = "INSERT INTO page VALUES ?"
  183. cursor.execute(query1, ((pageid, chart),))
  184. cursor.execute(query2, ((pageid, status, title, short, size, notes,
  185. c_user, c_time, c_id, m_user, m_time, m_id,
  186. s_user, s_time, s_id),))
  187. def update_page(self, cursor, pageid, title):
  188. """Update hook for when page is in our database."""
  189. msg = "Updating page [[{0}]] (id: {1})".format(title, pageid)
  190. self.logger.debug(msg)
  191. content = self.get_content(title)
  192. try:
  193. redirect_regex = wiki.Page.re_redirect
  194. target_title = re.findall(redirect_regex, content, flags=re.I)[0]
  195. except IndexError:
  196. pass
  197. else:
  198. target_ns = self.site.get_page(target_title).namespace()
  199. if target_ns == wiki.NS_MAIN:
  200. status, chart = "accept", CHART_ACCEPT
  201. elif target_ns in [wiki.NS_PROJECT, wiki.NS_PROJECT_TALK]:
  202. title = target_title
  203. content = self.get_content(title)
  204. else:
  205. msg = "Page has moved to namespace {0}".format(target_ns)
  206. self.logger.debug(msg)
  207. self.untrack_page(cursor, pageid)
  208. return
  209. status, chart = self.get_status_and_chart(content)
  210. if not status:
  211. self.untrack_page(cursor, pageid)
  212. size = len(content)
  213. notes = self.get_notes(pageid)
  214. m_user, m_time, m_id = self.get_modify(pageid)
  215. query = "SELECT * FROM page JOIN row ON page_id = row_id WHERE page_id = ?"
  216. with self.conn.cursor(oursql.DictCursor) as dict_cursor:
  217. dict_cursor.execute(query, (pageid,))
  218. result = dict_cursor.fetchall()[0]
  219. if title != result["page_title"]:
  220. self.update_page_title(cursor, result, pageid, title)
  221. if m_id != result["page_modify_oldid"]:
  222. self.update_page_modify(cursor, result, pageid, size, m_user, m_time, m_id)
  223. if status != result["page_status"]:
  224. self.update_page_special(cursor, result, pageid, status, chart, page)
  225. if notes != result["page_notes"]:
  226. self.update_page_notes(cursor, result, pageid, notes)
  227. def update_page_title(self, cursor, result, pageid, title):
  228. query = "UPDATE page SET page_title = ?, page_short = ? WHERE page_id = ?"
  229. short = self.get_short_title(title)
  230. cursor.execute(query, (title, short, pageid))
  231. msg = "{0}: title: {1} -> {2}"
  232. self.logger.debug(msg.format(pageid, result["page_title"], title))
  233. def update_page_modify(self, cursor, result, pageid, size, m_user, m_time, m_id):
  234. query = """UPDATE page SET page_size = ?, page_modify_user = ?,
  235. page_modify_time = ?, page_modify_oldid = ?
  236. WHERE page_id = ?"""
  237. cursor.execute(query, (size, m_user, m_time, m_id, pageid))
  238. msg = "{0}: modify: {1} / {2} / {3} -> {4} / {5} / {6}"
  239. msg = msg.format(pageid, result["page_modify_user"],
  240. result["page_modify_time"],
  241. result["page_modify_oldid"], m_user, m_time, m_id)
  242. self.logger.debug(msg)
  243. def update_page_special(self, cursor, result, pageid, status, chart, page):
  244. query1 = """UPDATE page JOIN row ON page_id = row_id
  245. SET page_status = ?, row_chart = ? WHERE page_id = ?"""
  246. query2 = """UPDATE page SET page_special_user = ?,
  247. page_special_time = ?, page_special_oldid = ?
  248. WHERE page_id = ?"""
  249. cursor.execute(query1, (status, chart, pageid))
  250. msg = "{0}: status: {1} ({2}) -> {3} ({4})"
  251. self.logger.debug(msg.format(pageid, result["page_status"],
  252. result["row_chart"], status, chart))
  253. s_user, s_time, s_id = self.get_special(pageid, chart)
  254. if s_id != result["page_special_oldid"]:
  255. cursor.execute(query2, (s_user, s_time, s_id, pageid))
  256. msg = "{0}: special: {1} / {2} / {3} -> {4} / {5} / {6}"
  257. msg = msg.format(pageid, result["page_special_user"],
  258. result["page_special_time"],
  259. result["page_special_oldid"], m_user, m_time, m_id)
  260. self.logger.debug(msg)
  261. def update_page_notes(self, cursor, result, pageid, notes):
  262. query = "UPDATE page SET page_notes = ? WHERE page_id = ?"
  263. cursor.execute(query, (notes, pageid))
  264. msg = "{0}: notes: {1} -> {2}"
  265. self.logger.debug(msg.format(pageid, result["page_notes"], notes))
  266. def get_content(self, title):
  267. query = "SELECT page_latest FROM page WHERE page_title = ? AND page_namespace = ?"
  268. namespace, base = title.split(":", 1)
  269. try:
  270. ns = self.site.namespace_name_to_id(namespace)
  271. except wiki.NamespaceNotFoundError:
  272. base = title
  273. ns = wiki.NS_MAIN
  274. result = self.site.sql_query(query, (base, ns))
  275. revid = list(result)[0]
  276. return self.site.get_revid_content(revid)
  277. def get_status_and_chart(self, content):
  278. if re.search("\{\{afc submission\|r\|(.*?)\}\}", content, re.I):
  279. return "review", CHART_REVIEW
  280. elif re.search("\{\{afc submission\|h\|(.*?)\}\}", content, re.I):
  281. return "pend", CHART_DRAFT
  282. elif re.search("\{\{afc submission\|\|(.*?)\}\}", content, re.I):
  283. return "pend", CHART_PEND
  284. elif re.search("\{\{afc submission\|t\|(.*?)\}\}", content, re.I):
  285. return None, CHART_NONE
  286. elif re.search("\{\{afc submission\|d\|(.*?)\}\}", content, re.I):
  287. return "decline", CHART_DECLINE
  288. return None, CHART_NONE
  289. def get_short_title(self, title):
  290. short = re.sub("Wikipedia(\s*talk)?\:Articles\sfor\screation\/", "", title)
  291. if len(short) > 50:
  292. short = "".join((short[:47], "..."))
  293. return short
  294. def get_create(self, pageid):
  295. query = """SELECT rev_user_text, rev_timestamp, rev_id
  296. FROM revision WHERE rev_id =
  297. (SELECT MIN(rev_id) FROM revision WHERE rev_page = ?)"""
  298. result = self.site.sql_query(query, (pageid,))
  299. c_user, c_time, c_id = list(result)[0]
  300. return c_user, datetime.strptime(c_time, "%Y%m%d%H%M%S"), c_id
  301. def get_modify(self, pageid):
  302. query = """SELECT rev_user_text, rev_timestamp, rev_id FROM revision
  303. JOIN page ON rev_id = page_latest WHERE page_id = ?"""
  304. result = self.site.sql_query(query, (pageid,))
  305. m_user, m_time, m_id = list(result)[0]
  306. return m_user, datetime.strptime(m_time, "%Y%m%d%H%M%S"), m_id
  307. def get_special(self, pageid, chart):
  308. if chart == CHART_PEND:
  309. return None, None, None
  310. elif chart == CHART_ACCEPT:
  311. return self.get_create(pageid)
  312. elif chart == CHART_DRAFT:
  313. search = "(?!\{\{afc submission\|h\|(.*?)\}\})"
  314. elif chart == CHART_REVIEW:
  315. search = "(?!\{\{afc submission\|r\|(.*?)\}\})"
  316. elif chart == CHART_DECLINE:
  317. search = "(?!\{\{afc submission\|d\|(.*?)\}\})"
  318. query = """SELECT rev_user_text, rev_timestamp, rev_id
  319. FROM revision WHERE rev_page = ? ORDER BY rev_id DESC"""
  320. result = self.site.sql_query(query, (pageid,))
  321. counter = 0
  322. for user, ts, revid in result:
  323. counter += 1
  324. if counter > 100:
  325. break
  326. content = self.site.get_revid_content(revid)
  327. if re.search(search, content, re.I):
  328. return user, datetime.strptime(ts, "%Y%m%d%H%M%S"), revid
  329. return None, None, None
  330. def get_notes(self, pageid):
  331. return None