Additional IRC commands and bot tasks for EarwigBot https://en.wikipedia.org/wiki/User:EarwigBot
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

790 line
35 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2009-2013 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 datetime import datetime
  23. from os.path import expanduser
  24. import re
  25. from threading import RLock
  26. from time import mktime, sleep, time
  27. from mwparserfromhell import parse as mw_parse
  28. import oursql
  29. from earwigbot import exceptions
  30. from earwigbot.tasks import Task
  31. from earwigbot.wiki import constants
  32. class DRNClerkBot(Task):
  33. """A task to clerk for [[WP:DRN]]."""
  34. name = "drn_clerkbot"
  35. number = 19
  36. # Case status:
  37. STATUS_UNKNOWN = 0
  38. STATUS_NEW = 1
  39. STATUS_OPEN = 2
  40. STATUS_STALE = 3
  41. STATUS_NEEDASSIST = 4
  42. STATUS_RESOLVED = 6
  43. STATUS_CLOSED = 7
  44. STATUS_FAILED = 8
  45. ALIASES = {
  46. STATUS_NEW: ("",),
  47. STATUS_OPEN: ("open", "active", "inprogress"),
  48. STATUS_STALE: ("stale",),
  49. STATUS_NEEDASSIST: ("needassist", "review", "relist", "relisted"),
  50. STATUS_RESOLVED: ("resolved", "resolve"),
  51. STATUS_CLOSED: ("closed", "close"),
  52. STATUS_FAILED: ("failed", "fail"),
  53. }
  54. def setup(self):
  55. """Hook called immediately after the task is loaded."""
  56. cfg = self.config.tasks.get(self.name, {})
  57. # Set some wiki-related attributes:
  58. self.title = cfg.get("title",
  59. "Wikipedia:Dispute resolution noticeboard")
  60. self.chart_title = cfg.get("chartTitle", "Template:DRN case status")
  61. self.volunteer_title = cfg.get("volunteers",
  62. "Wikipedia:Dispute resolution noticeboard/Volunteering")
  63. self.very_old_title = cfg.get("veryOldTitle", "User talk:Szhang (WMF)")
  64. self.notify_stale_cases = cfg.get("notifyStaleCases", False)
  65. clerk_summary = "Updating $3 case$4."
  66. notify_summary = "Notifying user regarding [[WP:DRN|dispute resolution noticeboard]] case."
  67. chart_summary = "Updating statistics for the [[WP:DRN|dispute resolution noticeboard]]."
  68. self.clerk_summary = self.make_summary(cfg.get("clerkSummary", clerk_summary))
  69. self.notify_summary = self.make_summary(cfg.get("notifySummary", notify_summary))
  70. self.chart_summary = self.make_summary(cfg.get("chartSummary", chart_summary))
  71. # Templates used:
  72. templates = cfg.get("templates", {})
  73. self.tl_status = templates.get("status", "DR case status")
  74. self.tl_notify_party = templates.get("notifyParty", "DRN-notice")
  75. self.tl_notify_stale = templates.get("notifyStale", "DRN stale notice")
  76. self.tl_archive_top = templates.get("archiveTop", "DRN archive top")
  77. self.tl_archive_bottom = templates.get("archiveBottom",
  78. "DRN archive bottom")
  79. self.tl_chart_header = templates.get("chartHeader",
  80. "DRN case status/header")
  81. self.tl_chart_row = templates.get("chartRow", "DRN case status/row")
  82. self.tl_chart_footer = templates.get("chartFooter",
  83. "DRN case status/footer")
  84. # Connection data for our SQL database:
  85. kwargs = cfg.get("sql", {})
  86. kwargs["read_default_file"] = expanduser("~/.my.cnf")
  87. self.conn_data = kwargs
  88. self.db_access_lock = RLock()
  89. # Minimum size a MySQL TIMESTAMP field can hold:
  90. self.min_ts = datetime(1970, 1, 1, 0, 0, 1)
  91. def run(self, **kwargs):
  92. """Entry point for a task event."""
  93. if not self.db_access_lock.acquire(False): # Non-blocking
  94. self.logger.info("A job is already ongoing; aborting")
  95. return
  96. action = kwargs.get("action", "all")
  97. try:
  98. start = time()
  99. conn = oursql.connect(**self.conn_data)
  100. site = self.bot.wiki.get_site()
  101. if action in ["all", "update_volunteers"]:
  102. self.update_volunteers(conn, site)
  103. if action in ["all", "clerk"]:
  104. log = u"Starting update to [[{0}]]".format(self.title)
  105. self.logger.info(log)
  106. cases = self.read_database(conn)
  107. page = site.get_page(self.title)
  108. text = page.get()
  109. self.read_page(conn, cases, text)
  110. notices = self.clerk(conn, cases)
  111. if self.shutoff_enabled():
  112. return
  113. if not self.save(page, cases, kwargs, start):
  114. return
  115. self.send_notices(site, notices)
  116. if action in ["all", "update_chart"]:
  117. if self.shutoff_enabled():
  118. return
  119. self.update_chart(conn, site)
  120. if action in ["all", "purge"]:
  121. self.purge_old_data(conn)
  122. finally:
  123. self.db_access_lock.release()
  124. def update_volunteers(self, conn, site):
  125. """Updates and stores the list of dispute resolution volunteers."""
  126. log = u"Updating volunteer list from [[{0}]]"
  127. self.logger.info(log.format(self.volunteer_title))
  128. page = site.get_page(self.volunteer_title)
  129. try:
  130. text = page.get()
  131. except exceptions.PageNotFoundError:
  132. text = ""
  133. marker = "<!-- please don't remove this comment (used by EarwigBot) -->"
  134. if marker not in text:
  135. log = u"The marker ({0}) wasn't found in the volunteer list at [[{1}]]!"
  136. self.logger.error(log.format(marker, page.title))
  137. return
  138. text = text.split(marker)[1]
  139. additions = set()
  140. for line in text.splitlines():
  141. user = re.search("\# \{\{User\|(.+?)\}\}", line)
  142. if user:
  143. uname = user.group(1).replace("_", " ").strip()
  144. additions.add((uname[0].upper() + uname[1:],))
  145. removals = set()
  146. query1 = "SELECT volunteer_username FROM volunteers"
  147. query2 = "DELETE FROM volunteers WHERE volunteer_username = ?"
  148. query3 = "INSERT INTO volunteers (volunteer_username) VALUES (?)"
  149. with conn.cursor() as cursor:
  150. cursor.execute(query1)
  151. for row in cursor:
  152. if row in additions:
  153. additions.remove(row)
  154. else:
  155. removals.add(row)
  156. if removals:
  157. cursor.executemany(query2, removals)
  158. if additions:
  159. cursor.executemany(query3, additions)
  160. def read_database(self, conn):
  161. """Return a list of _Cases from the database."""
  162. cases = []
  163. query = "SELECT * FROM cases"
  164. with conn.cursor() as cursor:
  165. cursor.execute(query)
  166. for row in cursor:
  167. case = _Case(*row)
  168. cases.append(case)
  169. log = "Read {0} cases from the database"
  170. self.logger.debug(log.format(len(cases)))
  171. return cases
  172. def read_page(self, conn, cases, text):
  173. """Read the noticeboard content and update the list of _Cases."""
  174. nextid = self.select_next_id(conn)
  175. tl_status_esc = re.escape(self.tl_status)
  176. split = re.split("(^==\s*[^=]+?\s*==$)", text, flags=re.M|re.U)
  177. for i in xrange(len(split)):
  178. if i + 1 == len(split):
  179. break
  180. if not split[i].startswith("=="):
  181. continue
  182. title = split[i][2:-2].strip()
  183. body = old = split[i + 1]
  184. if not re.search("\s*\{\{" + tl_status_esc, body, re.U):
  185. continue
  186. status = self.read_status(body)
  187. re_id = "<!-- Bot Case ID \(please don't modify\): (.*?) -->"
  188. try:
  189. id_ = int(re.search(re_id, body).group(1))
  190. case = [case for case in cases if case.id == id_][0]
  191. except (AttributeError, IndexError, ValueError):
  192. id_ = nextid
  193. nextid += 1
  194. re_id2 = "(\{\{" + tl_status_esc
  195. re_id2 += r"(.*?)\}\})(<!-- Bot Case ID \(please don't modify\): .*? -->)?"
  196. repl = ur"\1 <!-- Bot Case ID (please don't modify): {0} -->"
  197. body = re.sub(re_id2, repl.format(id_), body)
  198. re_f = r"\{\{drn filing editor\|(.*?)\|"
  199. re_f += r"(\d{2}:\d{2},\s\d{1,2}\s\w+\s\d{4}\s\(UTC\))\}\}"
  200. match = re.search(re_f, body, re.U)
  201. if match:
  202. f_user = match.group(1).split("/", 1)[0].replace("_", " ")
  203. f_user = f_user[0].upper() + f_user[1:]
  204. strp = "%H:%M, %d %B %Y (UTC)"
  205. f_time = datetime.strptime(match.group(2), strp)
  206. else:
  207. f_user, f_time = None, datetime.utcnow()
  208. case = _Case(id_, title, status, self.STATUS_UNKNOWN, f_user,
  209. f_time, f_user, f_time, "", self.min_ts,
  210. self.min_ts, False, False, False, len(body),
  211. new=True)
  212. cases.append(case)
  213. log = u"Added new case {0} ('{1}', status={2}, by {3})"
  214. self.logger.debug(log.format(id_, title, status, f_user))
  215. else:
  216. case.status = status
  217. log = u"Read active case {0} ('{1}')".format(id_, title)
  218. self.logger.debug(log)
  219. if case.title != title:
  220. self.update_case_title(conn, id_, title)
  221. case.title = title
  222. case.body, case.old = body, old
  223. for case in cases[:]:
  224. if case.body is None:
  225. if case.original_status == self.STATUS_UNKNOWN:
  226. cases.remove(case) # Ignore archived case
  227. else:
  228. case.status = self.STATUS_UNKNOWN
  229. log = u"Dropped case {0} because it is no longer on the page ('{1}')"
  230. self.logger.debug(log.format(case.id, case.title))
  231. self.logger.debug("Done reading cases from the noticeboard page")
  232. def select_next_id(self, conn):
  233. """Return the next incremental ID for a case."""
  234. query = "SELECT MAX(case_id) FROM cases"
  235. with conn.cursor() as cursor:
  236. cursor.execute(query)
  237. current = cursor.fetchone()[0]
  238. if current:
  239. return int(current) + 1
  240. return 1
  241. def read_status(self, body):
  242. """Parse the current status from a case body."""
  243. templ = re.escape(self.tl_status)
  244. status = re.search("\{\{" + templ + "\|?(.*?)\}\}", body, re.S|re.U)
  245. if not status:
  246. return self.STATUS_NEW
  247. for option, names in self.ALIASES.iteritems():
  248. if status.group(1).lower() in names:
  249. return option
  250. return self.STATUS_NEW
  251. def update_case_title(self, conn, id_, title):
  252. """Update a case title in the database."""
  253. query = "UPDATE cases SET case_title = ? WHERE case_id = ?"
  254. with conn.cursor() as cursor:
  255. cursor.execute(query, (title, id_))
  256. log = u"Updated title of case {0} to '{1}'".format(id_, title)
  257. self.logger.debug(log)
  258. def clerk(self, conn, cases):
  259. """Actually go through cases and modify those to be updated."""
  260. query = "SELECT volunteer_username FROM volunteers"
  261. with conn.cursor() as cursor:
  262. cursor.execute(query)
  263. volunteers = [name for (name,) in cursor.fetchall()]
  264. notices = []
  265. for case in cases:
  266. log = u"Clerking case {0} ('{1}')".format(case.id, case.title)
  267. self.logger.debug(log)
  268. if case.status == self.STATUS_UNKNOWN:
  269. self.save_existing_case(conn, case)
  270. else:
  271. notices += self.clerk_case(conn, case, volunteers)
  272. self.logger.debug("Done clerking cases")
  273. return notices
  274. def clerk_case(self, conn, case, volunteers):
  275. """Clerk a particular case and return a list of any notices to send."""
  276. notices = []
  277. signatures = self.read_signatures(case.body)
  278. storedsigs = self.get_signatures_from_db(conn, case)
  279. newsigs = set(signatures) - set(storedsigs)
  280. if any([editor in volunteers for (editor, timestamp) in newsigs]):
  281. case.last_volunteer_size = len(case.body)
  282. if case.status == self.STATUS_NEW:
  283. notices = self.clerk_new_case(case, volunteers, signatures)
  284. elif case.status == self.STATUS_OPEN:
  285. notices = self.clerk_open_case(case, signatures)
  286. elif case.status == self.STATUS_NEEDASSIST:
  287. notices = self.clerk_needassist_case(case, volunteers, newsigs)
  288. elif case.status == self.STATUS_STALE:
  289. notices = self.clerk_stale_case(case, newsigs)
  290. elif case.status in [self.STATUS_RESOLVED, self.STATUS_CLOSED,
  291. self.STATUS_FAILED]:
  292. self.clerk_closed_case(case, signatures)
  293. self.save_case_updates(conn, case, volunteers, signatures, storedsigs)
  294. return notices
  295. def clerk_new_case(self, case, volunteers, signatures):
  296. """Clerk a case in the "brand new" state.
  297. The case will be set to "open" if a volunteer edits it, or "needassist"
  298. if it increases by over 15,000 bytes or goes by without any volunteer
  299. edits for two days.
  300. """
  301. notices = self.notify_parties(case)
  302. if any([editor in volunteers for (editor, timestamp) in signatures]):
  303. self.update_status(case, self.STATUS_OPEN)
  304. else:
  305. age = (datetime.utcnow() - case.file_time).total_seconds()
  306. if age > 60 * 60 * 24 * 2:
  307. self.update_status(case, self.STATUS_NEEDASSIST)
  308. elif len(case.body) - case.last_volunteer_size > 15000:
  309. self.update_status(case, self.STATUS_NEEDASSIST)
  310. return notices
  311. def clerk_open_case(self, case, signatures):
  312. """Clerk an open case (has been edited by a reviewer).
  313. The case will be set to "needassist" if 15,000 bytes have been added
  314. since a volunteer last edited or if it has been open for over seven
  315. days, or "stale" if no edits at all have occurred in two days.
  316. """
  317. if self.check_for_needassist(case):
  318. return []
  319. if len(case.body) - case.last_volunteer_size > 15000:
  320. self.update_status(case, self.STATUS_NEEDASSIST)
  321. timestamps = [timestamp for (editor, timestamp) in signatures]
  322. if timestamps:
  323. age = (datetime.utcnow() - max(timestamps)).total_seconds()
  324. if age > 60 * 60 * 24 * 2:
  325. self.update_status(case, self.STATUS_STALE)
  326. return []
  327. def clerk_needassist_case(self, case, volunteers, newsigs):
  328. """Clerk a "needassist" case (no volunteers in 15kb or >= 7 days old).
  329. The case will be set to "open" if a volunteer edits and the case is
  330. less than a week old. A message will be set to the "very old notifiee",
  331. which is generally [[User talk:Szhang (WMF)]], if the case has been
  332. open for more than ten days.
  333. """
  334. age = (datetime.utcnow() - case.file_time).total_seconds()
  335. if age <= 60 * 60 * 24 * 7:
  336. if any([editor in volunteers for (editor, timestamp) in newsigs]):
  337. self.update_status(case, self.STATUS_OPEN)
  338. elif age > 60 * 60 * 24 * 10:
  339. if not case.very_old_notified and self.notify_stale_cases:
  340. tmpl = self.tl_notify_stale
  341. title = case.title.replace("|", "&#124;")
  342. template = "{{subst:" + tmpl + "|" + title + "}}"
  343. miss = "<!-- Template:DRN stale notice | {0} -->".format(title)
  344. notice = _Notice(self.very_old_title, template, miss)
  345. case.very_old_notified = True
  346. msg = u" {0}: will notify [[{1}]] with '{2}'"
  347. log = msg.format(case.id, self.very_old_title, template)
  348. self.logger.debug(log)
  349. return [notice]
  350. return []
  351. def clerk_stale_case(self, case, newsigs):
  352. """Clerk a stale case (no edits in two days).
  353. The case will be set to "open" if anyone edits, or "needassist" if it
  354. has been open for over seven days.
  355. """
  356. if self.check_for_needassist(case):
  357. return []
  358. if newsigs:
  359. self.update_status(case, self.STATUS_OPEN)
  360. return []
  361. def clerk_closed_case(self, case, signatures):
  362. """Clerk a closed or resolved case.
  363. The case will be archived if it has been closed/resolved for more than
  364. one day and no edits have been made in the meantime. "Archiving" is
  365. the process of adding {{DRN archive top}}, {{DRN archive bottom}}, and
  366. removing the [[User:DoNotArchiveUntil]] comment.
  367. """
  368. if case.close_time == self.min_ts:
  369. case.close_time = datetime.utcnow()
  370. if case.archived:
  371. return
  372. timestamps = [timestamp for (editor, timestamp) in signatures]
  373. closed_age = (datetime.utcnow() - case.close_time).total_seconds()
  374. if timestamps:
  375. modify_age = (datetime.utcnow() - max(timestamps)).total_seconds()
  376. else:
  377. modify_age = 0
  378. if closed_age > 60 * 60 * 24 and modify_age > 60 * 60 * 24:
  379. arch_top = self.tl_archive_top
  380. arch_bottom = self.tl_archive_bottom
  381. reg = r"<!-- \[\[User:DoNotArchiveUntil\]\] .*? -->(<!-- .*? -->)?"
  382. if re.search(r"\{\{\s*" + arch_top, case.body):
  383. if re.search(reg, case.body):
  384. case.body = re.sub(reg, "", case.body)
  385. else:
  386. if re.search(reg, case.body):
  387. case.body = re.sub(r"\{\{" + arch_top + r"\}\}", "", case.body)
  388. case.body = re.sub(reg, "{{" + arch_top + "}}", case.body)
  389. if not re.search(arch_bottom + r"\s*\}\}\s*\Z", case.body):
  390. case.body += "\n{{" + arch_bottom + "}}"
  391. case.archived = True
  392. self.logger.debug(u" {0}: archived case".format(case.id))
  393. def check_for_needassist(self, case):
  394. """Check whether a case is old enough to be set to "needassist"."""
  395. age = (datetime.utcnow() - case.file_time).total_seconds()
  396. if age > 60 * 60 * 24 * 7:
  397. self.update_status(case, self.STATUS_NEEDASSIST)
  398. return True
  399. return False
  400. def update_status(self, case, new):
  401. """Safely update the status of a case, so we don't edit war."""
  402. old_n = self.ALIASES[case.status][0].upper()
  403. new_n = self.ALIASES[new][0].upper()
  404. old_n = "NEW" if not old_n else old_n
  405. new_n = "NEW" if not new_n else new_n
  406. if case.last_action != new:
  407. case.status = new
  408. log = u" {0}: {1} -> {2}"
  409. self.logger.debug(log.format(case.id, old_n, new_n))
  410. return
  411. log = u"Avoiding {0} {1} -> {2} because we already did this ('{3}')"
  412. self.logger.info(log.format(case.id, old_n, new_n, case.title))
  413. def read_signatures(self, text):
  414. """Return a list of all parseable signatures in the body of a case.
  415. Signatures are returned as tuples of (editor, timestamp as datetime).
  416. """
  417. regex = r"\[\[(?:User(?:\stalk)?\:|Special\:Contributions\/)"
  418. regex += r"([^\n\[\]|]{,256}?)(?:\||\]\])"
  419. regex += r"(?!.*?(?:User(?:\stalk)?\:|Special\:Contributions\/).*?)"
  420. regex += r".{,256}?(\d{2}:\d{2},\s\d{1,2}\s\w+\s\d{4}\s\(UTC\))"
  421. matches = re.findall(regex, text, re.U|re.I)
  422. signatures = []
  423. for userlink, stamp in matches:
  424. username = userlink.split("/", 1)[0].replace("_", " ").strip()
  425. username = username[0].upper() + username[1:]
  426. if username == "DoNotArchiveUntil":
  427. continue
  428. stamp = stamp.strip()
  429. timestamp = datetime.strptime(stamp, "%H:%M, %d %B %Y (UTC)")
  430. signatures.append((username, timestamp))
  431. return signatures
  432. def get_signatures_from_db(self, conn, case):
  433. """Return a list of signatures in a case from the database.
  434. The return type is the same as read_signatures().
  435. """
  436. query = "SELECT signature_username, signature_timestamp FROM signatures WHERE signature_case = ?"
  437. with conn.cursor() as cursor:
  438. cursor.execute(query, (case.id,))
  439. return cursor.fetchall()
  440. def notify_parties(self, case):
  441. """Schedule notices to be sent to all parties of a case."""
  442. if case.parties_notified:
  443. return []
  444. notices = []
  445. template = "{{subst:" + self.tl_notify_party
  446. template += "|thread=" + case.title + "}} ~~~~"
  447. too_late = "<!--Template:DRN-notice-->"
  448. re_parties = "<span.*?>'''Users involved'''</span>(.*?)<span.*?>"
  449. text = re.search(re_parties, case.body, re.S|re.U)
  450. for line in text.group(1).splitlines():
  451. user = re.search("[:*#]{,5} \{\{User\|(.*?)\}\}", line)
  452. if user:
  453. party = user.group(1).replace("_", " ").strip()
  454. if party:
  455. party = party[0].upper() + party[1:]
  456. if party == case.file_user:
  457. continue
  458. notice = _Notice("User talk:" + party, template, too_late)
  459. notices.append(notice)
  460. case.parties_notified = True
  461. log = u" {0}: will try to notify {1} parties with '{2}'"
  462. self.logger.debug(log.format(case.id, len(notices), template))
  463. return notices
  464. def save_case_updates(self, conn, case, volunteers, sigs, storedsigs):
  465. """Save any updates made to a case and signatures in the database."""
  466. if case.status != case.original_status:
  467. case.last_action = case.status
  468. new = self.ALIASES[case.status][0]
  469. tl_status_esc = re.escape(self.tl_status)
  470. search = "\{\{" + tl_status_esc + "(\|?.*?)\}\}"
  471. repl = "{{" + self.tl_status + "|" + new + "}}"
  472. case.body = re.sub(search, repl, case.body)
  473. if sigs:
  474. newest_ts = max([stamp for (user, stamp) in sigs])
  475. newest_user = [usr for (usr, stamp) in sigs if stamp == newest_ts][0]
  476. case.modify_time = newest_ts
  477. case.modify_user = newest_user
  478. if any([usr in volunteers for (usr, stamp) in sigs]):
  479. newest_vts = max([stamp for (usr, stamp) in sigs if usr in volunteers])
  480. newest_vuser = [usr for (usr, stamp) in sigs if stamp == newest_vts][0]
  481. case.volunteer_time = newest_vts
  482. case.volunteer_user = newest_vuser
  483. if case.new:
  484. self.save_new_case(conn, case)
  485. else:
  486. self.save_existing_case(conn, case)
  487. with conn.cursor() as cursor:
  488. query1 = "DELETE FROM signatures WHERE signature_case = ? AND signature_username = ? AND signature_timestamp = ?"
  489. query2 = "INSERT INTO signatures (signature_case, signature_username, signature_timestamp) VALUES (?, ?, ?)"
  490. removals = set(storedsigs) - set(sigs)
  491. additions = set(sigs) - set(storedsigs)
  492. if removals:
  493. args = [(case.id, name, stamp) for (name, stamp) in removals]
  494. cursor.executemany(query1, args)
  495. if additions:
  496. args = []
  497. for name, stamp in additions:
  498. args.append((case.id, name, stamp))
  499. cursor.executemany(query2, args)
  500. msg = u" {0}: added {1} signatures and removed {2}"
  501. log = msg.format(case.id, len(additions), len(removals))
  502. self.logger.debug(log)
  503. def save_new_case(self, conn, case):
  504. """Save a brand new case to the database."""
  505. args = (case.id, case.title, case.status, case.last_action,
  506. case.file_user, case.file_time, case.modify_user,
  507. case.modify_time, case.volunteer_user, case.volunteer_time,
  508. case.close_time, case.parties_notified,
  509. case.very_old_notified, case.archived,
  510. case.last_volunteer_size)
  511. with conn.cursor() as cursor:
  512. query = "INSERT INTO cases VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
  513. cursor.execute(query, args)
  514. log = u" {0}: inserted new case into database".format(case.id)
  515. self.logger.debug(log)
  516. def save_existing_case(self, conn, case):
  517. """Save an existing case to the database, updating as necessary."""
  518. with conn.cursor(oursql.DictCursor) as cursor:
  519. query = "SELECT * FROM cases WHERE case_id = ?"
  520. cursor.execute(query, (case.id,))
  521. stored = cursor.fetchone()
  522. with conn.cursor() as cursor:
  523. changes, args = [], []
  524. fields_to_check = [
  525. ("case_status", case.status),
  526. ("case_last_action", case.last_action),
  527. ("case_file_user", case.file_user),
  528. ("case_file_time", case.file_time),
  529. ("case_modify_user", case.modify_user),
  530. ("case_modify_time", case.modify_time),
  531. ("case_volunteer_user", case.volunteer_user),
  532. ("case_volunteer_time", case.volunteer_time),
  533. ("case_close_time", case.close_time),
  534. ("case_parties_notified", case.parties_notified),
  535. ("case_very_old_notified", case.very_old_notified),
  536. ("case_archived", case.archived),
  537. ("case_last_volunteer_size", case.last_volunteer_size)
  538. ]
  539. for column, data in fields_to_check:
  540. if data != stored[column]:
  541. changes.append(column + " = ?")
  542. args.append(data)
  543. msg = u" {0}: will alter {1} ('{2}' -> '{3}')"
  544. log = msg.format(case.id, column, stored[column], data)
  545. self.logger.debug(log)
  546. if changes:
  547. changes = ", ".join(changes)
  548. args.append(case.id)
  549. query = "UPDATE cases SET {0} WHERE case_id = ?".format(changes)
  550. cursor.execute(query, args)
  551. else:
  552. log = u" {0}: no changes to commit".format(case.id)
  553. self.logger.debug(log)
  554. def save(self, page, cases, kwargs, start):
  555. """Save any changes to the noticeboard."""
  556. newtext = text = page.get()
  557. counter = 0
  558. for case in cases:
  559. if case.old != case.body:
  560. newtext = newtext.replace(case.old, case.body)
  561. counter += 1
  562. if newtext == text:
  563. self.logger.info(u"Nothing to edit on [[{0}]]".format(page.title))
  564. return True
  565. worktime = time() - start
  566. if worktime < 60:
  567. log = "Waiting {0} seconds to avoid edit conflicts"
  568. self.logger.debug(log.format(int(60 - worktime)))
  569. sleep(60 - worktime)
  570. page.reload()
  571. if page.get() != text:
  572. log = "Someone has edited the page while we were working; restarting"
  573. self.logger.warn(log)
  574. self.run(**kwargs)
  575. return False
  576. summary = self.clerk_summary.replace("$3", str(counter))
  577. summary = summary.replace("$4", "" if counter == 1 else "s")
  578. page.edit(newtext, summary, minor=True, bot=True)
  579. log = u"Saved page [[{0}]] ({1} updates)"
  580. self.logger.info(log.format(page.title, counter))
  581. return True
  582. def send_notices(self, site, notices):
  583. """Send out any templated notices to users or pages."""
  584. if not notices:
  585. self.logger.info("No notices to send")
  586. return
  587. for notice in notices:
  588. target, template = notice.target, notice.template
  589. log = u"Trying to notify [[{0}]] with '{1}'"
  590. self.logger.debug(log.format(target, template))
  591. page = site.get_page(target, follow_redirects=True)
  592. if page.namespace == constants.NS_USER_TALK:
  593. user = site.get_user(target.split(":", 1)[1])
  594. if not user.exists and not user.is_ip:
  595. log = u"Skipping [[{0}]]; user does not exist and is not an IP"
  596. self.logger.info(log.format(target))
  597. continue
  598. try:
  599. text = page.get()
  600. except exceptions.PageNotFoundError:
  601. text = ""
  602. if notice.too_late and notice.too_late in text:
  603. log = u"Skipping [[{0}]]; was already notified with '{1}'"
  604. self.logger.info(log.format(page.title, template))
  605. continue
  606. text += ("\n" if text else "") + template
  607. try:
  608. page.edit(text, self.notify_summary, minor=False, bot=True)
  609. except exceptions.EditError as error:
  610. name, msg = type(error).name, error.message
  611. log = u"Couldn't leave notice on [[{0}]] because of {1}: {2}"
  612. self.logger.error(log.format(page.title, name, msg))
  613. else:
  614. log = u"Notified [[{0}]] with '{1}'"
  615. self.logger.info(log.format(page.title, template))
  616. self.logger.debug("Done sending notices")
  617. def update_chart(self, conn, site):
  618. """Update the chart of open or recently closed cases."""
  619. page = site.get_page(self.chart_title)
  620. self.logger.info(u"Updating case status at [[{0}]]".format(page.title))
  621. statuses = self.compile_chart(conn)
  622. text = page.get()
  623. newtext = re.sub(u"<!-- status begin -->(.*?)<!-- status end -->",
  624. "<!-- status begin -->\n" + statuses + "\n<!-- status end -->",
  625. text, flags=re.DOTALL)
  626. if newtext == text:
  627. self.logger.info("Chart unchanged; not saving")
  628. return
  629. newtext = re.sub("<!-- sig begin -->(.*?)<!-- sig end -->",
  630. "<!-- sig begin -->~~~ at ~~~~~<!-- sig end -->",
  631. newtext)
  632. page.edit(newtext, self.chart_summary, minor=True, bot=True)
  633. self.logger.info(u"Chart saved to [[{0}]]".format(page.title))
  634. def compile_chart(self, conn):
  635. """Actually generate the chart from the database."""
  636. chart = "{{" + self.tl_chart_header + "|small={{{small|}}}|collapsed={{{collapsed|}}}}}\n"
  637. query = "SELECT * FROM cases WHERE case_status != ?"
  638. with conn.cursor(oursql.DictCursor) as cursor:
  639. cursor.execute(query, (self.STATUS_UNKNOWN,))
  640. for case in cursor:
  641. chart += self.compile_row(case)
  642. chart += "{{" + self.tl_chart_footer + "|small={{{small|}}}}}"
  643. return chart
  644. def compile_row(self, case):
  645. """Generate a single row of the chart from a dict via the database."""
  646. data = u"|t={case_title}|d={title}|s={case_status}"
  647. data += "|cu={case_file_user}|cs={file_sortkey}|ct={file_time}"
  648. if case["case_volunteer_user"]:
  649. data += "|vu={case_volunteer_user}|vs={volunteer_sortkey}|vt={volunteer_time}"
  650. case["volunteer_time"] = self.format_time(case["case_volunteer_time"])
  651. case["volunteer_sortkey"] = int(mktime(case["case_volunteer_time"].timetuple()))
  652. data += "|mu={case_modify_user}|ms={modify_sortkey}|mt={modify_time}"
  653. case["case_title"] = mw_parse(case["case_title"]).strip_code()
  654. title = case["case_title"].replace("_", " ").replace("|", "&#124;")
  655. case["title"] = title[:47] + "..." if len(title) > 50 else title
  656. case["file_time"] = self.format_time(case["case_file_time"])
  657. case["file_sortkey"] = int(mktime(case["case_file_time"].timetuple()))
  658. case["modify_time"] = self.format_time(case["case_modify_time"])
  659. case["modify_sortkey"] = int(mktime(case["case_modify_time"].timetuple()))
  660. row = "{{" + self.tl_chart_row + data.format(**case)
  661. return row + "|sm={{{small|}}}}}\n"
  662. def format_time(self, dt):
  663. """Return a string telling the time since *dt* occurred."""
  664. parts = [("year", 31536000), ("day", 86400), ("hour", 3600)]
  665. seconds = int((datetime.utcnow() - dt).total_seconds())
  666. if seconds < 0:
  667. return "Invalid future time"
  668. msg = []
  669. for name, size in parts:
  670. num = seconds // size
  671. seconds -= num * size
  672. if num:
  673. chunk = "{0} {1}".format(num, name if num == 1 else name + "s")
  674. msg.append(chunk)
  675. return ", ".join(msg) + " ago" if msg else "0 hours ago"
  676. def purge_old_data(self, conn):
  677. """Delete old cases (> six months) from the database."""
  678. log = "Purging closed cases older than six months from the database"
  679. self.logger.info(log)
  680. query = """DELETE cases, signatures
  681. FROM cases JOIN signatures ON case_id = signature_case
  682. WHERE case_status = ?
  683. AND case_file_time < DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 180 DAY)
  684. AND case_modify_time < DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 180 DAY)
  685. """
  686. with conn.cursor() as cursor:
  687. cursor.execute(query, (self.STATUS_UNKNOWN,))
  688. class _Case(object):
  689. """A object representing a dispute resolution case."""
  690. def __init__(self, id_, title, status, last_action, file_user, file_time,
  691. modify_user, modify_time, volunteer_user, volunteer_time,
  692. close_time, parties_notified, archived, very_old_notified,
  693. last_volunteer_size, new=False):
  694. self.id = id_
  695. self.title = title
  696. self.status = status
  697. self.last_action = last_action
  698. self.file_user = file_user
  699. self.file_time = file_time
  700. self.modify_user = modify_user
  701. self.modify_time = modify_time
  702. self.volunteer_user = volunteer_user
  703. self.volunteer_time = volunteer_time
  704. self.close_time = close_time
  705. self.parties_notified = parties_notified
  706. self.very_old_notified = very_old_notified
  707. self.archived = archived
  708. self.last_volunteer_size = last_volunteer_size
  709. self.new = new
  710. self.original_status = status
  711. self.body = None
  712. self.old = None
  713. class _Notice(object):
  714. """An object representing a notice to be sent to a user or a page."""
  715. def __init__(self, target, template, too_late=None):
  716. self.target = target
  717. self.template = template
  718. self.too_late = too_late