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.

868 lines
36 KiB

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