locationbot.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. #!/usr/bin/env python
  2. # Location Bot
  3. #
  4. # Douglas Thrift
  5. #
  6. # $Id$
  7. from ConfigParser import NoOptionError, SafeConfigParser
  8. from datetime import datetime, timedelta
  9. import getpass
  10. import ircbot
  11. import irclib
  12. import os
  13. import psycopg2
  14. import pytz
  15. import re
  16. import sys
  17. import time
  18. import threading
  19. import urllib, urllib2
  20. import warnings
  21. try:
  22. import simplejson as json
  23. except ImportError:
  24. import json
  25. class LocationBot(ircbot.SingleServerIRCBot):
  26. def __init__(self, bot = None):
  27. config = SafeConfigParser({'hostname': ''})
  28. config.read('locationbot.ini')
  29. try:
  30. nick = config.sections()[0]
  31. except IndexError:
  32. sys.exit('No nick configured')
  33. servers = []
  34. try:
  35. for server in config.get(nick, 'servers').split():
  36. server = server.split(':', 2)
  37. if len(server) == 1:
  38. servers.append((server[0], 6667))
  39. else:
  40. host = server[0]
  41. port = int(server[1])
  42. ssl = server[1].startswith('+')
  43. if len(server) == 3:
  44. servers.append((host, port, ssl, server[2]))
  45. else:
  46. servers.append((host, port, ssl))
  47. self.__admins = config.get(nick, 'admins').split()
  48. self.__channels = set(config.get(nick, 'channels').split())
  49. self.__dsn = config.get(nick, 'dsn')
  50. self.__hostname = config.get(nick, 'hostname')
  51. except NoOptionError, error:
  52. sys.exit(error)
  53. ircbot.SingleServerIRCBot.__init__(self, servers, nick, 'Location Bot')
  54. self.__latitude_timer_lock = threading.Lock()
  55. self.__latitude_timer = None
  56. self.__locations_lock = threading.Lock()
  57. if bot is None:
  58. self.__locations = []
  59. self.__logins = {}
  60. self.__reloading = False
  61. else:
  62. irclibobj = self.ircobj.connections[0].irclibobj
  63. self.ircobj.connections[0] = bot.ircobj.connections[0]
  64. self.ircobj.connections[0].irclibobj = irclibobj
  65. self.channels = bot.channels
  66. self.connection = bot.connection
  67. self.__locations = bot.__locations
  68. self.__logins = bot.__logins
  69. self.__reloading = True
  70. self.__variables = frozenset(['nick', 'secret', 'masks', 'channels', 'timezone', 'location', 'latitude'])
  71. self.__lists = self.__variables.intersection(['masks', 'channels'])
  72. self.__unsetable = self.__variables.difference(['nick', 'secret'])
  73. def __admin(self, nickmask):
  74. return _or(lambda admin: irclib.mask_matches(nickmask, admin), self.__admins)
  75. def __db(self):
  76. db = psycopg2.connect(self.__dsn)
  77. return db, db.cursor()
  78. def __channel(self, nick, exclude = None):
  79. if exclude is not None:
  80. exclude = irclib.irc_lower(exclude)
  81. channels = map(lambda channel: channel[1], filter(lambda channel: irclib.irc_lower(channel[0]) == exclude, self.channels))
  82. else:
  83. channels = self.channels.values()
  84. return _or(lambda channel: channel.has_user(nick), channels)
  85. def __help(self, connection, nick, admin, login, arguments):
  86. command = irclib.irc_lower(arguments.split(None, 1)[0].lstrip('!')) if arguments else None
  87. commands = {
  88. 'help': ('[command]', 'show this help message'),
  89. 'status': ('[nick]', 'show where everybody or a nick is'),
  90. }
  91. if not login:
  92. commands.update({
  93. 'login': ('[nick] [secret]', 'log in as nick with secret or using masks'),
  94. 'register': ('[nick] secret', 'register as nick with secret'),
  95. })
  96. else:
  97. commands.update({
  98. 'logout': ('', 'log out as nick'),
  99. 'set': ('[variable [value]]', 'display or set variables'),
  100. 'unset': ('variable', 'unset a variable'),
  101. })
  102. if admin:
  103. commands.update({
  104. 'reload': ('', 'reload with more up to date code'),
  105. 'restart': ('', 'quit and join running more up to date code'),
  106. 'say': ('nick|channel message', 'say message to nick or channel'),
  107. 'who': ('', 'show who is logged in'),
  108. })
  109. connection.privmsg(nick, '\x02command arguments description\x0f')
  110. def help(command, arguments, description):
  111. connection.privmsg(nick, '%-11s %-23s %s' % (command, arguments, description))
  112. if command in commands:
  113. help(command, *commands[command])
  114. else:
  115. for command, (arguments, description) in sorted(commands.iteritems()):
  116. help(command, arguments, description)
  117. def __latitude(self):
  118. now = datetime.utcnow()
  119. try:
  120. while now < self.__latitude_next:
  121. time.sleep((self.__latitude_next - now).seconds)
  122. now = datetime.utcnow()
  123. except AttributeError:
  124. pass
  125. self.__latitude_next = now.replace(minute = now.minute - now.minute % 5, second = 0, microsecond = 0) + timedelta(minutes = 5)
  126. try:
  127. db, cursor = self.__db()
  128. cursor.execute('select nick, channels, location, latitude from locationbot.nick where latitude is not null order by latitude')
  129. locations = {}
  130. for nick, channels, old_location, latitude in cursor.fetchall():
  131. new_location = locations.get(latitude)
  132. if latitude not in locations:
  133. url = 'http://www.google.com/latitude/apps/badge/api?' + urllib.urlencode({'user': latitude, 'type': 'json'})
  134. try:
  135. response = urllib2.urlopen(url)
  136. except urllib2.URLError, error:
  137. print error
  138. continue
  139. try:
  140. geo = json.load(response)
  141. except (TypeError, ValueError), error:
  142. print error
  143. continue
  144. try:
  145. properties = geo['features'][0]['properties']
  146. new_location = properties['reverseGeocode']
  147. locations[latitude] = new_location
  148. updated = datetime.fromtimestamp(properties['timeStamp'], pytz.utc)
  149. except (IndexError, KeyError), error:
  150. print error
  151. continue
  152. cursor.execute('update locationbot.nick set location = %s, updated = %s where latitude = %s', (new_location, updated, latitude))
  153. db.commit()
  154. self.__location(nick, channels, old_location, new_location)
  155. except psycopg2.Error, error:
  156. print error
  157. with self.__latitude_timer_lock:
  158. self.__latitude_timer = threading.Timer((self.__latitude_next - datetime.utcnow()).seconds, self.__latitude)
  159. self.__latitude_timer.start()
  160. def __location(self, nick, channels, old_location, new_location):
  161. if channels and new_location and new_location != old_location:
  162. with self.__locations_lock:
  163. for channel in self.__channels.intersection(channels):
  164. self.__locations.append((nick, channel, new_location))
  165. def __login(self, connection, nickmask, nick, arguments = ''):
  166. login = nick
  167. if connection is not None:
  168. arguments = arguments.split(None, 1)
  169. if len(arguments) == 2:
  170. login, secret = arguments
  171. elif len(arguments) == 1:
  172. secret = arguments[0]
  173. else:
  174. secret = None
  175. else:
  176. secret = None
  177. if nick in self.__logins:
  178. login = self.__logins[nick][0]
  179. if connection is not None:
  180. return connection.privmsg(nick, 'already logged in as "%s"' % login)
  181. return login
  182. db, cursor = self.__db()
  183. def success():
  184. connection.privmsg(nick, 'successfully logged in as "%s"' % login)
  185. if secret is not None:
  186. cursor.execute('select true from locationbot.nick where nick = %s and secret = md5(%s)', (login, secret))
  187. if cursor.rowcount == 1:
  188. self.__logins[nick] = (login, nickmask)
  189. return success()
  190. cursor.execute('select nick, masks from locationbot.nick where nick in (%s, %s)', (login, secret if len(arguments) != 2 else None))
  191. for login, masks in cursor.fetchall():
  192. if _or(lambda mask: irclib.mask_matches(nickmask, mask), masks):
  193. self.__logins[nick] = (login, nickmask)
  194. return success() if connection else login
  195. if connection is not None:
  196. return connection.privmsg(nick, 'failed to log in as "%s"' % login)
  197. def __logout(self, connection, nick):
  198. connection.privmsg(nick, 'logged out as "%s"' % self.__logins.pop(nick)[0])
  199. def __register(self, connection, nick, arguments):
  200. arguments = arguments.split(None, 1)
  201. if len(arguments) == 2:
  202. login, secret = arguments
  203. elif len(arguments) == 1:
  204. login = nick
  205. secret = arguments[0]
  206. else:
  207. return self.__help(connection, nick, False, False, 'register')
  208. db, cursor = self.__db()
  209. try:
  210. cursor.execute('insert into locationbot.nick (nick, secret) values (%s, md5(%s))', (login, secret))
  211. db.commit()
  212. except psycopg2.IntegrityError:
  213. return connection.privmsg(nick, 'nick ("%s") is already registered' % login)
  214. connection.privmsg(nick, 'nick ("%s") sucessfully registered' % login)
  215. def __reload(self, connection, nick):
  216. self.__reloading = True
  217. connection.privmsg(nick, 'reloading')
  218. def __restart(self, connection):
  219. connection.disconnect('restarting')
  220. os.execvp(sys.argv[0], sys.argv)
  221. def __say(self, connection, nick, arguments):
  222. try:
  223. nick_channel, message = arguments.split(None, 1)
  224. except ValueError:
  225. return self.__help(connection, nick, True, False, 'say')
  226. if irclib.is_channel(nick_channel):
  227. if nick_channel not in self.channels:
  228. return connection.privmsg(nick, 'not in channel ("%s")' % nick_channel)
  229. elif not self.__channel(nick_channel):
  230. return connection.privmsg(nick, 'nick ("%s") not in channel(s)' % nick_channel)
  231. elif nick_channel == connection.get_nickname():
  232. return connection.privmsg(nick, 'nice try')
  233. connection.privmsg(nick_channel, message)
  234. def __set(self, connection, nickmask, nick, login, arguments):
  235. arguments = arguments.split(None, 1)
  236. if len(arguments) == 2:
  237. variable, value = arguments
  238. elif len(arguments) == 1:
  239. variable = arguments[0]
  240. value = None
  241. else:
  242. variable = None
  243. value = None
  244. if variable is not None and variable not in self.__variables:
  245. return self.__unknown_variable(connection, nick, variable)
  246. db, cursor = self.__db()
  247. if value is None:
  248. variables = sorted(self.__variables) if variable is None else [variable]
  249. cursor.execute('select ' + ', '.join(map(lambda variable: "'%s'" % ('*' * 8) if variable == 'secret' else variable, variables)) + ' from locationbot.nick where nick = %s', (login,))
  250. connection.privmsg(nick, '\x02variable value\x0f')
  251. for variable, value in zip(variables, cursor.fetchone()):
  252. connection.privmsg(nick, '%-8s %s' % (variable, ' '.join(value) if isinstance(value, list) else value))
  253. else:
  254. def invalid(value, variable = variable):
  255. connection.privmsg(nick, 'invalid %s ("%s")' % (variable, value))
  256. if variable in self.__lists:
  257. value = value.split()
  258. if variable == 'channels':
  259. for channel in value:
  260. if not irclib.is_channel(channel) or channel not in self.__channels:
  261. return invalid(channel, 'channel')
  262. elif variable == 'masks':
  263. _mask = re.compile('^.+!.+@.+$')
  264. for mask in value:
  265. if not _mask.match(mask):
  266. return invalid(mask, 'mask')
  267. elif variable == 'latitude':
  268. try:
  269. value = int(re.sub(r'^(?:http://(?:www\.)?google\.com/latitude/apps/badge/api\?user=)?([0-9]+)(?:&type=.*)?$', r'\1', value))
  270. except ValueError:
  271. return invalid(value)
  272. elif variable == 'location':
  273. cursor.execute('select channels, location from locationbot.nick where nick = %s', (login,))
  274. channels, location = cursor.fetchone()
  275. elif variable == 'nick':
  276. _nick = value.split(None, 1)
  277. if len(_nick) != 1:
  278. return invalid(value)
  279. elif variable == 'timezone':
  280. if value not in pytz.all_timezones_set:
  281. return invalid(value)
  282. try:
  283. cursor.execute('update locationbot.nick set ' + variable + ' = ' + ('md5(%s)' if variable == 'secret' else '%s') + (', updated = now()' if variable == 'location' else '') + ' where nick = %s', (value, login))
  284. db.commit()
  285. except psycopg2.IntegrityError:
  286. if variable == 'nick':
  287. return connection.privmsg(nick, 'nick ("%s") is already registered' % value)
  288. raise
  289. if variable == 'nick':
  290. self.__logins[nick] = (value, nickmask)
  291. elif variable == 'location':
  292. self.__location(nick, channels, location, value)
  293. connection.privmsg(nick, 'variable ("%s") successfully set to value ("%s")' % (variable, ' '.join(value) if isinstance(value, list) else value))
  294. def __status(self, connection, nick, login, arguments):
  295. _nick = arguments.split(None, 1)[0] if arguments else None
  296. db, cursor = self.__db()
  297. cursor.execute('select nick, location, updated from locationbot.nick where ' + ('nick = %s and ' if _nick is not None else '') + 'location is not null order by updated desc', (_nick,))
  298. if cursor.rowcount == 0:
  299. return connection.privmsg(nick, 'no location information for ' + ('"%s"' % _nick if _nick is not None else 'anybody'))
  300. locations = cursor.fetchall()
  301. if login is not None:
  302. cursor.execute('select timezone from locationbot.nick where nick = %s and timezone is not null', (login,))
  303. timezone = pytz.timezone(cursor.fetchone()[0]) if cursor.rowcount == 1 else pytz.utc
  304. else:
  305. timezone = pytz.utc
  306. connection.privmsg(nick, '\x02nick location when\x0f')
  307. for _nick, location, updated in locations:
  308. connection.privmsg(nick, '%-23s %-36s %s' % (_nick, location, timezone.normalize(updated.astimezone(timezone)).strftime('%Y-%m-%d %H:%M %Z')))
  309. def __unknown(self, connection, nick, command):
  310. connection.privmsg(nick, 'unknown command ("%s"); try "help"' % command)
  311. def __unknown_variable(self, connection, nick, variable):
  312. connection.privmsg(nick, 'unknown variable ("%s")' % variable)
  313. def __unset(self, connection, nick, login, arguments):
  314. try:
  315. variable = irclib.irc_lower(arguments.split(None, 1)[0])
  316. except IndexError:
  317. return self.__help(connection, nick, False, login, 'unset')
  318. if variable not in self.__unsetable:
  319. if variable in self.__variables:
  320. return connection.privmsg(nick, 'variable ("%s") is not unsetable' % variable)
  321. return self.__unknown_variable(connection, nick, variable)
  322. db, cursor = self.__db()
  323. cursor.execute('update locationbot.nick set ' + variable + ' = null' + (', updated = null' if variable == 'location' else '') + ' where nick = %s and ' + variable + ' is not null', (login,))
  324. db.commit()
  325. connection.privmsg(nick, 'variable ("%s") %s unset' % (variable, 'successfuly' if cursor.rowcount == 1 else 'already'))
  326. def __who(self, connection, nick):
  327. if self.__logins:
  328. connection.privmsg(nick, '\x02login nick nick mask\x0f')
  329. for login in sorted(self.__logins.values()):
  330. connection.privmsg(nick, '%-23s %s' % login)
  331. else:
  332. connection.privmsg(nick, 'nobody logged in')
  333. def _connect(self):
  334. if len(self.server_list[0]) != 2:
  335. ssl = self.server_list[0][2]
  336. else:
  337. ssl = False
  338. if len(self.server_list[0]) == 4:
  339. password = self.server_list[0][3]
  340. else:
  341. password = None
  342. try:
  343. with warnings.catch_warnings():
  344. warnings.filterwarnings('ignore', r'socket\.ssl\(\) is deprecated\. Use ssl\.wrap_socket\(\) instead\.', DeprecationWarning)
  345. self.connect(self.server_list[0][0], self.server_list[0][1], self._nickname, password, getpass.getuser(), self._realname, localaddress = self.__hostname, ssl = ssl)
  346. except irclib.ServerConnectionError:
  347. pass
  348. def get_version(self):
  349. return 'locationbot ' + sys.platform
  350. def on_kick(self, connection, event):
  351. nick = event.arguments()[0]
  352. if not self.__channel(nick, event.target()):
  353. self.__logins.pop(nick, None)
  354. def on_nick(self, connection, event):
  355. nickmask = event.source()
  356. login = self.__logins.pop(irclib.nm_to_n(nickmask), (None,))[0]
  357. if login is not None:
  358. nick = event.target()
  359. self.__logins[nick] = (login, nick + '!' + nm_to_uh(nickmask))
  360. def on_nicknameinuse(self, connection, event):
  361. connection.nick(connection.get_nickname() + '_')
  362. def on_part(self, connection, event):
  363. nick = irclib.nm_to_n(event.source())
  364. if not self.__channel(nick, event.target()):
  365. self.__logins.pop(nick, None)
  366. def on_privmsg(self, connection, event):
  367. nickmask = event.source()
  368. nick = irclib.nm_to_n(nickmask)
  369. admin = self.__admin(nickmask)
  370. if not admin and not self.__channel(nick):
  371. return
  372. try:
  373. login = self.__login(None, nickmask, nick)
  374. try:
  375. command, arguments = event.arguments()[0].split(None, 1)
  376. except ValueError:
  377. command = event.arguments()[0].strip()
  378. arguments = ''
  379. command = irclib.irc_lower(command.lstrip('!'))
  380. if command == 'help':
  381. self.__help(connection, nick, admin, login, arguments)
  382. elif command == 'login':
  383. self.__login(connection, nickmask, nick, arguments)
  384. elif command == 'status':
  385. self.__status(connection, nick, login, arguments)
  386. elif not login and command == 'register':
  387. self.__register(connection, nick, arguments)
  388. elif login and command == 'logout':
  389. self.__logout(connection, nick)
  390. elif login and command == 'set':
  391. self.__set(connection, nickmask, nick, login, arguments)
  392. elif login and command == 'unset':
  393. self.__unset(connection, nick, login, arguments)
  394. elif admin and command == 'reload':
  395. self.__reload(connection, nick)
  396. elif admin and command == 'restart':
  397. self.__restart(connection)
  398. elif admin and command == 'say':
  399. self.__say(connection, nick, arguments)
  400. elif admin and command == 'who':
  401. self.__who(connection, nick)
  402. else:
  403. self.__unknown(connection, nick, command)
  404. except psycopg2.Error, error:
  405. print error
  406. connection.privmsg(nick, 'an error occurred')
  407. def on_quit(self, connection, event):
  408. self.__logins.pop(irclib.nm_to_n(event.source()), None)
  409. def on_welcome(self, connection, event):
  410. for channel in self.__channels:
  411. connection.join(channel)
  412. def start(self):
  413. self.__latitude_thread = threading.Thread(None, self.__latitude)
  414. self.__latitude_thread.daemon = True
  415. self.__latitude_thread.start()
  416. if not self.__reloading:
  417. self._connect()
  418. else:
  419. self.__reloading = False
  420. for channel in self.__channels.difference(self.channels.keys()):
  421. self.connection.join(channel)
  422. while not self.__reloading:
  423. if self.__locations_lock.acquire(False):
  424. if self.__locations and self.__channels.issubset(self.channels.keys()):
  425. for nick, channel, location in self.__locations:
  426. self.connection.notice(channel, '%s is in %s' % (nick, location))
  427. self.__locations = []
  428. self.__locations_lock.release()
  429. self.ircobj.process_once(0.2)
  430. self.__latitude_thread.join()
  431. with self.__latitude_timer_lock:
  432. if self.__latitude_timer is not None:
  433. self.__latitude_timer.cancel()
  434. self.__latitude_timer.join()
  435. def _or(function, values):
  436. return reduce(lambda a, b: a or b, map(function, values) if values else [False])
  437. if __name__ == '__main__':
  438. import locationbot
  439. bot = None
  440. try:
  441. while True:
  442. bot = reload(locationbot).LocationBot(bot)
  443. bot.start()
  444. except KeyboardInterrupt:
  445. bot.connection.disconnect('oh no!')