locationbot.py 35 KB

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