locationbot.py 32 KB

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