A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

afc_statistics.py 8.7 KiB

13 years ago
13 years ago
13 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. # -*- coding: utf-8 -*-
  2. import re
  3. from os.path import expanduser
  4. from threading import Lock
  5. import oursql
  6. from classes import BaseTask
  7. import config
  8. import wiki
  9. class Task(BaseTask):
  10. """A task to generate statistics for WikiProject Articles for Creation.
  11. Statistics are stored in a MySQL database ("u_earwig_afc_statistics")
  12. accessed with oursql. Statistics are updated live while watching the recent
  13. changes IRC feed and saved once an hour, on the hour, to self.pagename.
  14. In the live bot, this is "Template:AFC statistics".
  15. """
  16. name = "afc_statistics"
  17. number = 2
  18. def __init__(self):
  19. self.cfg = cfg = config.tasks.get(self.name, {})
  20. # Set some wiki-related attributes:
  21. self.pagename = cfg.get("page", "Template:AFC statistics")
  22. self.pending_cat = cfg.get("pending", "Pending AfC submissions")
  23. self.ignore_list = cfg.get("ignore_list", [])
  24. default_summary = "Updating statistics for [[WP:WPAFC|WikiProject Articles for creation]]."
  25. self.summary = self.make_summary(cfg.get("summary", default_summary))
  26. # Templates used in chart generation:
  27. templates = cfg.get("templates", {})
  28. self.tl_header = templates.get("header", "AFC statistics/header")
  29. self.tl_row = templates.get("row", "AFC statistics/row")
  30. self.tl_footer = templates.get("footer", "AFC statistics/footer")
  31. # Establish a connection with our SQL database:
  32. kwargs = cfg.get("sql", {})
  33. kwargs["read_default_file"] = expanduser("~/.my.cnf")
  34. self.conn = oursql.connect(**kwargs)
  35. self.db_access_lock = Lock()
  36. def run(self, **kwargs):
  37. self.site = wiki.get_site()
  38. action = kwargs.get("action")
  39. if not action:
  40. return
  41. methods = {
  42. "save": self.save,
  43. "sync", self.sync,
  44. "edit": self.process_edit,
  45. "move": self.process_move,
  46. "delete": self.process_delete,
  47. "restore": self.process_edit,
  48. }
  49. method = methods.get(action)
  50. if method:
  51. method(**kwargs)
  52. def save(self, **kwargs):
  53. if kwargs.get("fromIRC"):
  54. summary = " ".join((self.summary, "(!earwigbot)"))
  55. else:
  56. if self.shutoff_enabled():
  57. return
  58. summary = self.summary
  59. statistics = self.compile_charts()
  60. page = self.site.get_page(self.pagename)
  61. text = page.get()
  62. newtext = re.sub("(<!-- stat begin -->)(.*?)(<!-- stat end -->)",
  63. statistics.join(("\\1\n", "\n\\3")), text,
  64. flags=re.DOTALL)
  65. if newtext == text:
  66. return # Don't edit the page if we're not adding anything
  67. newtext = re.sub("(<!-- sig begin -->)(.*?)(<!-- sig end -->)",
  68. "\\1~~~ at ~~~~~\\3", newtext)
  69. page.edit(newtext, summary, minor=True, bot=True)
  70. def compile_charts(self):
  71. stats = ""
  72. with self.conn.cursor() as cursor, self.db_access_lock:
  73. cursor.execute("SELECT * FROM chart")
  74. for chart in cursor:
  75. stats += self.compile_chart(chart) + "\n"
  76. return stats[:-1] # Drop the last newline
  77. def compile_chart(self, chart_info):
  78. chart_id, chart_title, special_title = chart_info
  79. chart = "|".join((self.tl_header, chart_title))
  80. if special_title:
  81. chart += "".join(("|", special_title))
  82. chart = "".join(("{{", chart, "}}"))
  83. query = "SELECT * FROM page JOIN row ON page_id = row_id WHERE row_chart = ?"
  84. with self.conn.cursor(oursql.DictCursor) as cursor:
  85. cursor.execute(query, (chart_id,))
  86. for page in cursor:
  87. chart += "\n" + self.compile_chart_row(page)
  88. chart += "".join(("\n{{", self.tl_footer, "}}"))
  89. return chart
  90. def compile_chart_row(self, page):
  91. row = "{0}|s={page_status}|t={page_title}|h={page_short}|z={page_size}|"
  92. row += "cr={page_create_user}|cd={page_create_time}|ci={page_create_oldid}|"
  93. row += "mr={page_modify_user}|md={page_modify_time}|mi={page_modify_oldid}|"
  94. page["page_create_time"] = self.format_time(page["page_create_time"])
  95. page["page_modify_time"] = self.format_time(page["page_modify_time"])
  96. if page["page_special_user"]:
  97. row += "sr={page_special_user}|sd={page_special_time}|si={page_special_oldid}|"
  98. page["page_special_time"] = self.format_time(page["page_special_time"])
  99. if page["page_notes"]:
  100. row += "n=1{page_notes}"
  101. return "".join(("{{", row.format(self.tl_row, **page), "}}"))
  102. def format_time(self, timestamp):
  103. return timestamp.strftime("%H:%M, %d %B %Y")
  104. def sync(self, **kwargs):
  105. with self.conn.cursor() as cursor, self.db_access_lock:
  106. self.sync_deleted(cursor) # Remove deleted subs
  107. self.sync_oldids(cursor) # Make sure all subs are up to date
  108. self.sync_pending(cursor) # Add missed pending subs
  109. self.sync_old(cursor) # Remove old declined and accepted subs
  110. def sync_deleted(self, cursor):
  111. query1 = "SELECT page_id FROM page"
  112. query2 = "SELECT page_id FROM page WHERE page_id = ?"
  113. query3 = "DELETE FROM page JOIN row ON page_id = row_id WHERE page_id = ?"
  114. cursor.execute(query1)
  115. for page in cursor:
  116. result = self.site.sql_query(query2, (page,))
  117. if not list(result)[0]:
  118. cursor.execute(query3, (page,))
  119. def sync_oldids(self, cursor):
  120. query1 = "SELECT page_id, page_title, page_modify_oldid FROM page"
  121. query2 = "SELECT page_latest FROM page WHERE page_id = ?"
  122. query3 = "DELETE FROM page JOIN row ON page_id = row_id WHERE page_id = ?"
  123. cursor.execute(query1)
  124. for page_id, title, oldid in cursor:
  125. result = self.site.sql_query(query2, (page_id,))
  126. try:
  127. real_oldid = list(result)[0][0]
  128. except IndexError: # Page doesn't exist!
  129. cursor.execute(query3, (page_id,))
  130. continue
  131. if real_oldid == oldid:
  132. continue
  133. self.update_page(cursor, title)
  134. def sync_pending(self, cursor):
  135. query = """SELECT page_title FROM page JOIN row ON page_id = row_id
  136. WHERE row_chart IN (1, 2, 3)"""
  137. cursor.execute(query)
  138. tracked = [i[0] for i in cursor.fetchall()]
  139. category = self.site.get_category(self.pending_cat)
  140. for page in category.members(limit=500):
  141. if page in self.ignore_list:
  142. continue
  143. if page not in tracked:
  144. self.track_page(cursor, page)
  145. def sync_old(self, cursor):
  146. query = """DELETE FROM page, row USING page JOIN row
  147. ON page_id = row_id WHERE row_chart IN (4, 5)
  148. AND ADDTIME(page_special_time, '36:00:00') < NOW()"""
  149. cursor.execute(query)
  150. def track_page(self, cursor, page):
  151. # Page update hook when page is not in our database.
  152. pass
  153. def update_page(self, cursor, page):
  154. # Page update hook when page is in our database.
  155. pass
  156. def process_edit(self, page, **kwargs):
  157. query = "SELECT * FROM page WHERE page_title = ?"
  158. with self.conn.cursor() as cursor, self.db_access_lock:
  159. cursor.execute(query, (page,))
  160. result = cursor.fetchall()
  161. if result:
  162. self.update_page(cursor, page)
  163. else:
  164. self.track_page(cursor, page)
  165. def process_move(self, page, **kwargs):
  166. query1 = "SELECT * FROM page WHERE page_title = ?"
  167. query2 = "SELECT page_latest FROM page WHERE page_title = ?"
  168. query3 = "UPDATE page SET page_title = ?, page_modify_oldid = ? WHERE page_title = ?"
  169. source, dest = page
  170. with self.conn.cursor() as cursor, self.db_access_lock:
  171. cursor.execute(query1, (source,))
  172. result = cursor.fetchall()
  173. if not result:
  174. self.track_page(cursor, page)
  175. else:
  176. try:
  177. new_oldid = list(self.site.sql_query(query2, (dest,)))[0][0]
  178. except IndexError:
  179. new_oldid = result[11]
  180. cursor.execute(query3, (dest, new_oldid, source))
  181. def process_delete(self, page, **kwargs):
  182. query1 = "SELECT page_id FROM page WHERE page_title = ?"
  183. query2 = "DELETE FROM page JOIN row ON page_id = row_id WHERE page_title = ?"
  184. with self.conn.cursor() as cursor, self.db_access_lock:
  185. result = self.site.sql_query(query1, (page,))
  186. if not list(result)[0]:
  187. cursor.execute(query2, (page,))
  188. return
  189. self.process_edit(page)