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.

143 rivejä
5.6 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. import sqlite3 as sqlite
  23. from threading import Lock
  24. __all__ = ["PermissionsDB"]
  25. class PermissionsDB(object):
  26. ADMIN = 1
  27. OWNER = 2
  28. def __init__(self, dbfile):
  29. self._dbfile = dbfile
  30. self._db_access_lock = Lock()
  31. self._data = {}
  32. def __repr__(self):
  33. """Return the canonical string representation of the PermissionsDB."""
  34. res = "PermissionsDB(dbfile={0!r})"
  35. return res.format(self._dbfile)
  36. def __str__(self):
  37. """Return a nice string representation of the PermissionsDB."""
  38. return "<PermissionsDB at {0}>".format(self._dbfile)
  39. def _create(self, conn):
  40. """Initialize the permissions database with its necessary tables."""
  41. query = """CREATE TABLE users (user_nick, user_ident, user_host,
  42. user_rank)"""
  43. conn.execute(query)
  44. def _is_rank(self, user, rank):
  45. """Return True if the given user has the given rank, else False."""
  46. try:
  47. for rule in self._data[rank]:
  48. if user == rule:
  49. return True
  50. except KeyError:
  51. return False
  52. def _set_rank(self, user, rank):
  53. """Add a User to the database under a given rank."""
  54. try:
  55. self._data[rank].append(user)
  56. except KeyError:
  57. self._data[rank] = [user]
  58. query = "INSERT INTO users VALUES (?, ?, ?, ?)"
  59. with sqlite.connect(self._dbfile) as conn, self._db_access_lock:
  60. conn.execute(query, (user.nick, user.ident, user.host, rank))
  61. def load(self):
  62. """Load permissions from an existing database, or create a new one."""
  63. query = "SELECT user_nick, user_ident, user_host, user_rank FROM users"
  64. self._data = {}
  65. with sqlite.connect(self._dbfile) as conn, self._db_access_lock:
  66. try:
  67. for nick, ident, host, rank in conn.execute(query):
  68. try:
  69. self._data[rank].append(_User(nick, ident, host))
  70. except KeyError:
  71. self._data[rank] = [_User(nick, ident, host)]
  72. except sqlite.OperationalError:
  73. self._create(conn)
  74. def is_admin(self, nick="*", ident="*", host="*"):
  75. """Return ``True`` if the given user is a bot admin, else ``False``."""
  76. return self._is_rank(_User(nick, ident, host), rank=self.ADMIN)
  77. def is_owner(self, nick="*", ident="*", host="*"):
  78. """Return ``True`` if the given user is a bot owner, else ``False``."""
  79. return self._is_rank(_User(nick, ident, host), rank=self.OWNER)
  80. def add_admin(self, nick="*", ident="*", host="*"):
  81. """Add an nick/ident/host combo to the bot admins list."""
  82. return self._set_rank(_User(nick, ident, host), rank=self.ADMIN)
  83. def add_owner(self, nick="*", ident="*", host="*"):
  84. """Add a nick/ident/host combo to the bot owners list."""
  85. return self._set_rank(_User(nick, ident, host), rank=self.OWNER)
  86. class _User(object):
  87. """A class that represents an IRC user for the purpose of testing rules."""
  88. def __init__(self, nick, ident, host):
  89. self.nick = nick
  90. self.ident = ident
  91. self.host = host
  92. def __repr__(self):
  93. """Return the canonical string representation of the User."""
  94. res = "_User(nick={0!r}, ident={1!r}, host={2!r})"
  95. return res.format(self.nick, self.ident, self.host)
  96. def __str__(self):
  97. """Return a nice string representation of the User."""
  98. return "{0}!{1}@{2}".format(self.nick, self.ident, self.host)
  99. def __eq__(self, user):
  100. if self._compare(self.nick, user.nick):
  101. if self._compare(self.ident, user.ident):
  102. if self._compare(self.host, user.host):
  103. return True
  104. return False
  105. def __ne__(self, user):
  106. return not self == user
  107. def _compare(self, field1, field2):
  108. if field1 == "*" or field2 == "*":
  109. return True
  110. if "*" in field1:
  111. regex = re.escape(field1).replace(r"\*", r".*?") + "$"
  112. if re.match(regex, field2, re.I):
  113. if "*" in field2:
  114. regex = re.escape(field2).replace(r"\*", r".*?") + "$"
  115. return re.match(regex, field1, re.I)
  116. return True
  117. else:
  118. return False
  119. elif "*" in field2:
  120. regex = re.escape(field2).replace(r"\*", r".*?") + "$"
  121. return re.match(regex, field1, re.I)
  122. return field1 == field2