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

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