locationbot.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877
  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 oauth2 as oauth
  13. import os
  14. import psycopg2
  15. import psycopg2.extensions
  16. import pytz
  17. import re
  18. import sys
  19. import time
  20. import threading
  21. import urllib, urllib2
  22. import urlparse
  23. import warnings
  24. try:
  25. import simplejson as json
  26. except ImportError:
  27. import json
  28. class LocationBot(ircbot.SingleServerIRCBot):
  29. def __init__(self, bot = None):
  30. self.__config = SafeConfigParser()
  31. self.__config.read('locationbot.ini')
  32. try:
  33. nick = self.__config.sections()[0]
  34. except IndexError:
  35. sys.exit('No nick configured')
  36. servers = []
  37. try:
  38. for server in self.__config.get(nick, 'servers').split():
  39. server = server.split(':', 2)
  40. if len(server) == 1:
  41. servers.append((server[0], 6667))
  42. else:
  43. host = server[0]
  44. port = int(server[1])
  45. ssl = server[1].startswith('+')
  46. if len(server) == 3:
  47. servers.append((host, port, ssl, server[2]))
  48. else:
  49. servers.append((host, port, ssl))
  50. self.__admins = self.__config.get(nick, 'admins').split()
  51. self.__channels = set(self.__config.get(nick, 'channels').split())
  52. self.__dsn = self.__config.get(nick, 'dsn')
  53. self.__latitude_key = self.__config.get(nick, 'latitude_key')
  54. self.__latitude_consumer = oauth.Consumer(key = self.__latitude_key, secret = self.__config.get(nick, 'latitude_secret'))
  55. except NoOptionError, error:
  56. sys.exit(error)
  57. try:
  58. self.__hostname = self.__config.get(nick, 'hostname')
  59. except NoOptionError:
  60. self.__hostname = ''
  61. ircbot.SingleServerIRCBot.__init__(self, servers, nick, 'Location Bot')
  62. if bot is None:
  63. self.__geocode_cache = {}
  64. self.__locations = []
  65. self.__logins = {}
  66. self.__nick = None
  67. self.__reloading = False
  68. else:
  69. self.__geocode_cache = bot.__geocode_cache
  70. irclibobj = self.ircobj.connections[0].irclibobj
  71. self.ircobj.connections[0] = bot.ircobj.connections[0]
  72. self.ircobj.connections[0].irclibobj = irclibobj
  73. self.channels = bot.channels
  74. self.connection = bot.connection
  75. self.__locations = bot.__locations
  76. self.__logins = bot.__logins
  77. self.__nick = bot.__nick
  78. self.__reloading = True
  79. self.__geocode_cache_lock = threading.Lock()
  80. self.__geocode_cache_clean_timer_lock = threading.Lock()
  81. self.__geocode_cache_clean_timer = None
  82. self.__latitude_granularities = frozenset(['city', 'best'])
  83. self.__latitude_timer_lock = threading.Lock()
  84. self.__latitude_timer = None
  85. self.__locations_lock = threading.Lock()
  86. self.__quiting = False
  87. self.__variables = frozenset(['nick', 'secret', 'masks', 'channels', 'timezone', 'location', 'coordinates', 'latitude'])
  88. self.__geocode_variables = self.__variables.intersection(['location', 'coordinates'])
  89. self.__lists = self.__variables.intersection(['masks', 'channels'])
  90. self.__unsetable = self.__variables.difference(['nick', 'secret'])
  91. def __admin(self, nickmask):
  92. return _or(lambda admin: irclib.mask_matches(nickmask, admin), self.__admins)
  93. def __channel(self, nick, exclude = None):
  94. if exclude is not None:
  95. exclude = irclib.irc_lower(exclude)
  96. channels = map(lambda channel: channel[1], filter(lambda channel: irclib.irc_lower(channel[0]) == exclude, self.channels))
  97. else:
  98. channels = self.channels.values()
  99. return _or(lambda channel: channel.has_user(nick), channels)
  100. def __db(self):
  101. db = psycopg2.connect(self.__dsn)
  102. def point(value, cursor):
  103. if value is not None:
  104. return tuple(map(lambda a: float(a), re.match(r'^\(([^)]+),([^)]+)\)$', value).groups()))
  105. psycopg2.extensions.register_type(psycopg2.extensions.new_type((600,), 'point', point), db)
  106. return db, db.cursor()
  107. def __geocode(self, sensor, coordinates = None, location = None):
  108. parameters = {'sensor': 'true' if sensor else 'false'}
  109. with self.__geocode_cache_lock:
  110. if coordinates is not None:
  111. try:
  112. return self.__geocode_cache[coordinates][0]
  113. except KeyError:
  114. parameters['latlng'] = '%f,%f' % coordinates
  115. else:
  116. try:
  117. return self.__geocode_cache[coordinates][0]
  118. except KeyError:
  119. parameters['address'] = location
  120. geocode = json.load(urllib2.urlopen('http://maps.google.com/maps/api/geocode/json?' + urllib.urlencode(parameters)))
  121. status = geocode['status']
  122. if status != 'OK':
  123. if coordinates is not None and status == 'ZERO_RESULTS':
  124. return self.__geocode(sensor, location = parameters['latlng'])
  125. else:
  126. raise Exception(status)
  127. results = geocode['results']
  128. def _result():
  129. _location = result['geometry']['location']
  130. geocode = (_location['lat'], _location['lng']), result['formatted_address']
  131. with self.__geocode_cache_lock:
  132. self.__geocode_cache[coordinates if coordinates is not None else location] = (geocode, datetime.utcnow())
  133. return geocode
  134. if coordinates is not None:
  135. types = frozenset([
  136. 'country',
  137. 'administrative_area_level_1',
  138. 'administrative_area_level_2',
  139. 'administrative_area_level_3',
  140. 'colloquial_area',
  141. 'locality',
  142. 'sublocality',
  143. 'neighborhood',
  144. ])
  145. for result in results:
  146. if not types.isdisjoint(result['types']):
  147. return _result()
  148. result = results[0]
  149. return _result()
  150. def __geocode_cache_clean(self):
  151. now = datetime.utcnow()
  152. try:
  153. while now < self.__geocode_cache_clean_next:
  154. time.sleep((self.__geocode_cache_clean_next - now).seconds)
  155. now = datetime.utcnow()
  156. except AttributeError:
  157. self.__geocode_cache_length = timedelta(hours = 1)
  158. self.__geocode_cache_clean_next = now.replace(minute = 2, second = 30, microsecond = 0) + self.__geocode_cache_length
  159. with self.__geocode_cache_lock:
  160. for location, (geocode, created) in self.__geocode_cache.items():
  161. if now - created >= self.__geocode_cache_length:
  162. del self.__geocode_cache[location]
  163. with self.__geocode_cache_clean_timer_lock:
  164. self.__geocode_cache_clean_timer = threading.Timer((self.__geocode_cache_clean_next - datetime.utcnow()).seconds, self.__latitude)
  165. self.__geocode_cache_clean_timer.start()
  166. def __help(self, connection, nick, admin, login, arguments):
  167. command = irclib.irc_lower(arguments.split(None, 1)[0].lstrip('!')) if arguments else None
  168. commands = {
  169. 'help': ('[command]', 'show this help message'),
  170. 'status': ('[nick]', 'show where everybody or a nick is'),
  171. }
  172. if not login:
  173. commands.update({
  174. 'login': ('[nick] [secret]', 'log in as nick with secret or using masks'),
  175. 'register': ('[nick] secret', 'register as nick with secret'),
  176. })
  177. else:
  178. commands.update({
  179. 'logout': ('', 'log out as nick'),
  180. 'set': ('[variable [value]]', 'display or set variables'),
  181. 'unset': ('variable', 'unset a variable'),
  182. })
  183. if admin:
  184. commands.update({
  185. 'join': ('channel', 'join a channel'),
  186. 'part': ('channel [message]', 'part from a channel'),
  187. 'quit': ('[message]', 'quit and do not come back'),
  188. 'reload': ('', 'reload with more up to date code'),
  189. 'restart': ('', 'quit and join running more up to date code'),
  190. 'say': ('nick|channel message', 'say message to nick or channel'),
  191. 'who': ('', 'show who is logged in'),
  192. })
  193. connection.privmsg(nick, '\x02command arguments description\x0f')
  194. def help(command, arguments, description):
  195. connection.privmsg(nick, '%-11s %-23s %s' % (command, arguments, description))
  196. if command in commands:
  197. help(command, *commands[command])
  198. else:
  199. for command, (arguments, description) in sorted(commands.iteritems()):
  200. help(command, arguments, description)
  201. def __join(self, connection, nick, arguments):
  202. try:
  203. channel = arguments.split(None, 1)[0]
  204. except IndexError:
  205. return self.__help(connection, nick, True, False, 'join')
  206. connection.join(channel)
  207. self.__channels.add(channel)
  208. self.__config.set(self._nickname, 'channels', ' '.join(self.__channels))
  209. self.__write()
  210. connection.privmsg(nick, 'successfully joined channel ("%s")' % channel)
  211. def __latitude(self, granularity = None, token = None, secret = None):
  212. if granularity is not None:
  213. response, content = oauth.Client(self.__latitude_consumer, oauth.Token(token, secret)).request('https://www.googleapis.com/latitude/v1/currentLocation?' + urllib.urlencode({'granularity': granularity}), 'GET')
  214. if int(response['status']) != 200:
  215. raise Exception(content.strip())
  216. data = json.loads(content)['data']
  217. coordinates = (data['latitude'], data['longitude'])
  218. return datetime.fromtimestamp(int(data['timestampMs']) / 1e3, pytz.utc), coordinates, data.get('accuracy'), data.get('speed'), data.get('heading'), data.get('altitude'), data.get('altitudeAccuracy'), self.__geocode(False, coordinates = coordinates)[1]
  219. now = datetime.utcnow()
  220. try:
  221. while now < self.__latitude_next:
  222. time.sleep((self.__latitude_next - now).seconds)
  223. now = datetime.utcnow()
  224. except AttributeError:
  225. pass
  226. self.__latitude_next = now.replace(minute = now.minute - now.minute % 5, second = 0, microsecond = 0) + timedelta(minutes = 5)
  227. try:
  228. db, cursor = self.__db()
  229. cursor.execute('select nick, channels, location, latitude.granularity, token, latitude.secret from locationbot.nick join locationbot.latitude using (id)')
  230. for nick, channels, old_location, granularity, token, secret in cursor.fetchall():
  231. try:
  232. updated, coordinates, accuracy, speed, heading, altitude, altitude_accuracy, new_location = self.__latitude(granularity, token, secret)
  233. except Exception, error:
  234. print error
  235. continue
  236. cursor.execute('update locationbot.nick set granularity = %s, location = %s, coordinates = point %s, updated = %s where nick = %s', (granularity, new_location, coordinates, updated, nick))
  237. db.commit()
  238. self.__location(nick, channels, granularity, old_location, new_location, coordinates)
  239. except psycopg2.Error, error:
  240. print error
  241. with self.__latitude_timer_lock:
  242. self.__latitude_timer = threading.Timer((self.__latitude_next - datetime.utcnow()).seconds, self.__latitude)
  243. self.__latitude_timer.start()
  244. def __location(self, nick, channels, granularity, old_location, new_location, coordinates):
  245. if channels and new_location and new_location != old_location:
  246. with self.__locations_lock:
  247. for channel in self.__channels.intersection(channels):
  248. self.__locations.append((nick, channel, granularity, new_location, coordinates))
  249. def __login(self, connection, nickmask, nick, arguments = ''):
  250. login = nick
  251. if connection is not None:
  252. arguments = arguments.split(None, 1)
  253. if len(arguments) == 2:
  254. login, secret = arguments
  255. elif len(arguments) == 1:
  256. secret = arguments[0]
  257. else:
  258. secret = None
  259. else:
  260. secret = None
  261. if nick in self.__logins:
  262. login = self.__logins[nick][0]
  263. if connection is not None:
  264. return connection.privmsg(nick, 'already logged in as "%s"' % login)
  265. return login
  266. db, cursor = self.__db()
  267. def success():
  268. connection.privmsg(nick, 'successfully logged in as "%s"' % login)
  269. if secret is not None:
  270. cursor.execute('select true from locationbot.nick where nick = %s and secret = md5(%s)', (login, secret))
  271. if cursor.rowcount == 1:
  272. self.__logins[nick] = (login, nickmask)
  273. return success()
  274. cursor.execute('select nick, masks from locationbot.nick where nick in (%s, %s)', (login, secret if len(arguments) != 2 else None))
  275. for login, masks in cursor.fetchall():
  276. if _or(lambda mask: irclib.mask_matches(nickmask, mask), masks):
  277. self.__logins[nick] = (login, nickmask)
  278. return success() if connection else login
  279. if connection is not None:
  280. return connection.privmsg(nick, 'failed to log in as "%s"' % login)
  281. def __logout(self, connection, nick):
  282. connection.privmsg(nick, 'logged out as "%s"' % self.__logins.pop(nick)[0])
  283. def __part(self, connection, nick, arguments):
  284. arguments = arguments.split(None, 1)
  285. if len(arguments) == 2:
  286. channel, message = arguments
  287. message = ':' + message
  288. elif len(arguments) == 1:
  289. channel = arguments[0]
  290. message = ''
  291. else:
  292. return self.__help(connection, nick, True, False, 'part')
  293. if channel in self.__channels:
  294. connection.part(channel, message)
  295. self.__channels.remove(channel)
  296. self.__config.set(self._nickname, 'channels', ' '.join(self.__channels))
  297. self.__write()
  298. connection.privmsg(nick, 'successfully parted channel ("%s")' % channel)
  299. else:
  300. connection.privmsg(nick, 'not in channel ("%s")' % channel)
  301. def __quit(self, connection, nick, arguments):
  302. self.__reloading = True
  303. self.__quiting = True
  304. connection.privmsg(nick, 'quiting')
  305. self.disconnect(arguments)
  306. def __register(self, connection, nick, arguments):
  307. arguments = arguments.split(None, 1)
  308. if len(arguments) == 2:
  309. login, secret = arguments
  310. elif len(arguments) == 1:
  311. login = nick
  312. secret = arguments[0]
  313. else:
  314. return self.__help(connection, nick, False, False, 'register')
  315. db, cursor = self.__db()
  316. try:
  317. cursor.execute('insert into locationbot.nick (nick, secret) values (%s, md5(%s))', (login, secret))
  318. db.commit()
  319. except psycopg2.IntegrityError:
  320. return connection.privmsg(nick, 'nick ("%s") is already registered' % login)
  321. connection.privmsg(nick, 'nick ("%s") sucessfully registered' % login)
  322. def __reload(self, connection, nick):
  323. self.__nick = nick
  324. self.__reloading = True
  325. connection.privmsg(nick, 'reloading')
  326. def __restart(self, connection):
  327. connection.disconnect('restarting')
  328. os.execvp(sys.argv[0], sys.argv)
  329. def __say(self, connection, nick, arguments):
  330. try:
  331. nick_channel, message = arguments.split(None, 1)
  332. except ValueError:
  333. return self.__help(connection, nick, True, False, 'say')
  334. if irclib.is_channel(nick_channel):
  335. if nick_channel not in self.channels:
  336. return connection.privmsg(nick, 'not in channel ("%s")' % nick_channel)
  337. elif not self.__channel(nick_channel):
  338. return connection.privmsg(nick, 'nick ("%s") not in channel(s)' % nick_channel)
  339. elif nick_channel == connection.get_nickname():
  340. return connection.privmsg(nick, 'nice try')
  341. connection.privmsg(nick_channel, message)
  342. connection.privmsg(nick, 'successfully sent message ("%s") to nick/channel ("%s")' % (message, nick_channel))
  343. def __set(self, connection, nickmask, nick, login, arguments):
  344. arguments = arguments.split(None, 1)
  345. if len(arguments) == 2:
  346. variable, value = arguments
  347. elif len(arguments) == 1:
  348. variable = arguments[0]
  349. value = None
  350. else:
  351. variable = None
  352. value = None
  353. if variable is not None and variable not in self.__variables:
  354. return self.__unknown_variable(connection, nick, variable)
  355. db, cursor = self.__db()
  356. if value is None:
  357. variables = sorted(self.__variables) if variable is None else [variable]
  358. cursor.execute('select ' + ', '.join(map(lambda variable: "'%s'" % ('*' * 8) if variable == 'secret' else 'latitude.granularity, latitude.authorized' if variable == 'latitude' else variable, variables)) + ' from locationbot.nick join locationbot.latitude using (id) where nick = %s', (login,))
  359. values = list(cursor.fetchone())
  360. try:
  361. index = variables.index('latitude')
  362. values[index:index + 2] = ['%s (%s)' % (values[index], 'authorized' if values[index + 1] else 'unauthorized')]
  363. except ValueError:
  364. pass
  365. connection.privmsg(nick, '\x02variable value\x0f')
  366. for variable, value in zip(variables, values):
  367. connection.privmsg(nick, '%-11s %s' % (variable, ' '.join(value) if isinstance(value, list) else '%f,%f' % value if isinstance(value, tuple) else value))
  368. else:
  369. def invalid(value, variable = variable):
  370. connection.privmsg(nick, 'invalid %s ("%s")' % (variable, value))
  371. if variable in self.__lists:
  372. value = value.split()
  373. if variable == 'channels':
  374. for channel in value:
  375. if not irclib.is_channel(channel) or channel not in self.__channels:
  376. return invalid(channel, 'channel')
  377. elif variable == 'masks':
  378. _mask = re.compile('^.+!.+@.+$')
  379. for mask in value:
  380. if not _mask.match(mask):
  381. return invalid(mask, 'mask')
  382. elif variable == 'latitude':
  383. if value in self.__latitude_granularities:
  384. response, content = oauth.Client(self.__latitude_consumer).request('https://www.google.com/accounts/OAuthGetRequestToken', 'POST', urllib.urlencode({
  385. 'scope': 'https://www.googleapis.com/auth/latitude',
  386. 'oauth_callback': 'oob',
  387. }))
  388. if int(response['status']) != 200:
  389. raise Exception(content.strip())
  390. authorized = False
  391. else:
  392. cursor.execute('select channels, location, latitude.granularity, token, latitude.secret from locationbot.nick join locationbot.latitude using (id) where nick = %s and authorized = false', (login,))
  393. if cursor.rowcount == 0:
  394. return invalid(value)
  395. channels, old_location, granularity, token, secret = cursor.fetchone()
  396. token = oauth.Token(token, secret)
  397. token.set_verifier(value)
  398. response, content = oauth.Client(self.__latitude_consumer, token).request('https://www.google.com/accounts/OAuthGetAccessToken', 'GET')
  399. status = int(response['status'])
  400. if status == 400:
  401. return invalid(value)
  402. elif status != 200:
  403. raise Exception(content.strip())
  404. authorized = True
  405. data = dict(urlparse.parse_qsl(content))
  406. token = data['oauth_token']
  407. secret = data['oauth_token_secret']
  408. if not authorized:
  409. connection.privmsg(nick, 'go to https://www.google.com/latitude/apps/OAuthAuthorizeToken?' + urllib.urlencode({
  410. 'domain': self.__latitude_key,
  411. 'granularity': value,
  412. 'oauth_token': token,
  413. }))
  414. elif variable in self.__geocode_variables:
  415. cursor.execute('select channels, location from locationbot.nick where nick = %s', (login,))
  416. channels, old_location = cursor.fetchone()
  417. if variable == 'location':
  418. coordinates = None
  419. granularity = 'city'
  420. location = value
  421. else:
  422. coordinates = value.split(None, 1)
  423. if len(coordinates) == 1:
  424. coordinates = coordinates[0].split(',', 1)
  425. try:
  426. coordinates = tuple(map(lambda a: float(a), coordinates))
  427. except ValueError:
  428. return invalid(value)
  429. for coordinate in coordinates:
  430. if not -180.0 <= coordinate <= 180.0:
  431. return invalid(value)
  432. granularity = 'best'
  433. location = None
  434. geocode = self.__geocode(False, coordinates, location)
  435. new_location = geocode[1]
  436. if variable == 'location':
  437. coordinates = geocode[0]
  438. value = new_location
  439. else:
  440. value = coordinates
  441. elif variable == 'nick':
  442. _nick = value.split(None, 1)
  443. if len(_nick) != 1:
  444. return invalid(value)
  445. elif variable == 'timezone':
  446. if value not in pytz.all_timezones_set:
  447. return invalid(value)
  448. try:
  449. if variable in self.__geocode_variables:
  450. cursor.execute('update locationbot.nick set granularity = %s, location = %s, coordinates = point %s, updated = now() where nick = %s', (granularity, new_location, coordinates, login))
  451. elif variable == 'latitude':
  452. if authorized:
  453. cursor.execute('update locationbot.latitude set token = %s, secret = %s, authorized = %s from locationbot.nick where latitude.id = nick.id and nick = %s', (token, secret, authorized, login))
  454. else:
  455. cursor.execute('delete from locationbot.latitude using locationbot.nick where latitude.id = nick.id and nick = %s', (login,))
  456. cursor.execute('insert into locationbot.latitude (id, granularity, token, secret, authorized) select id, %s, %s, %s, %s from locationbot.nick where nick = %s', (value, token, secret, authorized, login))
  457. else:
  458. cursor.execute('update locationbot.nick set ' + variable + ' = ' + ('md5(%s)' if variable == 'secret' else '%s') + ' where nick = %s', (value, login))
  459. db.commit()
  460. except psycopg2.IntegrityError:
  461. if variable == 'nick':
  462. return connection.privmsg(nick, 'nick ("%s") is already registered' % value)
  463. raise
  464. connection.privmsg(nick, 'variable ("%s") successfully set to value ("%s")' % (variable, ' '.join(value) if isinstance(value, list) else '%f,%f' % value if isinstance(value, tuple) else value))
  465. if variable == 'nick':
  466. self.__logins[nick] = (value, nickmask)
  467. elif variable in self.__geocode_variables or variable == 'latitude' and authorized:
  468. if variable == 'latitude':
  469. updated, coordinates, accuracy, speed, heading, altitude, altitude_accuracy, new_location = self.__latitude(granularity, token, secret)
  470. cursor.execute('update locationbot.nick set granularity = %s, location = %s, coordinates = point %s, updated = %s where nick = %s', (granularity, new_location, coordinates, updated, login))
  471. self.__location(login, channels, granularity, old_location, new_location, coordinates)
  472. def __status(self, connection, nick, login, arguments):
  473. _nick = arguments.split(None, 1)[0] if arguments else None
  474. db, cursor = self.__db()
  475. cursor.execute('select nick, location, coordinates, updated from locationbot.nick where ' + ('nick = %s and ' if _nick is not None else '') + 'location is not null order by updated desc', (_nick,))
  476. if cursor.rowcount == 0:
  477. return connection.privmsg(nick, 'no location information for ' + ('"%s"' % _nick if _nick is not None else 'anybody'))
  478. locations = cursor.fetchall()
  479. if login is not None:
  480. cursor.execute('select timezone from locationbot.nick where nick = %s and timezone is not null', (login,))
  481. timezone = pytz.timezone(cursor.fetchone()[0]) if cursor.rowcount == 1 else pytz.utc
  482. else:
  483. timezone = pytz.utc
  484. connection.privmsg(nick, '\x02nick location when map\x0f')
  485. for _nick, location, coordinates, updated in locations:
  486. connection.privmsg(nick, '%-23s %-35s %-23s %s' % (_nick, location, timezone.normalize(updated.astimezone(timezone)).strftime('%Y-%m-%d %H:%M %Z'), self.__url(_nick, 'best', location, coordinates)))
  487. def __unknown(self, connection, nick, command):
  488. connection.privmsg(nick, 'unknown command ("%s"); try "help"' % command)
  489. def __unknown_variable(self, connection, nick, variable):
  490. connection.privmsg(nick, 'unknown variable ("%s")' % variable)
  491. def __unset(self, connection, nick, login, arguments):
  492. try:
  493. variable = irclib.irc_lower(arguments.split(None, 1)[0])
  494. except IndexError:
  495. return self.__help(connection, nick, False, login, 'unset')
  496. if variable not in self.__unsetable:
  497. if variable in self.__variables:
  498. return connection.privmsg(nick, 'variable ("%s") is not unsetable' % variable)
  499. return self.__unknown_variable(connection, nick, variable)
  500. db, cursor = self.__db()
  501. cursor.execute('update locationbot.nick set ' + ('location = null, coordinates = null, updated = null' if variable in self.__geocode_variables else variable + ' = null') + ' where nick = %s and ' + variable + ' is not null', (login,))
  502. db.commit()
  503. connection.privmsg(nick, 'variable ("%s") %s unset' % (variable, 'successfuly' if cursor.rowcount == 1 else 'already'))
  504. def __url(self, nick, granularity, location, coordinates):
  505. if granularity == 'best':
  506. location = '%f,%f' % coordinates
  507. return 'http://maps.google.com/maps?' + urllib.urlencode({'q': '%s (%s)' % (location, nick)})
  508. def __who(self, connection, nick):
  509. if self.__logins:
  510. connection.privmsg(nick, '\x02login nick nick mask\x0f')
  511. for login in sorted(self.__logins.values()):
  512. connection.privmsg(nick, '%-23s %s' % login)
  513. else:
  514. connection.privmsg(nick, 'nobody logged in')
  515. def __write(self):
  516. with open('locationbot.ini', 'w') as config:
  517. self.__config.write(config)
  518. def _connect(self):
  519. if len(self.server_list[0]) != 2:
  520. ssl = self.server_list[0][2]
  521. else:
  522. ssl = False
  523. if len(self.server_list[0]) == 4:
  524. password = self.server_list[0][3]
  525. else:
  526. password = None
  527. try:
  528. with warnings.catch_warnings():
  529. warnings.filterwarnings('ignore', r'socket\.ssl\(\) is deprecated\. Use ssl\.wrap_socket\(\) instead\.', DeprecationWarning)
  530. self.connect(self.server_list[0][0], self.server_list[0][1], self._nickname, password, getpass.getuser(), self._realname, localaddress = self.__hostname, ssl = ssl)
  531. except irclib.ServerConnectionError:
  532. pass
  533. def disconnect(self, message = 'oh no!'):
  534. ircbot.SingleServerIRCBot.disconnect(self, message)
  535. def error(self, error):
  536. print error
  537. self.connection.privmsg(self.__nick, 'an error occured')
  538. def get_version(self):
  539. return 'locationbot ' + sys.platform
  540. def on_kick(self, connection, event):
  541. nick = event.arguments()[0]
  542. if not self.__channel(nick, event.target()):
  543. self.__logins.pop(nick, None)
  544. def on_nick(self, connection, event):
  545. nickmask = event.source()
  546. login = self.__logins.pop(irclib.nm_to_n(nickmask), (None,))[0]
  547. if login is not None:
  548. nick = event.target()
  549. self.__logins[nick] = (login, nick + '!' + nm_to_uh(nickmask))
  550. def on_nicknameinuse(self, connection, event):
  551. connection.nick(connection.get_nickname() + '_')
  552. def on_part(self, connection, event):
  553. nick = irclib.nm_to_n(event.source())
  554. if not self.__channel(nick, event.target()):
  555. self.__logins.pop(nick, None)
  556. def on_privmsg(self, connection, event):
  557. nickmask = event.source()
  558. nick = irclib.nm_to_n(nickmask)
  559. admin = self.__admin(nickmask)
  560. if not admin and not self.__channel(nick):
  561. return
  562. try:
  563. login = self.__login(None, nickmask, nick)
  564. try:
  565. command, arguments = event.arguments()[0].split(None, 1)
  566. except ValueError:
  567. command = event.arguments()[0].strip()
  568. arguments = ''
  569. command = irclib.irc_lower(command.lstrip('!'))
  570. if command == 'help':
  571. self.__help(connection, nick, admin, login, arguments)
  572. elif command == 'login':
  573. self.__login(connection, nickmask, nick, arguments)
  574. elif command == 'status':
  575. self.__status(connection, nick, login, arguments)
  576. elif not login and command == 'register':
  577. self.__register(connection, nick, arguments)
  578. elif login and command == 'logout':
  579. self.__logout(connection, nick)
  580. elif login and command == 'set':
  581. self.__set(connection, nickmask, nick, login, arguments)
  582. elif login and command == 'unset':
  583. self.__unset(connection, nick, login, arguments)
  584. elif admin and command == 'join':
  585. self.__join(connection, nick, arguments)
  586. elif admin and command == 'part':
  587. self.__part(connection, nick, arguments)
  588. elif admin and command == 'quit':
  589. self.__quit(connection, nick, arguments)
  590. elif admin and command == 'reload':
  591. self.__reload(connection, nick)
  592. elif admin and command == 'restart':
  593. self.__restart(connection)
  594. elif admin and command == 'say':
  595. self.__say(connection, nick, arguments)
  596. elif admin and command == 'who':
  597. self.__who(connection, nick)
  598. else:
  599. self.__unknown(connection, nick, command)
  600. except Exception, error:
  601. print error
  602. connection.privmsg(nick, 'an error occurred')
  603. def on_quit(self, connection, event):
  604. self.__logins.pop(irclib.nm_to_n(event.source()), None)
  605. def on_welcome(self, connection, event):
  606. for channel in self.__channels:
  607. connection.join(channel)
  608. def start(self):
  609. latitude_thread = threading.Thread(None, self.__latitude)
  610. latitude_thread.daemon = True
  611. latitude_thread.start()
  612. geocode_cache_clean_thread = threading.Thread(None, self.__geocode_cache_clean)
  613. geocode_cache_clean_thread.daemon = True
  614. geocode_cache_clean_thread.start()
  615. if not self.__reloading:
  616. self._connect()
  617. else:
  618. self.__reloading = False
  619. for channel in self.__channels.symmetric_difference(self.channels.keys()):
  620. if channel in self.__channels:
  621. self.connection.join(channel)
  622. else:
  623. self.connection.part(channel)
  624. while not self.__reloading:
  625. if self.__locations_lock.acquire(False):
  626. if self.__locations and self.__channels.issubset(self.channels.keys()):
  627. for nick, channel, granularity, location, coordinates in self.__locations:
  628. self.connection.notice(channel, '%s is in %s %s' % (nick, location, self.__url(nick, granularity, location, coordinates)))
  629. self.__locations = []
  630. self.__locations_lock.release()
  631. self.ircobj.process_once(0.2)
  632. latitude_thread.join()
  633. geocode_cache_clean_thread.join()
  634. with self.__latitude_timer_lock:
  635. if self.__latitude_timer is not None:
  636. self.__latitude_timer.cancel()
  637. self.__latitude_timer.join()
  638. with self.__geocode_cache_clean_timer_lock:
  639. if self.__geocode_cache_clean_timer is not None:
  640. self.__geocode_cache_clean_timer.cancel()
  641. self.__geocode_cache_clean_timer.join()
  642. return not self.__quiting
  643. def success(self):
  644. self.connection.privmsg(self.__nick, 'successfully reloaded')
  645. def _or(function, values):
  646. for value in values:
  647. if function(value):
  648. return True
  649. return False
  650. if __name__ == '__main__':
  651. os.chdir(os.path.abspath(os.path.dirname(__file__)))
  652. pid = os.fork()
  653. if pid != 0:
  654. with open('locationbot.pid', 'w') as _file:
  655. _file.write('%u\n' % pid)
  656. sys.exit(0)
  657. sys.stdin = open('/dev/null')
  658. sys.stdout = open('locationbot.log', 'a', 1)
  659. sys.stderr = sys.stdout
  660. import locationbot
  661. bot = locationbot.LocationBot()
  662. try:
  663. while bot.start():
  664. import locationbot
  665. try:
  666. bot = reload(locationbot).LocationBot(bot)
  667. except (ImportError, SyntaxError), error:
  668. bot.error(error)
  669. else:
  670. bot.success()
  671. except KeyboardInterrupt:
  672. bot.disconnect()
  673. os.unlink('locationbot.pid')