locationbot.py 35 KB

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