A Python robot that edits Wikipedia and interacts with people over IRC 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.

782 lines
34 KiB

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