Additional IRC commands and bot tasks for EarwigBot https://en.wikipedia.org/wiki/User:EarwigBot
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

afc_statistics.py 34 KiB

11 år sedan
10 år sedan
11 år sedan
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2009-2019 Ben Kurtovic <ben.kurtovic@gmail.com>
  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 collections import OrderedDict
  23. from datetime import datetime
  24. import re
  25. from os.path import expanduser
  26. from threading import Lock
  27. from time import sleep
  28. import mwparserfromhell
  29. import oursql
  30. from earwigbot import exceptions
  31. from earwigbot import wiki
  32. from earwigbot.tasks import Task
  33. _DEFAULT_PAGE_TEXT = """<noinclude><!-- You can edit anything on this page \
  34. except for content inside of <!-- stat begin/end -> and <!-- sig begin/end -> \
  35. without causing problems. Most of the chart can be modified by editing the \
  36. templates it uses, documented in [[Template:AFC statistics/doc]]. -->
  37. {{NOINDEX}}</noinclude>
  38. <!-- stat begin --><!-- stat end -->
  39. <span style="font-style: italic; font-weight: bold;">Last updated by \
  40. {{#ifeq:{{REVISIONUSER:Template:AFC statistics}}|EarwigBot|<!-- sig begin -->\
  41. <!-- sig end -->|{{User|{{REVISIONUSER:Template:AFC statistics}}}} at \
  42. {{#time:H:i, j F Y "(UTC)"|{{REVISIONTIMESTAMP:Template:AFC statistics}}}}}}\
  43. </span><noinclude>
  44. {{Documentation}}</noinclude>
  45. """
  46. class AFCStatistics(Task):
  47. """A task to generate statistics for WikiProject Articles for Creation.
  48. Statistics are stored in a MySQL database ("u_earwig_afc_statistics")
  49. accessed with oursql. Statistics are synchronied with the live database
  50. every four minutes and saved once an hour, on the hour, to subpages of
  51. self.pageroot. In the live bot, this is "Template:AFC statistics".
  52. """
  53. name = "afc_statistics"
  54. number = 2
  55. # Chart status number constants:
  56. CHART_NONE = 0
  57. CHART_PEND = 1
  58. CHART_REVIEW = 3
  59. CHART_ACCEPT = 4
  60. CHART_DECLINE = 5
  61. CHART_MISPLACE = 6
  62. def setup(self):
  63. self.cfg = cfg = self.config.tasks.get(self.name, {})
  64. self.site = self.bot.wiki.get_site()
  65. self.revision_cache = {}
  66. # Set some wiki-related attributes:
  67. self.pageroot = cfg.get("page", "Template:AFC statistics")
  68. self.pending_cat = cfg.get("pending", "Pending AfC submissions")
  69. self.ignore_list = cfg.get("ignoreList", [])
  70. default_summary = "Updating statistics for [[WP:WPAFC|WikiProject Articles for creation]]."
  71. self.summary = self.make_summary(cfg.get("summary", default_summary))
  72. # Templates used in chart generation:
  73. templates = cfg.get("templates", {})
  74. self.tl_header = templates.get("header", "AFC statistics/header")
  75. self.tl_row = templates.get("row", "#invoke:AfC|row")
  76. self.tl_footer = templates.get("footer", "AFC statistics/footer")
  77. # Connection data for our SQL database:
  78. kwargs = cfg.get("sql", {})
  79. kwargs["read_default_file"] = expanduser("~/.my.cnf")
  80. self.conn_data = kwargs
  81. self.db_access_lock = Lock()
  82. def run(self, **kwargs):
  83. """Entry point for a task event.
  84. Depending on the kwargs passed, we will either synchronize our local
  85. statistics database with the site (self.sync()) or save it to the wiki
  86. (self.save()). We will additionally create an SQL connection with our
  87. local database.
  88. """
  89. action = kwargs.get("action")
  90. if not self.db_access_lock.acquire(False): # Non-blocking
  91. if action == "sync":
  92. self.logger.info("A sync is already ongoing; aborting")
  93. return
  94. self.logger.info("Waiting for database access lock")
  95. self.db_access_lock.acquire()
  96. try:
  97. self.site = self.bot.wiki.get_site()
  98. self.conn = oursql.connect(**self.conn_data)
  99. self.revision_cache = {}
  100. try:
  101. if action == "save":
  102. self.save(kwargs)
  103. elif action == "sync":
  104. self.sync(kwargs)
  105. finally:
  106. self.conn.close()
  107. finally:
  108. self.db_access_lock.release()
  109. #################### CHART BUILDING AND SAVING METHODS ####################
  110. def save(self, kwargs):
  111. """Save our local statistics to the wiki.
  112. After checking for emergency shutoff, the statistics chart is compiled,
  113. and then saved to subpages of self.pageroot using self.summary iff it
  114. has changed since last save.
  115. """
  116. self.logger.info("Saving chart")
  117. if kwargs.get("fromIRC"):
  118. summary = self.summary + " (!earwigbot)"
  119. else:
  120. if self.shutoff_enabled():
  121. return
  122. summary = self.summary
  123. statistics = self._compile_charts()
  124. for name, chart in statistics.iteritems():
  125. self._save_page(name, chart)
  126. def _save_page(self, name, chart):
  127. """Save a statistics chart to a single page."""
  128. page = self.site.get_page(u"{}/{}".format(self.pageroot, name))
  129. try:
  130. text = page.get()
  131. except exceptions.PageNotFoundError:
  132. text = _DEFAULT_PAGE_TEXT
  133. newtext = re.sub(u"<!-- stat begin -->(.*?)<!-- stat end -->",
  134. "<!-- stat begin -->\n" + chart + "\n<!-- stat end -->",
  135. text, flags=re.DOTALL)
  136. if newtext == text:
  137. self.logger.info(u"Chart for {} unchanged; not saving".format(name))
  138. return
  139. newtext = re.sub("<!-- sig begin -->(.*?)<!-- sig end -->",
  140. "<!-- sig begin -->~~~ at ~~~~~<!-- sig end -->",
  141. newtext)
  142. page.edit(newtext, summary, minor=True, bot=True)
  143. self.logger.info(u"Chart for {} saved to [[{}]]".format(name, page.title))
  144. def _compile_charts(self):
  145. """Compile and return all statistics information from our local db."""
  146. stats = OrderedDict()
  147. with self.conn.cursor(oursql.DictCursor) as cursor:
  148. cursor.execute("SELECT * FROM chart")
  149. for chart in cursor:
  150. name = chart['chart_name']
  151. stats[name] = self._compile_chart(chart)
  152. return stats
  153. def _compile_chart(self, chart_info):
  154. """Compile and return a single statistics chart."""
  155. chart = self.tl_header + "|" + chart_info['chart_title']
  156. if chart_info['chart_special_title']:
  157. chart += "|" + chart_info['chart_special_title']
  158. chart = "{{" + chart + "}}"
  159. query = "SELECT * FROM page JOIN row ON page_id = row_id WHERE row_chart = ?"
  160. with self.conn.cursor(oursql.DictCursor) as cursor:
  161. cursor.execute(query, (chart_info['chart_id'],))
  162. for page in cursor.fetchall():
  163. chart += "\n" + self._compile_chart_row(page)
  164. chart += "\n{{" + self.tl_footer + "}}"
  165. return chart
  166. def _compile_chart_row(self, page):
  167. """Compile and return a single chart row.
  168. 'page' is a dict of page information, taken as a row from the page
  169. table, where keys are column names and values are their cell contents.
  170. """
  171. row = u"{0}|s={page_status}|t={page_title}|z={page_size}|"
  172. if page["page_special_oldid"]:
  173. row += "sr={page_special_user}|sd={page_special_time}|si={page_special_oldid}|"
  174. row += "mr={page_modify_user}|md={page_modify_time}|mi={page_modify_oldid}"
  175. page["page_special_time"] = self._fmt_time(page["page_special_time"])
  176. page["page_modify_time"] = self._fmt_time(page["page_modify_time"])
  177. if page["page_notes"]:
  178. row += "|n=1{page_notes}"
  179. return "{{" + row.format(self.tl_row, **page) + "}}"
  180. def _fmt_time(self, date):
  181. """Format a datetime into the standard MediaWiki timestamp format."""
  182. return date.strftime("%H:%M, %d %b %Y")
  183. ######################## PRIMARY SYNC ENTRY POINTS ########################
  184. def sync(self, kwargs):
  185. """Synchronize our local statistics database with the site.
  186. Syncing involves, in order, updating tracked submissions that have
  187. been changed since last sync (self._update_tracked()), adding pending
  188. submissions that are not tracked (self._add_untracked()), and removing
  189. old submissions from the database (self._delete_old()).
  190. The sync will be canceled if SQL replication lag is greater than 600
  191. seconds, because this will lead to potential problems and outdated
  192. data, not to mention putting demand on an already overloaded server.
  193. Giving sync the kwarg "ignore_replag" will go around this restriction.
  194. """
  195. self.logger.info("Starting sync")
  196. replag = self.site.get_replag()
  197. self.logger.debug("Server replag is {0}".format(replag))
  198. if replag > 600 and not kwargs.get("ignore_replag"):
  199. msg = "Sync canceled as replag ({0} secs) is greater than ten minutes"
  200. self.logger.warn(msg.format(replag))
  201. return
  202. with self.conn.cursor() as cursor:
  203. self._update_tracked(cursor)
  204. self._add_untracked(cursor)
  205. self._update_stale(cursor)
  206. self._delete_old(cursor)
  207. self.logger.info("Sync completed")
  208. def _update_tracked(self, cursor):
  209. """Update tracked submissions that have been changed since last sync.
  210. This is done by iterating through every page in our database and
  211. comparing our stored latest revision ID with the actual latest revision
  212. ID from an SQL query. If they differ, we will update our information
  213. about the page (self._update_page()).
  214. If the page does not exist, we will remove it from our database with
  215. self._untrack_page().
  216. """
  217. self.logger.debug("Updating tracked submissions")
  218. query1 = """SELECT page_id, page_title, page_modify_oldid
  219. FROM page"""
  220. query2 = """SELECT page_latest, page_title, page_namespace
  221. FROM page WHERE page_id = ?"""
  222. cursor.execute(query1)
  223. for pageid, title, oldid in cursor.fetchall():
  224. result = list(self.site.sql_query(query2, (pageid,)))
  225. if not result:
  226. self._untrack_page(cursor, pageid)
  227. continue
  228. real_oldid, real_title, real_ns = result[0]
  229. if oldid == real_oldid:
  230. continue
  231. msg = u"Updating page [[{0}]] (id: {1}) @ {2}"
  232. self.logger.debug(msg.format(title, pageid, oldid))
  233. msg = u" {0}: oldid: {1} -> {2}"
  234. self.logger.debug(msg.format(pageid, oldid, real_oldid))
  235. real_title = real_title.decode("utf8").replace("_", " ")
  236. ns = self.site.namespace_id_to_name(real_ns)
  237. if ns:
  238. real_title = u":".join((ns, real_title))
  239. try:
  240. self._update_page(cursor, pageid, real_title)
  241. except Exception:
  242. e = u"Error updating page [[{0}]] (id: {1})"
  243. self.logger.exception(e.format(real_title, pageid))
  244. def _add_untracked(self, cursor):
  245. """Add pending submissions that are not yet tracked.
  246. This is done by compiling a list of all currently tracked submissions
  247. and iterating through all members of self.pending_cat via SQL. If a
  248. page in the pending category is not tracked and is not in
  249. self.ignore_list, we will track it with self._track_page().
  250. """
  251. self.logger.debug("Adding untracked pending submissions")
  252. query1 = "SELECT page_id FROM page"
  253. query2 = """SELECT page_id, page_title, page_namespace
  254. FROM page
  255. INNER JOIN categorylinks ON page_id = cl_from
  256. WHERE cl_to = ?"""
  257. cursor.execute(query1)
  258. tracked = [pid for (pid,) in cursor.fetchall()]
  259. pend_cat = self.pending_cat.replace(" ", "_")
  260. for pageid, title, ns in self.site.sql_query(query2, (pend_cat,)):
  261. if pageid in tracked:
  262. continue
  263. title = title.decode("utf8").replace("_", " ")
  264. ns_name = self.site.namespace_id_to_name(ns)
  265. if ns_name:
  266. title = u":".join((ns_name, title))
  267. if title in self.ignore_list or ns == wiki.NS_CATEGORY:
  268. continue
  269. msg = u"Tracking page [[{0}]] (id: {1})".format(title, pageid)
  270. self.logger.debug(msg)
  271. try:
  272. self._track_page(cursor, pageid, title)
  273. except Exception:
  274. e = u"Error tracking page [[{0}]] (id: {1})"
  275. self.logger.exception(e.format(title, pageid))
  276. def _update_stale(self, cursor):
  277. """Update submissions that haven't been updated in a long time.
  278. This is intended to update notes that change without typical update
  279. triggers, like when submitters are blocked. It also resolves conflicts
  280. when pages are tracked during high replag, potentially causing data to
  281. be inaccurate (like a missed decline). It updates no more than the ten
  282. stalest pages that haven't been updated in two days.
  283. """
  284. self.logger.debug("Updating stale submissions")
  285. query = """SELECT page_id, page_title, page_modify_oldid
  286. FROM page JOIN updatelog ON page_id = update_id
  287. WHERE ADDTIME(update_time, '48:00:00') < NOW()
  288. ORDER BY update_time ASC LIMIT 10"""
  289. cursor.execute(query)
  290. for pageid, title, oldid in cursor:
  291. msg = u"Updating page [[{0}]] (id: {1}) @ {2}"
  292. self.logger.debug(msg.format(title, pageid, oldid))
  293. try:
  294. self._update_page(cursor, pageid, title)
  295. except Exception:
  296. e = u"Error updating page [[{0}]] (id: {1})"
  297. self.logger.exception(e.format(title, pageid))
  298. def _delete_old(self, cursor):
  299. """Remove old submissions from the database.
  300. "Old" is defined as a submission that has been declined or accepted
  301. more than 36 hours ago. Pending submissions cannot be "old".
  302. """
  303. self.logger.debug("Removing old submissions from chart")
  304. query = """DELETE FROM page, row, updatelog USING page JOIN row
  305. ON page_id = row_id JOIN updatelog ON page_id = update_id
  306. WHERE row_chart IN (?, ?)
  307. AND ADDTIME(page_special_time, '36:00:00') < NOW()"""
  308. cursor.execute(query, (self.CHART_ACCEPT, self.CHART_DECLINE))
  309. ######################## PRIMARY PAGE ENTRY POINTS ########################
  310. def _untrack_page(self, cursor, pageid):
  311. """Remove a page, given by ID, from our database."""
  312. self.logger.debug("Untracking page (id: {0})".format(pageid))
  313. query = """DELETE FROM page, row, updatelog USING page JOIN row
  314. ON page_id = row_id JOIN updatelog ON page_id = update_id
  315. WHERE page_id = ?"""
  316. cursor.execute(query, (pageid,))
  317. def _track_page(self, cursor, pageid, title):
  318. """Update hook for when page is not in our database.
  319. A variety of SQL queries are used to gather information about the page,
  320. which is then saved to our database.
  321. """
  322. content = self._get_content(pageid)
  323. if content is None:
  324. msg = u"Could not get page content for [[{0}]]".format(title)
  325. self.logger.error(msg)
  326. return
  327. namespace = self.site.get_page(title).namespace
  328. status, chart = self._get_status_and_chart(content, namespace)
  329. if chart == self.CHART_NONE:
  330. msg = u"Could not find a status for [[{0}]]".format(title)
  331. self.logger.warn(msg)
  332. return
  333. m_user, m_time, m_id = self._get_modify(pageid)
  334. s_user, s_time, s_id = self._get_special(pageid, content, chart)
  335. notes = self._get_notes(chart, content, m_time, s_user)
  336. query1 = "INSERT INTO row VALUES (?, ?)"
  337. query2 = "INSERT INTO page VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
  338. query3 = "INSERT INTO updatelog VALUES (?, ?)"
  339. cursor.execute(query1, (pageid, chart))
  340. cursor.execute(query2, (pageid, status, title, len(content), notes,
  341. m_user, m_time, m_id, s_user, s_time, s_id))
  342. cursor.execute(query3, (pageid, datetime.utcnow()))
  343. def _update_page(self, cursor, pageid, title):
  344. """Update hook for when page is already in our database.
  345. A variety of SQL queries are used to gather information about the page,
  346. which is compared against our stored information. Differing information
  347. is then updated.
  348. """
  349. content = self._get_content(pageid)
  350. if content is None:
  351. msg = u"Could not get page content for [[{0}]]".format(title)
  352. self.logger.error(msg)
  353. return
  354. namespace = self.site.get_page(title).namespace
  355. status, chart = self._get_status_and_chart(content, namespace)
  356. if chart == self.CHART_NONE:
  357. self._untrack_page(cursor, pageid)
  358. return
  359. query = "SELECT * FROM page JOIN row ON page_id = row_id WHERE page_id = ?"
  360. with self.conn.cursor(oursql.DictCursor) as dict_cursor:
  361. dict_cursor.execute(query, (pageid,))
  362. result = dict_cursor.fetchall()[0]
  363. m_user, m_time, m_id = self._get_modify(pageid)
  364. if title != result["page_title"]:
  365. self._update_page_title(cursor, result, pageid, title)
  366. if m_id != result["page_modify_oldid"]:
  367. self._update_page_modify(cursor, result, pageid, len(content),
  368. m_user, m_time, m_id)
  369. if status != result["page_status"]:
  370. special = self._update_page_status(cursor, result, pageid, content,
  371. status, chart)
  372. s_user = special[0]
  373. else:
  374. s_user = result["page_special_user"]
  375. notes = self._get_notes(chart, content, m_time, s_user)
  376. if notes != result["page_notes"]:
  377. self._update_page_notes(cursor, result, pageid, notes)
  378. query = "UPDATE updatelog SET update_time = ? WHERE update_id = ?"
  379. cursor.execute(query, (datetime.utcnow(), pageid))
  380. ###################### PAGE ATTRIBUTE UPDATE METHODS ######################
  381. def _update_page_title(self, cursor, result, pageid, title):
  382. """Update the title of a page in our database."""
  383. query = "UPDATE page SET page_title = ? WHERE page_id = ?"
  384. cursor.execute(query, (title, pageid))
  385. msg = u" {0}: title: {1} -> {2}"
  386. self.logger.debug(msg.format(pageid, result["page_title"], title))
  387. def _update_page_modify(self, cursor, result, pageid, size, m_user, m_time, m_id):
  388. """Update the last modified information of a page in our database."""
  389. query = """UPDATE page SET page_size = ?, page_modify_user = ?,
  390. page_modify_time = ?, page_modify_oldid = ?
  391. WHERE page_id = ?"""
  392. cursor.execute(query, (size, m_user, m_time, m_id, pageid))
  393. msg = u" {0}: modify: {1} / {2} / {3} -> {4} / {5} / {6}"
  394. msg = msg.format(pageid, result["page_modify_user"],
  395. result["page_modify_time"],
  396. result["page_modify_oldid"], m_user, m_time, m_id)
  397. self.logger.debug(msg)
  398. def _update_page_status(self, cursor, result, pageid, content, status, chart):
  399. """Update the status and "specialed" information of a page."""
  400. query1 = """UPDATE page JOIN row ON page_id = row_id
  401. SET page_status = ?, row_chart = ? WHERE page_id = ?"""
  402. query2 = """UPDATE page SET page_special_user = ?,
  403. page_special_time = ?, page_special_oldid = ?
  404. WHERE page_id = ?"""
  405. cursor.execute(query1, (status, chart, pageid))
  406. msg = " {0}: status: {1} ({2}) -> {3} ({4})"
  407. self.logger.debug(msg.format(pageid, result["page_status"],
  408. result["row_chart"], status, chart))
  409. s_user, s_time, s_id = self._get_special(pageid, content, chart)
  410. if s_id != result["page_special_oldid"]:
  411. cursor.execute(query2, (s_user, s_time, s_id, pageid))
  412. msg = u" {0}: special: {1} / {2} / {3} -> {4} / {5} / {6}"
  413. msg = msg.format(pageid, result["page_special_user"],
  414. result["page_special_time"],
  415. result["page_special_oldid"], s_user, s_time, s_id)
  416. self.logger.debug(msg)
  417. return s_user, s_time, s_id
  418. def _update_page_notes(self, cursor, result, pageid, notes):
  419. """Update the notes (or warnings) of a page in our database."""
  420. query = "UPDATE page SET page_notes = ? WHERE page_id = ?"
  421. cursor.execute(query, (notes, pageid))
  422. msg = " {0}: notes: {1} -> {2}"
  423. self.logger.debug(msg.format(pageid, result["page_notes"], notes))
  424. ###################### DATA RETRIEVAL HELPER METHODS ######################
  425. def _get_content(self, pageid):
  426. """Get the current content of a page by ID from the API.
  427. The page's current revision ID is retrieved from SQL, and then
  428. an API query is made to get its content. This is the only API query
  429. used in the task's code.
  430. """
  431. query = "SELECT page_latest FROM page WHERE page_id = ?"
  432. result = self.site.sql_query(query, (pageid,))
  433. try:
  434. revid = int(list(result)[0][0])
  435. except IndexError:
  436. return None
  437. return self._get_revision_content(revid)
  438. def _get_revision_content(self, revid, tries=1):
  439. """Get the content of a revision by ID from the API."""
  440. if revid in self.revision_cache:
  441. return self.revision_cache[revid]
  442. res = self.site.api_query(action="query", prop="revisions",
  443. rvprop="content", rvslots="main",
  444. revids=revid)
  445. try:
  446. revision = res["query"]["pages"].values()[0]["revisions"][0]
  447. content = revision["slots"]["main"]["*"]
  448. except KeyError:
  449. if tries == 0:
  450. raise
  451. sleep(5)
  452. return self._get_revision_content(revid, tries=tries - 1)
  453. self.revision_cache[revid] = content
  454. return content
  455. def _get_status_and_chart(self, content, namespace):
  456. """Determine the status and chart number of an AFC submission.
  457. The methodology used here is the same one I've been using for years
  458. (see also commands.afc_report), but with the new draft system taken
  459. into account. The order here is important: if there is more than one
  460. {{AFC submission}} template on a page, we need to know which one to
  461. use (revision history search to find the most recent isn't a viable
  462. idea :P).
  463. """
  464. statuses = self.get_statuses(content)
  465. if namespace == wiki.NS_MAIN:
  466. if statuses:
  467. return None, self.CHART_MISPLACE
  468. return "a", self.CHART_ACCEPT
  469. elif "R" in statuses:
  470. return "r", self.CHART_REVIEW
  471. elif "P" in statuses:
  472. return "p", self.CHART_PEND
  473. elif "T" in statuses:
  474. return None, self.CHART_NONE
  475. elif "D" in statuses:
  476. return "d", self.CHART_DECLINE
  477. return None, self.CHART_NONE
  478. def get_statuses(self, content):
  479. """Return a list of all AFC submission statuses in a page's text."""
  480. valid = ["P", "R", "T", "D"]
  481. aliases = {
  482. "submit": "P",
  483. "afc submission/submit": "P",
  484. "afc submission/reviewing": "R",
  485. "afc submission/pending": "P",
  486. "afc submission/draft": "T",
  487. "afc submission/declined": "D"
  488. }
  489. statuses = []
  490. code = mwparserfromhell.parse(content)
  491. for template in code.filter_templates():
  492. name = template.name.strip().lower()
  493. if name == "afc submission":
  494. if template.has(1, ignore_empty=True):
  495. status = template.get(1).value.strip().upper()
  496. statuses.append(status if status in valid else "P")
  497. else:
  498. statuses.append("P")
  499. elif name in aliases:
  500. statuses.append(aliases[name])
  501. return statuses
  502. def _get_modify(self, pageid):
  503. """Return information about a page's last edit ("modification").
  504. This consists of the most recent editor, modification time, and the
  505. lastest revision ID.
  506. """
  507. query = """SELECT actor_name, rev_timestamp, rev_id
  508. FROM revision
  509. JOIN page ON rev_id = page_latest
  510. JOIN actor ON rev_actor = actor_id
  511. WHERE page_id = ?"""
  512. result = self.site.sql_query(query, (pageid,))
  513. m_user, m_time, m_id = list(result)[0]
  514. timestamp = datetime.strptime(m_time, "%Y%m%d%H%M%S")
  515. return m_user.decode("utf8"), timestamp, m_id
  516. def _get_special(self, pageid, content, chart):
  517. """Return information about a page's "special" edit.
  518. I tend to use the term "special" as a verb a lot, which is bound to
  519. cause confusion. It is merely a short way of saying "the edit in which
  520. a declined submission was declined, an accepted submission was
  521. accepted, a submission in review was set as such, a pending submission
  522. was submitted, and a "misplaced" submission was created."
  523. This "information" consists of the special edit's editor, its time, and
  524. its revision ID. If the page's status is not something that involves
  525. "special"-ing, we will return None for all three. The same will be
  526. returned if we cannot determine when the page was "special"-ed.
  527. """
  528. charts = {
  529. self.CHART_NONE: (lambda pageid, content: None, None, None),
  530. self.CHART_MISPLACE: self.get_create,
  531. self.CHART_ACCEPT: self.get_accepted,
  532. self.CHART_REVIEW: self.get_reviewing,
  533. self.CHART_PEND: self.get_pending,
  534. self.CHART_DECLINE: self.get_decline
  535. }
  536. return charts[chart](pageid, content)
  537. def get_create(self, pageid, content=None):
  538. """Return (creator, create_ts, create_revid) for the given page."""
  539. query = """SELECT actor_name, rev_timestamp, rev_id
  540. FROM revision
  541. JOIN actor ON rev_actor = actor_id
  542. WHERE rev_id = (SELECT MIN(rev_id) FROM revision WHERE rev_page = ?)"""
  543. result = self.site.sql_query(query, (pageid,))
  544. c_user, c_time, c_id = list(result)[0]
  545. timestamp = datetime.strptime(c_time, "%Y%m%d%H%M%S")
  546. return c_user.decode("utf8"), timestamp, c_id
  547. def get_accepted(self, pageid, content=None):
  548. """Return (acceptor, accept_ts, accept_revid) for the given page."""
  549. query = """SELECT actor_name, rev_timestamp, rev_id
  550. FROM revision
  551. JOIN actor ON rev_actor = actor_id
  552. JOIN comment ON rev_comment_id = comment_id
  553. WHERE rev_page = ?
  554. AND comment_text LIKE "% moved page [[%]] to [[%]]%"
  555. ORDER BY rev_timestamp DESC LIMIT 1"""
  556. result = self.site.sql_query(query, (pageid,))
  557. try:
  558. a_user, a_time, a_id = list(result)[0]
  559. except IndexError:
  560. return None, None, None
  561. timestamp = datetime.strptime(a_time, "%Y%m%d%H%M%S")
  562. return a_user.decode("utf8"), timestamp, a_id
  563. def get_reviewing(self, pageid, content=None):
  564. """Return (reviewer, review_ts, review_revid) for the given page."""
  565. return self._search_history(pageid, self.CHART_REVIEW, ["R"], [])
  566. def get_pending(self, pageid, content):
  567. """Return (submitter, submit_ts, submit_revid) for the given page."""
  568. res = self._get_status_helper(pageid, content, ("P", ""), ("u", "ts"))
  569. return res or self._search_history(pageid, self.CHART_PEND, ["P"], [])
  570. def get_decline(self, pageid, content):
  571. """Return (decliner, decline_ts, decline_revid) for the given page."""
  572. params = ("decliner", "declinets")
  573. res = self._get_status_helper(pageid, content, ("D"), params)
  574. return res or self._search_history(
  575. pageid, self.CHART_DECLINE, ["D"], ["R", "P", "T"])
  576. def _get_status_helper(self, pageid, content, statuses, params):
  577. """Helper function for get_pending() and get_decline()."""
  578. submits = []
  579. code = mwparserfromhell.parse(content)
  580. for tmpl in code.filter_templates():
  581. status = tmpl.get(1).value.strip().upper() if tmpl.has(1) else "P"
  582. if tmpl.name.strip().lower() == "afc submission":
  583. if all([tmpl.has(par, ignore_empty=True) for par in params]):
  584. if status in statuses:
  585. data = [unicode(tmpl.get(par).value) for par in params]
  586. submits.append(data)
  587. if not submits:
  588. return None
  589. user, stamp = max(submits, key=lambda pair: pair[1])
  590. query = """SELECT rev_id
  591. FROM revision_userindex
  592. JOIN actor ON rev_actor = actor_id
  593. WHERE rev_page = ? AND actor_name = ? AND ABS(rev_timestamp - ?) <= 60
  594. ORDER BY ABS(rev_timestamp - ?) ASC LIMIT 1"""
  595. result = self.site.sql_query(query, (pageid, user, stamp, stamp))
  596. try:
  597. dtime = datetime.strptime(stamp, "%Y%m%d%H%M%S")
  598. return user, dtime, list(result)[0][0]
  599. except (ValueError, IndexError):
  600. return None
  601. def _search_history(self, pageid, chart, search_with, search_without):
  602. """Search through a page's history to find when a status was set.
  603. Linear search backwards in time for the edit right after the most
  604. recent edit that fails the (pseudocode) test:
  605. ``status_set(any(search_with)) && !status_set(any(search_without))``
  606. """
  607. query = """SELECT actor_name, rev_timestamp, rev_id
  608. FROM revision
  609. JOIN actor ON rev_actor = actor_id
  610. WHERE rev_page = ? ORDER BY rev_id DESC"""
  611. result = self.site.sql_query(query, (pageid,))
  612. counter = 0
  613. last = (None, None, None)
  614. for user, ts, revid in result:
  615. counter += 1
  616. if counter > 50:
  617. msg = "Exceeded 50 content lookups while searching history of page (id: {0}, chart: {1})"
  618. self.logger.warn(msg.format(pageid, chart))
  619. return None, None, None
  620. try:
  621. content = self._get_revision_content(revid)
  622. except exceptions.APIError:
  623. msg = "API error interrupted SQL query in _search_history() for page (id: {0}, chart: {1})"
  624. self.logger.exception(msg.format(pageid, chart))
  625. return None, None, None
  626. statuses = self.get_statuses(content)
  627. req = search_with and not any([s in statuses for s in search_with])
  628. if any([s in statuses for s in search_without]) or req:
  629. return last
  630. timestamp = datetime.strptime(ts, "%Y%m%d%H%M%S")
  631. last = (user.decode("utf8"), timestamp, revid)
  632. return last
  633. def _get_notes(self, chart, content, m_time, s_user):
  634. """Return any special notes or warnings about this page.
  635. copyvio: submission is a suspected copyright violation
  636. unsourced: submission lacks references completely
  637. no-inline: submission has no inline citations
  638. short: submission is less than a kilobyte in length
  639. resubmit: submission was resubmitted after a previous decline
  640. old: submission has not been touched in > 4 days
  641. rejected: submission was rejected, a more severe form of declined
  642. blocked: submitter is currently blocked
  643. """
  644. notes = ""
  645. ignored_charts = [self.CHART_NONE, self.CHART_ACCEPT]
  646. if chart in ignored_charts:
  647. return notes
  648. if chart == self.CHART_DECLINE:
  649. # Decline is special, as only the rejected note is meaningful
  650. code = mwparserfromhell.parse(content)
  651. for tmpl in code.filter_templates():
  652. if tmpl.name.strip().lower() == "afc submission":
  653. if tmpl.has("reject") and tmpl.get("reject").value:
  654. notes += "|nj=1" # Submission was rejected
  655. break
  656. return notes
  657. copyvios = self.config.tasks.get("afc_copyvios", {})
  658. regex = r"\{\{s*" + copyvios.get("template", "AfC suspected copyvio")
  659. if re.search(regex, content):
  660. notes += "|nc=1" # Submission is a suspected copyvio
  661. if not re.search(r"\<ref\s*(.*?)\>(.*?)\</ref\>", content, re.I|re.S):
  662. regex = r"(https?:)|\[//(?!{0})([^ \]\t\n\r\f\v]+?)"
  663. sitedomain = re.escape(self.site.domain)
  664. if re.search(regex.format(sitedomain), content, re.I | re.S):
  665. notes += "|ni=1" # Submission has no inline citations
  666. else:
  667. notes += "|nu=1" # Submission is completely unsourced
  668. if len(content) < 1000:
  669. notes += "|ns=1" # Submission is short
  670. statuses = self.get_statuses(content)
  671. if "D" in statuses and chart != self.CHART_MISPLACE:
  672. notes += "|nr=1" # Submission was resubmitted
  673. time_since_modify = (datetime.utcnow() - m_time).total_seconds()
  674. max_time = 4 * 24 * 60 * 60
  675. if time_since_modify > max_time:
  676. notes += "|no=1" # Submission hasn't been touched in over 4 days
  677. if chart == self.CHART_PEND and s_user:
  678. submitter = self.site.get_user(s_user)
  679. try:
  680. if submitter.blockinfo:
  681. notes += "|nb=1" # Submitter is blocked
  682. except exceptions.UserNotFoundError: # Likely an IP
  683. pass
  684. return notes