locationbot.py 33 KB

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