Additional IRC commands and bot tasks for EarwigBot https://en.wikipedia.org/wiki/User:EarwigBot
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 

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