A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

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