Additional IRC commands and bot tasks for EarwigBot https://en.wikipedia.org/wiki/User:EarwigBot
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

drn_clerkbot.py 35 KiB

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