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.

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