Additional IRC commands and bot tasks for EarwigBot https://en.wikipedia.org/wiki/User:EarwigBot
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

drn_clerkbot.py 34 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780
  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_RESOLVED = 6
  42. STATUS_CLOSED = 7
  43. STATUS_FAILED = 8
  44. ALIASES = {
  45. STATUS_NEW: ("",),
  46. STATUS_OPEN: ("open", "active", "inprogress"),
  47. STATUS_STALE: ("stale",),
  48. STATUS_NEEDASSIST: ("needassist", "review", "relist", "relisted"),
  49. STATUS_RESOLVED: ("resolved", "resolve"),
  50. STATUS_CLOSED: ("closed", "close"),
  51. STATUS_FAILED: ("failed", "fail"),
  52. }
  53. def setup(self):
  54. """Hook called immediately after the task is loaded."""
  55. cfg = self.config.tasks.get(self.name, {})
  56. # Set some wiki-related attributes:
  57. self.title = cfg.get("title",
  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 in [self.STATUS_RESOLVED, self.STATUS_CLOSED,
  289. self.STATUS_FAILED]:
  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 or if it has been open for over seven
  313. days, or "stale" if no edits at all have occurred in two days.
  314. """
  315. if self.check_for_needassist(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. if timestamps:
  321. age = (datetime.utcnow() - max(timestamps)).total_seconds()
  322. if age > 60 * 60 * 24 * 2:
  323. self.update_status(case, self.STATUS_STALE)
  324. return []
  325. def clerk_needassist_case(self, case, volunteers, newsigs):
  326. """Clerk a "needassist" case (no volunteers in 15kb or >= 7 days old).
  327. The case will be set to "open" if a volunteer edits and the case is
  328. less than a week old. A message will be set to the "very old notifiee",
  329. which is generally [[User talk:Szhang (WMF)]], if the case has been
  330. open for more than ten days.
  331. """
  332. age = (datetime.utcnow() - case.file_time).total_seconds()
  333. if age <= 60 * 60 * 24 * 7:
  334. if any([editor in volunteers for (editor, timestamp) in newsigs]):
  335. self.update_status(case, self.STATUS_OPEN)
  336. elif age > 60 * 60 * 24 * 10:
  337. if not case.very_old_notified:
  338. tmpl = self.tl_notify_stale
  339. title = case.title.replace("|", "&#124;")
  340. template = "{{subst:" + tmpl + "|" + title + "}}"
  341. miss = "<!-- Template:DRN stale notice | {0} -->".format(title)
  342. notice = _Notice(self.very_old_title, template, miss)
  343. case.very_old_notified = True
  344. msg = u" {0}: will notify [[{1}]] with '{2}'"
  345. log = msg.format(case.id, self.very_old_title, template)
  346. self.logger.debug(log)
  347. return [notice]
  348. return []
  349. def clerk_stale_case(self, case, newsigs):
  350. """Clerk a stale case (no edits in two days).
  351. The case will be set to "open" if anyone edits, or "needassist" if it
  352. has been open for over seven days.
  353. """
  354. if self.check_for_needassist(case):
  355. return []
  356. if newsigs:
  357. self.update_status(case, self.STATUS_OPEN)
  358. return []
  359. def clerk_closed_case(self, case, signatures):
  360. """Clerk a closed or resolved case.
  361. The case will be archived if it has been closed/resolved for more than
  362. one day and no edits have been made in the meantime. "Archiving" is
  363. the process of adding {{DRN archive top}}, {{DRN archive bottom}}, and
  364. removing the [[User:DoNotArchiveUntil]] comment.
  365. """
  366. if case.close_time == self.min_ts:
  367. case.close_time = datetime.utcnow()
  368. if case.archived:
  369. return
  370. timestamps = [timestamp for (editor, timestamp) in signatures]
  371. closed_age = (datetime.utcnow() - case.close_time).total_seconds()
  372. if timestamps:
  373. modify_age = (datetime.utcnow() - max(timestamps)).total_seconds()
  374. else:
  375. modify_age = 0
  376. if closed_age > 60 * 60 * 24 and modify_age > 60 * 60 * 24:
  377. arch_top = self.tl_archive_top
  378. arch_bottom = self.tl_archive_bottom
  379. reg = "<!-- \[\[User:DoNotArchiveUntil\]\] .*? -->(<!-- .*? -->)?"
  380. if re.search(reg, case.body):
  381. case.body = re.sub("\{\{" + arch_top + "\}\}", "", case.body)
  382. case.body = re.sub(reg, "{{" + arch_top + "}}", case.body)
  383. if not re.search(arch_bottom + "\s*\}\}\s*\Z", case.body):
  384. case.body += "\n{{" + arch_bottom + "}}"
  385. case.archived = True
  386. self.logger.debug(u" {0}: archived case".format(case.id))
  387. def check_for_needassist(self, case):
  388. """Check whether a case is old enough to be set to "needassist"."""
  389. age = (datetime.utcnow() - case.file_time).total_seconds()
  390. if age > 60 * 60 * 24 * 7:
  391. self.update_status(case, self.STATUS_NEEDASSIST)
  392. return True
  393. return False
  394. def update_status(self, case, new):
  395. """Safely update the status of a case, so we don't edit war."""
  396. old_n = self.ALIASES[case.status][0].upper()
  397. new_n = self.ALIASES[new][0].upper()
  398. old_n = "NEW" if not old_n else old_n
  399. new_n = "NEW" if not new_n else new_n
  400. if case.last_action != new:
  401. case.status = new
  402. log = u" {0}: {1} -> {2}"
  403. self.logger.debug(log.format(case.id, old_n, new_n))
  404. return
  405. log = u"Avoiding {0} {1} -> {2} because we already did this ('{3}')"
  406. self.logger.info(log.format(case.id, old_n, new_n, case.title))
  407. def read_signatures(self, text):
  408. """Return a list of all parseable signatures in the body of a case.
  409. Signatures are returned as tuples of (editor, timestamp as datetime).
  410. """
  411. regex = r"\[\[(?:User(?:\stalk)?\:|Special\:Contributions\/)"
  412. regex += r"([^\n\[\]|]{,256}?)(?:\||\]\])"
  413. regex += r"(?!.*?(?:User(?:\stalk)?\:|Special\:Contributions\/).*?)"
  414. regex += r".{,256}?(\d{2}:\d{2},\s\d{1,2}\s\w+\s\d{4}\s\(UTC\))"
  415. matches = re.findall(regex, text, re.U|re.I)
  416. signatures = []
  417. for userlink, stamp in matches:
  418. username = userlink.split("/", 1)[0].replace("_", " ").strip()
  419. username = username[0].upper() + username[1:]
  420. if username == "DoNotArchiveUntil":
  421. continue
  422. stamp = stamp.strip()
  423. timestamp = datetime.strptime(stamp, "%H:%M, %d %B %Y (UTC)")
  424. signatures.append((username, timestamp))
  425. return signatures
  426. def get_signatures_from_db(self, conn, case):
  427. """Return a list of signatures in a case from the database.
  428. The return type is the same as read_signatures().
  429. """
  430. query = "SELECT signature_username, signature_timestamp FROM signatures WHERE signature_case = ?"
  431. with conn.cursor() as cursor:
  432. cursor.execute(query, (case.id,))
  433. return cursor.fetchall()
  434. def notify_parties(self, case):
  435. """Schedule notices to be sent to all parties of a case."""
  436. if case.parties_notified:
  437. return []
  438. notices = []
  439. template = "{{subst:" + self.tl_notify_party
  440. template += "|thread=" + case.title + "}} ~~~~"
  441. too_late = "<!--Template:DRN-notice-->"
  442. re_parties = "<span.*?>'''Users involved'''</span>(.*?)<span.*?>"
  443. text = re.search(re_parties, case.body, re.S|re.U)
  444. for line in text.group(1).splitlines():
  445. user = re.search("[:*#]{,5} \{\{User\|(.*?)\}\}", line)
  446. if user:
  447. party = user.group(1).replace("_", " ").strip()
  448. if party:
  449. party = party[0].upper() + party[1:]
  450. if party == case.file_user:
  451. continue
  452. notice = _Notice("User talk:" + party, template, too_late)
  453. notices.append(notice)
  454. case.parties_notified = True
  455. log = u" {0}: will try to notify {1} parties with '{2}'"
  456. self.logger.debug(log.format(case.id, len(notices), template))
  457. return notices
  458. def save_case_updates(self, conn, case, volunteers, sigs, storedsigs):
  459. """Save any updates made to a case and signatures in the database."""
  460. if case.status != case.original_status:
  461. case.last_action = case.status
  462. new = self.ALIASES[case.status][0]
  463. tl_status_esc = re.escape(self.tl_status)
  464. search = "\{\{" + tl_status_esc + "(\|?.*?)\}\}"
  465. repl = "{{" + self.tl_status + "|" + new + "}}"
  466. case.body = re.sub(search, repl, case.body)
  467. if sigs:
  468. newest_ts = max([stamp for (user, stamp) in sigs])
  469. newest_user = [usr for (usr, stamp) in sigs if stamp == newest_ts][0]
  470. case.modify_time = newest_ts
  471. case.modify_user = newest_user
  472. if any([usr in volunteers for (usr, stamp) in sigs]):
  473. newest_vts = max([stamp for (usr, stamp) in sigs if usr in volunteers])
  474. newest_vuser = [usr for (usr, stamp) in sigs if stamp == newest_vts][0]
  475. case.volunteer_time = newest_vts
  476. case.volunteer_user = newest_vuser
  477. if case.new:
  478. self.save_new_case(conn, case)
  479. else:
  480. self.save_existing_case(conn, case)
  481. with conn.cursor() as cursor:
  482. query1 = "DELETE FROM signatures WHERE signature_case = ? AND signature_username = ? AND signature_timestamp = ?"
  483. query2 = "INSERT INTO signatures (signature_case, signature_username, signature_timestamp) VALUES (?, ?, ?)"
  484. removals = set(storedsigs) - set(sigs)
  485. additions = set(sigs) - set(storedsigs)
  486. if removals:
  487. args = [(case.id, name, stamp) for (name, stamp) in removals]
  488. cursor.executemany(query1, args)
  489. if additions:
  490. args = []
  491. for name, stamp in additions:
  492. args.append((case.id, name, stamp))
  493. cursor.executemany(query2, args)
  494. msg = u" {0}: added {1} signatures and removed {2}"
  495. log = msg.format(case.id, len(additions), len(removals))
  496. self.logger.debug(log)
  497. def save_new_case(self, conn, case):
  498. """Save a brand new case to the database."""
  499. args = (case.id, case.title, case.status, case.last_action,
  500. case.file_user, case.file_time, case.modify_user,
  501. case.modify_time, case.volunteer_user, case.volunteer_time,
  502. case.close_time, case.parties_notified,
  503. case.very_old_notified, case.archived,
  504. case.last_volunteer_size)
  505. with conn.cursor() as cursor:
  506. query = "INSERT INTO cases VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
  507. cursor.execute(query, args)
  508. log = u" {0}: inserted new case into database".format(case.id)
  509. self.logger.debug(log)
  510. def save_existing_case(self, conn, case):
  511. """Save an existing case to the database, updating as necessary."""
  512. with conn.cursor(oursql.DictCursor) as cursor:
  513. query = "SELECT * FROM cases WHERE case_id = ?"
  514. cursor.execute(query, (case.id,))
  515. stored = cursor.fetchone()
  516. with conn.cursor() as cursor:
  517. changes, args = [], []
  518. fields_to_check = [
  519. ("case_status", case.status),
  520. ("case_last_action", case.last_action),
  521. ("case_file_user", case.file_user),
  522. ("case_file_time", case.file_time),
  523. ("case_modify_user", case.modify_user),
  524. ("case_modify_time", case.modify_time),
  525. ("case_volunteer_user", case.volunteer_user),
  526. ("case_volunteer_time", case.volunteer_time),
  527. ("case_close_time", case.close_time),
  528. ("case_parties_notified", case.parties_notified),
  529. ("case_very_old_notified", case.very_old_notified),
  530. ("case_archived", case.archived),
  531. ("case_last_volunteer_size", case.last_volunteer_size)
  532. ]
  533. for column, data in fields_to_check:
  534. if data != stored[column]:
  535. changes.append(column + " = ?")
  536. args.append(data)
  537. msg = u" {0}: will alter {1} ('{2}' -> '{3}')"
  538. log = msg.format(case.id, column, stored[column], data)
  539. self.logger.debug(log)
  540. if changes:
  541. changes = ", ".join(changes)
  542. args.append(case.id)
  543. query = "UPDATE cases SET {0} WHERE case_id = ?".format(changes)
  544. cursor.execute(query, args)
  545. else:
  546. log = u" {0}: no changes to commit".format(case.id)
  547. self.logger.debug(log)
  548. def save(self, page, cases, kwargs, start):
  549. """Save any changes to the noticeboard."""
  550. newtext = text = page.get()
  551. counter = 0
  552. for case in cases:
  553. if case.old != case.body:
  554. newtext = newtext.replace(case.old, case.body)
  555. counter += 1
  556. if newtext == text:
  557. self.logger.info(u"Nothing to edit on [[{0}]]".format(page.title))
  558. return True
  559. worktime = time() - start
  560. if worktime < 60:
  561. log = "Waiting {0} seconds to avoid edit conflicts"
  562. self.logger.debug(log.format(int(60 - worktime)))
  563. sleep(60 - worktime)
  564. page.reload()
  565. if page.get() != text:
  566. log = "Someone has edited the page while we were working; restarting"
  567. self.logger.warn(log)
  568. self.run(**kwargs)
  569. return False
  570. summary = self.clerk_summary.replace("$3", str(counter))
  571. summary = summary.replace("$4", "" if counter == 1 else "s")
  572. page.edit(newtext, summary, minor=True, bot=True)
  573. log = u"Saved page [[{0}]] ({1} updates)"
  574. self.logger.info(log.format(page.title, counter))
  575. return True
  576. def send_notices(self, site, notices):
  577. """Send out any templated notices to users or pages."""
  578. if not notices:
  579. self.logger.info("No notices to send")
  580. return
  581. for notice in notices:
  582. target, template = notice.target, notice.template
  583. log = u"Trying to notify [[{0}]] with '{1}'"
  584. self.logger.debug(log.format(target, template))
  585. page = site.get_page(target)
  586. if page.namespace == constants.NS_USER_TALK:
  587. user = site.get_user(target.split(":", 1)[1])
  588. if not user.exists and not user.is_ip:
  589. log = u"Skipping [[{0}]]; user does not exist and is not an IP"
  590. self.logger.info(log.format(target))
  591. continue
  592. try:
  593. text = page.get()
  594. except exceptions.PageNotFoundError:
  595. text = ""
  596. if notice.too_late and notice.too_late in text:
  597. log = u"Skipping [[{0}]]; was already notified with '{1}'"
  598. self.logger.info(log.format(page.title, template))
  599. continue
  600. text += ("\n" if text else "") + template
  601. try:
  602. page.edit(text, self.notify_summary, minor=False, bot=True)
  603. except exceptions.EditError as error:
  604. name, msg = type(error).name, error.message
  605. log = u"Couldn't leave notice on [[{0}]] because of {1}: {2}"
  606. self.logger.error(log.format(page.title, name, msg))
  607. else:
  608. log = u"Notified [[{0}]] with '{1}'"
  609. self.logger.info(log.format(page.title, template))
  610. self.logger.debug("Done sending notices")
  611. def update_chart(self, conn, site):
  612. """Update the chart of open or recently closed cases."""
  613. page = site.get_page(self.chart_title)
  614. self.logger.info(u"Updating case status at [[{0}]]".format(page.title))
  615. statuses = self.compile_chart(conn)
  616. text = page.get()
  617. newtext = re.sub(u"<!-- status begin -->(.*?)<!-- status end -->",
  618. "<!-- status begin -->\n" + statuses + "\n<!-- status end -->",
  619. text, flags=re.DOTALL)
  620. if newtext == text:
  621. self.logger.info("Chart unchanged; not saving")
  622. return
  623. newtext = re.sub("<!-- sig begin -->(.*?)<!-- sig end -->",
  624. "<!-- sig begin -->~~~ at ~~~~~<!-- sig end -->",
  625. newtext)
  626. page.edit(newtext, self.chart_summary, minor=True, bot=True)
  627. self.logger.info(u"Chart saved to [[{0}]]".format(page.title))
  628. def compile_chart(self, conn):
  629. """Actually generate the chart from the database."""
  630. chart = "{{" + self.tl_chart_header + "|small={{{small|}}}|collapsed={{{collapsed|}}}}}\n"
  631. query = "SELECT * FROM cases WHERE case_status != ?"
  632. with conn.cursor(oursql.DictCursor) as cursor:
  633. cursor.execute(query, (self.STATUS_UNKNOWN,))
  634. for case in cursor:
  635. chart += self.compile_row(case)
  636. chart += "{{" + self.tl_chart_footer + "|small={{{small|}}}}}"
  637. return chart
  638. def compile_row(self, case):
  639. """Generate a single row of the chart from a dict via the database."""
  640. data = u"|t={case_title}|d={title}|s={case_status}"
  641. data += "|cu={case_file_user}|cs={file_sortkey}|ct={file_time}"
  642. if case["case_volunteer_user"]:
  643. data += "|vu={case_volunteer_user}|vs={volunteer_sortkey}|vt={volunteer_time}"
  644. case["volunteer_time"] = self.format_time(case["case_volunteer_time"])
  645. case["volunteer_sortkey"] = int(mktime(case["case_volunteer_time"].timetuple()))
  646. data += "|mu={case_modify_user}|ms={modify_sortkey}|mt={modify_time}"
  647. title = case["case_title"].replace("_", " ").replace("|", "&#124;")
  648. case["title"] = title[:47] + "..." if len(title) > 50 else title
  649. case["file_time"] = self.format_time(case["case_file_time"])
  650. case["file_sortkey"] = int(mktime(case["case_file_time"].timetuple()))
  651. case["modify_time"] = self.format_time(case["case_modify_time"])
  652. case["modify_sortkey"] = int(mktime(case["case_modify_time"].timetuple()))
  653. row = "{{" + self.tl_chart_row + data.format(**case)
  654. return row + "|sm={{{small|}}}}}\n"
  655. def format_time(self, dt):
  656. """Return a string telling the time since datetime occurred."""
  657. parts = [("year", 31536000), ("day", 86400), ("hour", 3600)]
  658. seconds = int((datetime.utcnow() - dt).total_seconds())
  659. msg = []
  660. for name, size in parts:
  661. num = seconds // size
  662. seconds -= num * size
  663. if num:
  664. chunk = "{0} {1}".format(num, name if num == 1 else name + "s")
  665. msg.append(chunk)
  666. return ", ".join(msg) + " ago" if msg else "0 hours ago"
  667. def purge_old_data(self, conn):
  668. """Delete old cases (> six months) from the database."""
  669. log = "Purging closed cases older than six months from the database"
  670. self.logger.info(log)
  671. query = """DELETE cases, signatures
  672. FROM cases JOIN signatures ON case_id = signature_case
  673. WHERE case_status = ?
  674. AND case_file_time < DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 180 DAY)
  675. AND case_modify_time < DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 180 DAY)
  676. """
  677. with conn.cursor() as cursor:
  678. cursor.execute(query, (self.STATUS_UNKNOWN,))
  679. class _Case(object):
  680. """A object representing a dispute resolution case."""
  681. def __init__(self, id_, title, status, last_action, file_user, file_time,
  682. modify_user, modify_time, volunteer_user, volunteer_time,
  683. close_time, parties_notified, archived, very_old_notified,
  684. last_volunteer_size, new=False):
  685. self.id = id_
  686. self.title = title
  687. self.status = status
  688. self.last_action = last_action
  689. self.file_user = file_user
  690. self.file_time = file_time
  691. self.modify_user = modify_user
  692. self.modify_time = modify_time
  693. self.volunteer_user = volunteer_user
  694. self.volunteer_time = volunteer_time
  695. self.close_time = close_time
  696. self.parties_notified = parties_notified
  697. self.very_old_notified = very_old_notified
  698. self.archived = archived
  699. self.last_volunteer_size = last_volunteer_size
  700. self.new = new
  701. self.original_status = status
  702. self.body = None
  703. self.old = None
  704. class _Notice(object):
  705. """An object representing a notice to be sent to a user or a page."""
  706. def __init__(self, target, template, too_late=None):
  707. self.target = target
  708. self.template = template
  709. self.too_late = too_late