A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

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