A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
Não pode escolher mais do que 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.

580 linhas
25 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. from time import sleep
  8. import oursql
  9. from classes import BaseTask
  10. import config
  11. import wiki
  12. # Chart status number constants:
  13. CHART_NONE = 0
  14. CHART_PEND = 1
  15. CHART_DRAFT = 2
  16. CHART_REVIEW = 3
  17. CHART_ACCEPT = 4
  18. CHART_DECLINE = 5
  19. class Task(BaseTask):
  20. """A task to generate statistics for WikiProject Articles for Creation.
  21. Statistics are stored in a MySQL database ("u_earwig_afc_statistics")
  22. accessed with oursql. Statistics are synchronied with the live database
  23. every four minutes and saved once an hour, on the hour, to self.pagename.
  24. In the live bot, this is "Template:AFC statistics".
  25. """
  26. name = "afc_statistics"
  27. number = 2
  28. def __init__(self):
  29. self.cfg = cfg = config.tasks.get(self.name, {})
  30. # Set some wiki-related attributes:
  31. self.pagename = cfg.get("page", "Template:AFC statistics")
  32. self.pending_cat = cfg.get("pending", "Pending AfC submissions")
  33. self.ignore_list = cfg.get("ignore_list", [])
  34. default_summary = "Updating statistics for [[WP:WPAFC|WikiProject Articles for creation]]."
  35. self.summary = self.make_summary(cfg.get("summary", default_summary))
  36. # Templates used in chart generation:
  37. templates = cfg.get("templates", {})
  38. self.tl_header = templates.get("header", "AFC statistics/header")
  39. self.tl_row = templates.get("row", "AFC statistics/row")
  40. self.tl_footer = templates.get("footer", "AFC statistics/footer")
  41. # Connection data for our SQL database:
  42. kwargs = cfg.get("sql", {})
  43. kwargs["read_default_file"] = expanduser("~/.my.cnf")
  44. self.conn_data = kwargs
  45. self.db_access_lock = Lock()
  46. def run(self, **kwargs):
  47. """Entry point for a task event.
  48. Depending on the kwargs passed, we will either synchronize our local
  49. statistics database with the site (self.sync()) or save it to the wiki
  50. (self.save()). We will additionally create an SQL connection with our
  51. local database.
  52. """
  53. self.site = wiki.get_site()
  54. with self.db_access_lock:
  55. self.conn = oursql.connect(**self.conn_data)
  56. action = kwargs.get("action")
  57. try:
  58. if action == "save":
  59. self.save(**kwargs)
  60. elif action == "sync":
  61. self.sync(**kwargs)
  62. finally:
  63. self.conn.close()
  64. def save(self, **kwargs):
  65. """Save our local statistics to the wiki.
  66. After checking for emergency shutoff, the statistics chart is compiled,
  67. and then saved to self.pagename using self.summary iff it has changed
  68. since last save.
  69. """
  70. self.logger.info("Saving chart")
  71. if kwargs.get("fromIRC"):
  72. summary = " ".join((self.summary, "(!earwigbot)"))
  73. else:
  74. if self.shutoff_enabled():
  75. return
  76. summary = self.summary
  77. statistics = self.compile_charts().encode("utf8")
  78. page = self.site.get_page(self.pagename)
  79. text = page.get().encode("utf8")
  80. newtext = re.sub("(<!-- stat begin -->)(.*?)(<!-- stat end -->)",
  81. statistics.join(("\\1\n", "\n\\3")), text,
  82. flags=re.DOTALL)
  83. if newtext == text:
  84. self.logger.info("Chart unchanged; not saving")
  85. return # Don't edit the page if we're not adding anything
  86. newtext = re.sub("(<!-- sig begin -->)(.*?)(<!-- sig end -->)",
  87. "\\1~~~ at ~~~~~\\3", newtext)
  88. page.edit(newtext, summary, minor=True, bot=True)
  89. self.logger.info("Chart saved to [[{0}]]".format(page.title()))
  90. def compile_charts(self):
  91. """Compile and return all statistics information from our local db."""
  92. stats = ""
  93. with self.conn.cursor() as cursor:
  94. cursor.execute("SELECT * FROM chart")
  95. for chart in cursor:
  96. stats += self.compile_chart(chart) + "\n"
  97. return stats[:-1] # Drop the last newline
  98. def compile_chart(self, chart_info):
  99. """Compile and return a single statistics chart."""
  100. chart_id, chart_title, special_title = chart_info
  101. chart = "|".join((self.tl_header, chart_title))
  102. if special_title:
  103. chart += "".join(("|", special_title))
  104. chart = "".join(("{{", chart, "}}"))
  105. query = "SELECT * FROM page JOIN row ON page_id = row_id WHERE row_chart = ?"
  106. with self.conn.cursor(oursql.DictCursor) as cursor:
  107. cursor.execute(query, (chart_id,))
  108. for page in cursor:
  109. chart += "\n" + self.compile_chart_row(page).decode("utf8")
  110. chart += "".join(("\n{{", self.tl_footer, "}}"))
  111. return chart
  112. def compile_chart_row(self, page):
  113. """Compile and return a single chart row.
  114. 'page' is a dict of page information, taken as a row from the page
  115. table, where keys are column names and values are their cell contents.
  116. """
  117. row = "{0}|s={page_status}|t={page_title}|h={page_short}|z={page_size}|"
  118. row += "cr={page_create_user}|cd={page_create_time}|ci={page_create_oldid}|"
  119. row += "mr={page_modify_user}|md={page_modify_time}|mi={page_modify_oldid}|"
  120. page["page_create_time"] = self.format_time(page["page_create_time"])
  121. page["page_modify_time"] = self.format_time(page["page_modify_time"])
  122. if page["page_special_user"]:
  123. row += "sr={page_special_user}|sd={page_special_time}|si={page_special_oldid}|"
  124. page["page_special_time"] = self.format_time(page["page_special_time"])
  125. if page["page_notes"]:
  126. row += "n=1{page_notes}"
  127. return "".join(("{{", row.format(self.tl_row, **page), "}}"))
  128. def format_time(self, timestamp):
  129. """Format a datetime into the standard MediaWiki timestamp format."""
  130. return timestamp.strftime("%H:%M, %d %B %Y")
  131. def sync(self, **kwargs):
  132. """Synchronize our local statistics database with the site.
  133. Syncing involves, in order, updating tracked submissions that have
  134. been changed since last sync (self.update_tracked()), adding pending
  135. submissions that are not tracked (self.add_untracked()), and removing
  136. old submissions from the database (self.delete_old()).
  137. The sync will be canceled if SQL replication lag is greater than 600
  138. seconds, because this will lead to potential problems and outdated
  139. data, not to mention putting demand on an already overloaded server.
  140. Giving sync the kwarg "ignore_replag" will go around this restriction.
  141. """
  142. self.logger.info("Starting sync")
  143. replag = self.site.get_replag()
  144. self.logger.debug("Server replag is {0}".format(replag))
  145. if replag > 600 and not kwargs.get("ignore_replag"):
  146. msg = "Sync canceled as replag ({0} secs) is greater than ten minutes."
  147. self.logger.warn(msg.format(replag))
  148. with self.conn.cursor() as cursor:
  149. self.update_tracked(cursor)
  150. self.add_untracked(cursor)
  151. self.delete_old(cursor)
  152. self.logger.info("Sync completed")
  153. def update_tracked(self, cursor):
  154. """Update tracked submissions that have been changed since last sync.
  155. This is done by iterating through every page in our database and
  156. comparing our stored latest revision ID with the actual latest revision
  157. ID from an SQL query. If they differ, we will update our information
  158. about the page (self.update_page()).
  159. If the page does not exist, we will remove it from our database with
  160. self.untrack_page().
  161. """
  162. self.logger.debug("Updating tracked submissions")
  163. query1 = "SELECT page_id, page_title, page_modify_oldid FROM page"
  164. query2 = """SELECT page_latest, page_title, page_namespace FROM page
  165. WHERE page_id = ?"""
  166. cursor.execute(query1)
  167. for pageid, title, oldid in cursor:
  168. result = list(self.site.sql_query(query2, (pageid,)))
  169. if not result:
  170. self.untrack_page(cursor, pageid)
  171. continue
  172. real_oldid = result[0][0]
  173. if oldid != real_oldid:
  174. msg = "Updating page [[{0}]] (id: {1}) @ {2}"
  175. self.logger.debug(msg.format(title, pageid, oldid))
  176. self.logger.debug(" {0} -> {1}".format(oldid, real_oldid))
  177. body = result[0][1].replace("_", " ")
  178. ns = self.site.namespace_id_to_name(result[0][2])
  179. if ns:
  180. real_title = ":".join((str(ns), body))
  181. else:
  182. real_title = body
  183. self.update_page(cursor, pageid, real_title)
  184. def add_untracked(self, cursor):
  185. """Add pending submissions that are not yet tracked.
  186. This is done by compiling a list of all currently tracked submissions
  187. and iterating through all members of self.pending_cat via SQL. If a
  188. page in the pending category is not tracked and is not in
  189. self.ignore_list, we will track it with self.track_page().
  190. """
  191. self.logger.debug("Adding untracked pending submissions")
  192. cursor.execute("SELECT page_id FROM page")
  193. tracked = [i[0] for i in cursor.fetchall()]
  194. category = self.site.get_category(self.pending_cat)
  195. pending = category.members(use_sql=True)
  196. for title, pageid in pending:
  197. if title.decode("utf8") in self.ignore_list:
  198. continue
  199. if pageid not in tracked:
  200. msg = "Tracking page [[{0}]] (id: {1})".format(title, pageid)
  201. self.logger.debug(msg)
  202. self.track_page(cursor, pageid, title)
  203. def delete_old(self, cursor):
  204. """Remove old submissions from the database.
  205. "Old" is defined as a submission that has been declined or accepted
  206. more than 36 hours ago. Pending submissions cannot be "old".
  207. """
  208. self.logger.debug("Removing old submissions from chart")
  209. query = """DELETE FROM page, row USING page JOIN row
  210. ON page_id = row_id WHERE row_chart IN (?, ?)
  211. AND ADDTIME(page_special_time, '36:00:00') < NOW()"""
  212. cursor.execute(query, (CHART_ACCEPT, CHART_DECLINE))
  213. def untrack_page(self, cursor, pageid):
  214. """Remove a page, given by ID, from our database."""
  215. self.logger.debug("Untracking page (id: {0})".format(pageid))
  216. query = """DELETE FROM page, row USING page JOIN row
  217. ON page_id = row_id WHERE page_id = ?"""
  218. cursor.execute(query, (pageid,))
  219. def track_page(self, cursor, pageid, title):
  220. """Update hook for when page is not in our database.
  221. A variety of SQL queries are used to gather information about the page,
  222. which are then saved to our database.
  223. """
  224. content = self.get_content(title)
  225. if not content:
  226. msg = "Could not get page content for [[{0}]]".format(title)
  227. self.logger.error(msg)
  228. return
  229. status, chart = self.get_status_and_chart(content)
  230. if not status:
  231. msg = "Could not find a status for [[{0}]]".format(title)
  232. self.logger.error(msg)
  233. return
  234. short = self.get_short_title(title)
  235. size = len(content)
  236. c_user, c_time, c_id = self.get_create(pageid)
  237. m_user, m_time, m_id = self.get_modify(pageid)
  238. s_user, s_time, s_id = self.get_special(pageid, chart)
  239. notes = self.get_notes(content, m_time, c_user)
  240. query1 = "INSERT INTO row VALUES (?, ?)"
  241. query2 = "INSERT INTO page VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
  242. cursor.execute(query1, (pageid, chart))
  243. cursor.execute(query2, (pageid, status, title.decode("utf8"),
  244. short.decode("utf8"), size, notes, c_user,
  245. c_time, c_id, m_user, m_time, m_id, s_user,
  246. s_time, s_id))
  247. def update_page(self, cursor, pageid, title):
  248. """Update hook for when page is already in our database.
  249. A variety of SQL queries are used to gather information about the page,
  250. which is compared against our stored information. Differing information
  251. is then updated.
  252. If our page is now a redirect, we will determine the namespace it was
  253. moved to. If it was moved to the mainspace or template space, we will
  254. set the sub's status as accepted. If it was to the Project: or Project
  255. talk: namespaces, we'll merely update our stored title (this is likely
  256. to occur if a submission was moved from the userspace to the project
  257. space). If it was moved to another namespace, something unusual has
  258. happened, and we'll untrack the submission.
  259. """
  260. content = self.get_content(title)
  261. if not content:
  262. msg = "Could not get page content for [[{0}]]".format(title)
  263. self.logger.error(msg)
  264. return
  265. try:
  266. redirect_regex = wiki.Page.re_redirect
  267. target_title = re.findall(redirect_regex, content, flags=re.I)[0]
  268. except IndexError:
  269. status, chart = self.get_status_and_chart(content)
  270. if not status:
  271. self.untrack_page(cursor, pageid)
  272. return
  273. else:
  274. target_ns = self.site.get_page(target_title).namespace()
  275. if target_ns in [wiki.NS_MAIN, wiki.NS_TEMPLATE]:
  276. status, chart = "a", CHART_ACCEPT
  277. elif target_ns in [wiki.NS_PROJECT, wiki.NS_PROJECT_TALK]:
  278. title = target_title
  279. content = self.get_content(title)
  280. status, chart = self.get_status_and_chart(content)
  281. if not status:
  282. self.untrack_page(cursor, pageid)
  283. return
  284. else:
  285. msg = " Page has moved to namespace {0}".format(target_ns)
  286. self.logger.debug(msg)
  287. self.untrack_page(cursor, pageid)
  288. return
  289. query = "SELECT * FROM page JOIN row ON page_id = row_id WHERE page_id = ?"
  290. with self.conn.cursor(oursql.DictCursor) as dict_cursor:
  291. dict_cursor.execute(query, (pageid,))
  292. result = dict_cursor.fetchall()[0]
  293. size = len(content)
  294. m_user, m_time, m_id = self.get_modify(pageid)
  295. notes = self.get_notes(content, m_time, result["page_create_user"])
  296. if title != result["page_title"]:
  297. self.update_page_title(cursor, result, pageid, title)
  298. if m_id != result["page_modify_oldid"]:
  299. self.update_page_modify(cursor, result, pageid, size, m_user, m_time, m_id)
  300. if status != result["page_status"]:
  301. self.update_page_status(cursor, result, pageid, status, chart)
  302. if notes != result["page_notes"]:
  303. self.update_page_notes(cursor, result, pageid, notes)
  304. def update_page_title(self, cursor, result, pageid, title):
  305. """Update the title and short_title of a page in our database."""
  306. query = "UPDATE page SET page_title = ?, page_short = ? WHERE page_id = ?"
  307. short = self.get_short_title(title)
  308. cursor.execute(query, (title.decode("utf8"), short.decode("utf8"),
  309. pageid))
  310. msg = " {0}: title: {1} -> {2}"
  311. self.logger.debug(msg.format(pageid, result["page_title"], title))
  312. def update_page_modify(self, cursor, result, pageid, size, m_user, m_time, m_id):
  313. """Update the last modified information of a page in our database."""
  314. query = """UPDATE page SET page_size = ?, page_modify_user = ?,
  315. page_modify_time = ?, page_modify_oldid = ?
  316. WHERE page_id = ?"""
  317. cursor.execute(query, (size, m_user, m_time, m_id, pageid))
  318. msg = " {0}: modify: {1} / {2} / {3} -> {4} / {5} / {6}"
  319. msg = msg.format(pageid, result["page_modify_user"],
  320. result["page_modify_time"],
  321. result["page_modify_oldid"], m_user, m_time, m_id)
  322. self.logger.debug(msg)
  323. def update_page_status(self, cursor, result, pageid, status, chart):
  324. """Update the status and "specialed" information of a page."""
  325. query1 = """UPDATE page JOIN row ON page_id = row_id
  326. SET page_status = ?, row_chart = ? WHERE page_id = ?"""
  327. query2 = """UPDATE page SET page_special_user = ?,
  328. page_special_time = ?, page_special_oldid = ?
  329. WHERE page_id = ?"""
  330. cursor.execute(query1, (status, chart, pageid))
  331. msg = " {0}: status: {1} ({2}) -> {3} ({4})"
  332. self.logger.debug(msg.format(pageid, result["page_status"],
  333. result["row_chart"], status, chart))
  334. s_user, s_time, s_id = self.get_special(pageid, chart)
  335. if s_id != result["page_special_oldid"]:
  336. cursor.execute(query2, (s_user, s_time, s_id, pageid))
  337. msg = "{0}: special: {1} / {2} / {3} -> {4} / {5} / {6}"
  338. msg = msg.format(pageid, result["page_special_user"],
  339. result["page_special_time"],
  340. result["page_special_oldid"], s_user, s_time, s_id)
  341. self.logger.debug(msg)
  342. def update_page_notes(self, cursor, result, pageid, notes):
  343. """Update the notes (or warnings) of a page in our database."""
  344. query = "UPDATE page SET page_notes = ? WHERE page_id = ?"
  345. cursor.execute(query, (notes, pageid))
  346. msg = " {0}: notes: {1} -> {2}"
  347. self.logger.debug(msg.format(pageid, result["page_notes"], notes))
  348. def get_content(self, title):
  349. """Get the current content of a page by title from the API.
  350. The page's current revision ID is retrieved from SQL, and then
  351. an API query is made to get its content. This is the only API query
  352. used in the task's code.
  353. """
  354. query = "SELECT page_latest FROM page WHERE page_title = ? AND page_namespace = ?"
  355. namespace, base = title.decode("utf8").split(":", 1)
  356. try:
  357. ns = self.site.namespace_name_to_id(namespace)
  358. except wiki.NamespaceNotFoundError:
  359. base = title
  360. ns = wiki.NS_MAIN
  361. result = self.site.sql_query(query, (base.replace(" ", "_"), ns))
  362. revid = int(list(result)[0][0])
  363. return self.get_revision_content(revid)
  364. def get_revision_content(self, revid):
  365. """Get the content of a revision by ID from the API."""
  366. res = self.site.api_query(action="query", prop="revisions",
  367. revids=revid, rvprop="content")
  368. try:
  369. return res["query"]["pages"].values()[0]["revisions"][0]["*"]
  370. except KeyError:
  371. sleep(5)
  372. res = self.site.api_query(action="query", prop="revisions",
  373. revids=revid, rvprop="content")
  374. try:
  375. return res["query"]["pages"].values()[0]["revisions"][0]["*"]
  376. except KeyError:
  377. return None
  378. def get_status_and_chart(self, content):
  379. """Determine the status and chart number of an AFC submission.
  380. The methodology used here is the same one I've been using for years
  381. (see also commands.afc_report), but with the new draft system taken
  382. into account. The order here is important: if there is more than one
  383. {{AFC submission}} template on a page, we need to know which one to
  384. use (revision history search to find the most recent isn't a viable
  385. idea :P).
  386. """
  387. if re.search("\{\{afc submission\|r\|(.*?)\}\}", content, re.I):
  388. return "r", CHART_REVIEW
  389. elif re.search("\{\{afc submission\|h\|(.*?)\}\}", content, re.I):
  390. return "p", CHART_DRAFT
  391. elif re.search("\{\{afc submission\|\|(.*?)\}\}", content, re.I):
  392. return "p", CHART_PEND
  393. elif re.search("\{\{afc submission\|t\|(.*?)\}\}", content, re.I):
  394. return None, CHART_NONE
  395. elif re.search("\{\{afc submission\|d\|(.*?)\}\}", content, re.I):
  396. return "d", CHART_DECLINE
  397. return None, CHART_NONE
  398. def get_short_title(self, title):
  399. """Shorten a title so we can display it in a chart using less space.
  400. Basically, this just means removing the "Wikipedia talk:Articles for
  401. creation" part from the beginning. If it is longer than 50 characters,
  402. we'll shorten it down to 47 and add an poor-man's ellipsis at the end.
  403. """
  404. short = re.sub("Wikipedia(\s*talk)?\:Articles\sfor\screation\/", "", title)
  405. if len(short) > 50:
  406. short = "".join((short[:47], "..."))
  407. return short
  408. def get_create(self, pageid):
  409. """Return information about a page's first edit ("creation").
  410. This consists of the page creator, creation time, and the earliest
  411. revision ID.
  412. """
  413. query = """SELECT rev_user_text, rev_timestamp, rev_id
  414. FROM revision WHERE rev_id =
  415. (SELECT MIN(rev_id) FROM revision WHERE rev_page = ?)"""
  416. result = self.site.sql_query(query, (pageid,))
  417. c_user, c_time, c_id = list(result)[0]
  418. return c_user, datetime.strptime(c_time, "%Y%m%d%H%M%S"), c_id
  419. def get_modify(self, pageid):
  420. """Return information about a page's last edit ("modification").
  421. This consists of the most recent editor, modification time, and the
  422. lastest revision ID.
  423. """
  424. query = """SELECT rev_user_text, rev_timestamp, rev_id FROM revision
  425. JOIN page ON rev_id = page_latest WHERE page_id = ?"""
  426. result = self.site.sql_query(query, (pageid,))
  427. m_user, m_time, m_id = list(result)[0]
  428. return m_user, datetime.strptime(m_time, "%Y%m%d%H%M%S"), m_id
  429. def get_special(self, pageid, chart):
  430. """Return information about a page's "special" edit.
  431. I tend to use the term "special" as a verb a lot, which is bound to
  432. cause confusion. It is merely a short way of saying "the edit in which
  433. a declined submission was declined, an accepted submission was
  434. accepted, a submission in review was set as such, and a pending draft
  435. was submitted."
  436. This "information" consists of the special edit's editor, its time, and
  437. its revision ID. If the page's status is not something that involves
  438. "special"-ing, we will return None for all three. The same will be
  439. returned if we cannot determine when the page was "special"-ed, or if
  440. it was "special"-ed more than 250 edits ago.
  441. """
  442. if chart in [CHART_NONE, CHART_PEND]:
  443. return None, None, None
  444. elif chart == CHART_ACCEPT:
  445. return self.get_create(pageid)
  446. elif chart == CHART_DRAFT:
  447. search = "\{\{afc submission\|h\|(.*?)\}\}"
  448. elif chart == CHART_REVIEW:
  449. search = "\{\{afc submission\|r\|(.*?)\}\}"
  450. elif chart == CHART_DECLINE:
  451. search = "\{\{afc submission\|d\|(.*?)\}\}"
  452. query = """SELECT rev_user_text, rev_timestamp, rev_id
  453. FROM revision WHERE rev_page = ? ORDER BY rev_id DESC"""
  454. result = self.site.sql_query(query, (pageid,))
  455. counter = 0
  456. last = (None, None, None)
  457. for user, ts, revid in result:
  458. counter += 1
  459. if counter > 250:
  460. msg = "Exceeded 250 content lookups while determining special for page (id: {0}, chart: {1})"
  461. self.logger.warn(msg.format(pageid, chart))
  462. return None, None, None
  463. content = self.get_revision_content(revid)
  464. if content and not re.search(search, content, re.I):
  465. return last
  466. last = (user, datetime.strptime(ts, "%Y%m%d%H%M%S"), revid)
  467. return last
  468. def get_notes(self, content, m_time, c_user):
  469. """Return any special notes or warnings about this page.
  470. Currently unimplemented, so always returns None.
  471. """
  472. # accepted subs
  473. # rebuild action
  474. # resubmit submission was resubmitted after a previous decline
  475. # re.search("\{\{afc submission\|d\|(.*?)\}\}", content, re.I)
  476. # short submission is less than X bytes
  477. # len(content) < X
  478. # no-inline submission has no inline citations
  479. # not re.search("\<ref\s*(.*?)\>(.*?)\</ref\>", content, re.I|re.S)
  480. # unsourced submission lacks references completely
  481. # not re.search(references, content, re.I|re.S) and search(hyperlinks)
  482. # old submission has not been touched in > 4 days
  483. # m_time < now - 4 hours
  484. # blocked submitter is currently blocked
  485. # c_user is blocked via API
  486. return ""