locationbot.py 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046
  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 _encode(u'%.1f\xb0 (%s)' % (heading, _heading_to_direction(heading)))
  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 KeyError, error:
  244. print nick, error
  245. continue
  246. except Exception, error:
  247. traceback.print_exc()
  248. continue
  249. 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))
  250. db.commit()
  251. 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)
  252. except psycopg2.Error, error:
  253. traceback.print_exc()
  254. with self.__latitude_timer_lock:
  255. self.__latitude_timer = threading.Timer((self.__latitude_next - datetime.utcnow()).seconds, self.__latitude)
  256. self.__latitude_timer.start()
  257. 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):
  258. def calc_distance(lat1, lon1, lat2, lon2): # returns meters
  259. nauticalMilePerLat = 60.00721
  260. nauticalMilePerLongitude = 60.10793
  261. rad = math.pi / 180.0
  262. milesPerNauticalMile = 1.15078
  263. metersPerNauticalMile = 1852
  264. yDistance = (lat2 - lat1) * nauticalMilePerLat
  265. xDistance = (math.cos(lat1 * rad) + math.cos(lat2 * rad)) * \
  266. (lon2 - lon1) * (nauticalMilePerLongitude / 2)
  267. distance = math.sqrt( yDistance**2 + xDistance**2 )
  268. return distance * metersPerNauticalMile
  269. def make_update_noise():
  270. with self.__locations_lock:
  271. for channel in self.__channels.intersection(channels):
  272. self.__locations.append((nick, channel, granularity, new_location, new_coordinates, new_accuracy, new_speed, new_heading, new_altitude, new_altitude_accuracy))
  273. if channels:
  274. if new_location != old_location: # old method
  275. return make_update_noise()
  276. distance = calc_distance(old_coordinates[0], old_coordinates[1],
  277. new_coordinates[0], new_coordinates[1])
  278. if distance < self.min_update_distance:
  279. return
  280. if old_accuracy is not None and new_accuracy is not None:
  281. avg_radius = (old_accuracy + new_accuracy) / 2
  282. if distance > avg_radius:
  283. return make_update_noise()
  284. min_radius = min(old_accuracy, new_accuracy)
  285. if distance > min_radius and new_accuracy < old_accuracy:
  286. return make_update_noise()
  287. def __login(self, connection, nickmask, nick, arguments = ''):
  288. login = nick
  289. if connection is not None:
  290. arguments = arguments.split(None, 1)
  291. if len(arguments) == 2:
  292. login, secret = arguments
  293. elif len(arguments) == 1:
  294. secret = arguments[0]
  295. else:
  296. secret = None
  297. else:
  298. secret = None
  299. if nick in self.__logins:
  300. login = self.__logins[nick][0]
  301. if connection is not None:
  302. return connection.privmsg(nick, 'already logged in as "%s"' % login)
  303. return login
  304. db, cursor = self.__db()
  305. def success():
  306. connection.privmsg(nick, 'successfully logged in as "%s"' % login)
  307. if secret is not None:
  308. cursor.execute('select true from locationbot.nick where nick = %s and secret = md5(%s)', (login, secret))
  309. if cursor.rowcount == 1:
  310. self.__logins[nick] = (login, nickmask)
  311. return success()
  312. cursor.execute('select nick, masks from locationbot.nick where nick in (%s, %s)', (login, secret if len(arguments) != 2 else None))
  313. for login, masks in cursor.fetchall():
  314. if _or(lambda mask: irclib.mask_matches(nickmask, mask), masks):
  315. self.__logins[nick] = (login, nickmask)
  316. return success() if connection else login
  317. if connection is not None:
  318. return connection.privmsg(nick, 'failed to log in as "%s"' % login)
  319. def __logout(self, connection, nick):
  320. connection.privmsg(nick, 'logged out as "%s"' % self.__logins.pop(nick)[0])
  321. def __part(self, connection, nick, arguments):
  322. arguments = arguments.split(None, 1)
  323. if len(arguments) == 2:
  324. channel, message = arguments
  325. message = ':' + message
  326. elif len(arguments) == 1:
  327. channel = arguments[0]
  328. message = ''
  329. else:
  330. return self.__help(connection, nick, True, False, 'part')
  331. if channel in self.__channels:
  332. connection.part(channel, message)
  333. self.__channels.remove(channel)
  334. self.__config.set(self._nickname, 'channels', ' '.join(self.__channels))
  335. self.__write()
  336. connection.privmsg(nick, 'successfully parted channel ("%s")' % channel)
  337. else:
  338. connection.privmsg(nick, 'not in channel ("%s")' % channel)
  339. def __quit(self, connection, nick, arguments):
  340. self.__reloading = True
  341. self.__quiting = True
  342. connection.privmsg(nick, 'quiting')
  343. self.disconnect(arguments)
  344. def __register(self, connection, nick, arguments):
  345. arguments = arguments.split(None, 1)
  346. if len(arguments) == 2:
  347. login, secret = arguments
  348. elif len(arguments) == 1:
  349. login = nick
  350. secret = arguments[0]
  351. else:
  352. return self.__help(connection, nick, False, False, 'register')
  353. db, cursor = self.__db()
  354. try:
  355. cursor.execute('insert into locationbot.nick (nick, secret) values (%s, md5(%s))', (login, secret))
  356. db.commit()
  357. except psycopg2.IntegrityError:
  358. return connection.privmsg(nick, 'nick ("%s") is already registered' % login)
  359. connection.privmsg(nick, 'nick ("%s") sucessfully registered' % login)
  360. def __reload(self, connection, nick):
  361. self.__nick = nick
  362. self.__reloading = True
  363. connection.privmsg(nick, 'reloading')
  364. def __restart(self, connection):
  365. connection.disconnect('restarting')
  366. os.execvp(sys.argv[0], sys.argv)
  367. def __say(self, connection, nick, arguments):
  368. try:
  369. nick_channel, message = arguments.split(None, 1)
  370. except ValueError:
  371. return self.__help(connection, nick, True, False, 'say')
  372. if irclib.is_channel(nick_channel):
  373. if nick_channel not in self.channels:
  374. return connection.privmsg(nick, 'not in channel ("%s")' % nick_channel)
  375. elif not self.__channel(nick_channel):
  376. return connection.privmsg(nick, 'nick ("%s") not in channel(s)' % nick_channel)
  377. elif nick_channel == connection.get_nickname():
  378. return connection.privmsg(nick, 'nice try')
  379. connection.privmsg(nick_channel, message)
  380. connection.privmsg(nick, 'successfully sent message ("%s") to nick/channel ("%s")' % (message, nick_channel))
  381. def __set(self, connection, nickmask, nick, login, arguments):
  382. arguments = arguments.split(None, 1)
  383. if len(arguments) == 2:
  384. variable, value = arguments
  385. elif len(arguments) == 1:
  386. variable = arguments[0]
  387. value = None
  388. else:
  389. variable = None
  390. value = None
  391. if variable is not None and variable not in self.__variables:
  392. return self.__unknown_variable(connection, nick, variable)
  393. db, cursor = self.__db()
  394. if value is None:
  395. variables = sorted(self.__variables) if variable is None else [variable]
  396. 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,))
  397. values = list(cursor.fetchone())
  398. try:
  399. index = variables.index('latitude')
  400. values[index:index + 2] = ['%s (%s)' % (values[index], 'authorized' if values[index + 1] else 'unauthorized')]
  401. except ValueError:
  402. pass
  403. connection.privmsg(nick, '\x02variable value\x0f')
  404. for variable, value in zip(variables, values):
  405. connection.privmsg(nick, '%-11s %s' % (variable, ' '.join(value) if isinstance(value, list) else '%f,%f' % value if isinstance(value, tuple) else value))
  406. else:
  407. def invalid(value, variable = variable):
  408. connection.privmsg(nick, 'invalid %s ("%s")' % (variable, value))
  409. if variable in self.__lists:
  410. value = value.split()
  411. if variable == 'channels':
  412. for channel in value:
  413. if not irclib.is_channel(channel) or channel not in self.__channels:
  414. return invalid(channel, 'channel')
  415. elif variable == 'masks':
  416. _mask = re.compile('^.+!.+@.+$')
  417. for mask in value:
  418. if not _mask.match(mask):
  419. return invalid(mask, 'mask')
  420. elif variable == 'latitude':
  421. if value in self.__latitude_granularities:
  422. response, content = oauth.Client(self.__latitude_consumer, timeout = self.__timeout).request('https://www.google.com/accounts/OAuthGetRequestToken', 'POST', urllib.urlencode({
  423. 'scope': 'https://www.googleapis.com/auth/latitude',
  424. 'oauth_callback': 'oob',
  425. }))
  426. if int(response['status']) != 200:
  427. raise Exception(content.strip())
  428. authorized = False
  429. else:
  430. 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,))
  431. if cursor.rowcount == 0:
  432. return invalid(value)
  433. channels, old_location, granularity, token, secret = cursor.fetchone()
  434. token = oauth.Token(token, secret)
  435. token.set_verifier(value)
  436. response, content = oauth.Client(self.__latitude_consumer, token, timeout = self.__timeout).request('https://www.google.com/accounts/OAuthGetAccessToken', 'GET')
  437. status = int(response['status'])
  438. if status == 400:
  439. return invalid(value)
  440. elif status != 200:
  441. raise Exception(content.strip())
  442. authorized = True
  443. data = dict(urlparse.parse_qsl(content))
  444. token = data['oauth_token']
  445. secret = data['oauth_token_secret']
  446. if not authorized:
  447. connection.privmsg(nick, 'go to https://www.google.com/latitude/apps/OAuthAuthorizeToken?' + urllib.urlencode({
  448. 'domain': self.__latitude_client_id,
  449. 'granularity': value,
  450. 'oauth_token': token,
  451. }))
  452. elif variable in self.__geocode_variables:
  453. cursor.execute('select channels, location, latitude.granularity, token, latitude.secret, authorized from locationbot.nick left join locationbot.latitude using (id) where nick = %s', (login,))
  454. channels, old_location, granularity, token, secret, authorized = cursor.fetchone()
  455. if variable == 'location':
  456. coordinates = None
  457. granularity = 'city'
  458. location = value
  459. else:
  460. coordinates = value.split(None, 1)
  461. if len(coordinates) == 1:
  462. coordinates = coordinates[0].split(',', 1)
  463. try:
  464. coordinates = tuple(map(lambda a: float(a), coordinates))
  465. except ValueError:
  466. return invalid(value)
  467. for coordinate in coordinates:
  468. if not -180.0 <= coordinate <= 180.0:
  469. return invalid(value)
  470. location = None
  471. geocode = self.__geocode(False, coordinates, location)
  472. new_location = geocode[1]
  473. if variable == 'location':
  474. coordinates = geocode[0]
  475. value = new_location
  476. else:
  477. value = coordinates
  478. if authorized:
  479. 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': {
  480. 'kind': 'latitude#location',
  481. 'latitude': coordinates[0],
  482. 'longitude': coordinates[1],
  483. }}), {'Content-Type': 'application/json'})
  484. if int(response['status']) != 200:
  485. raise Exception(content.strip())
  486. accuracy = speed = heading = altitude = altitude_accuracy = None
  487. elif variable == 'nick':
  488. _nick = value.split(None, 1)
  489. if len(_nick) != 1:
  490. return invalid(value)
  491. elif variable == 'timezone':
  492. if value not in pytz.all_timezones_set:
  493. return invalid(value)
  494. try:
  495. if variable in self.__geocode_variables:
  496. 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))
  497. elif variable == 'latitude':
  498. if authorized:
  499. 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))
  500. else:
  501. cursor.execute('delete from locationbot.latitude using locationbot.nick where latitude.id = nick.id and nick = %s', (login,))
  502. 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))
  503. else:
  504. cursor.execute('update locationbot.nick set ' + variable + ' = ' + ('md5(%s)' if variable == 'secret' else '%s') + ' where nick = %s', (value, login))
  505. db.commit()
  506. except psycopg2.IntegrityError:
  507. if variable == 'nick':
  508. return connection.privmsg(nick, 'nick ("%s") is already registered' % value)
  509. raise
  510. 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))
  511. if variable == 'nick':
  512. self.__logins[nick] = (value, nickmask)
  513. elif variable in self.__geocode_variables or variable == 'latitude' and authorized:
  514. if variable == 'latitude':
  515. updated, coordinates, accuracy, speed, heading, altitude, altitude_accuracy, new_location = self.__latitude(granularity, token, secret)
  516. 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))
  517. self.__location(login, channels, granularity, old_location, new_location, None, coordinates, None, accuracy, None, speed, None, heading, None, altitude, None, altitude_accuracy, None, updated)
  518. def __speed(self, speed):
  519. if speed is not None:
  520. return '%.1f m/s (%.1f mph)' % (speed, _meters_per_second_to_miles_per_hour(speed))
  521. def __status(self, connection, nick, login, arguments):
  522. _nick = arguments.split(None, 1)[0] if arguments else None
  523. db, cursor = self.__db()
  524. 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,))
  525. if cursor.rowcount == 0:
  526. return connection.privmsg(nick, 'no location information for ' + ('"%s"' % _nick if _nick is not None else 'anybody'))
  527. locations = cursor.fetchall()
  528. if login is not None:
  529. cursor.execute('select timezone from locationbot.nick where nick = %s and timezone is not null', (login,))
  530. timezone = pytz.timezone(cursor.fetchone()[0]) if cursor.rowcount == 1 else pytz.utc
  531. else:
  532. timezone = pytz.utc
  533. connection.privmsg(nick, '\x02%-24s%-36s%-24s%-24s%-16s%-24s%-24s%-24s%s\x0f' % ('nick', 'location', 'accuracy', 'speed', 'heading', 'altitude', 'altitude accuracy', 'when', 'map'))
  534. for _nick, granularity, location, coordinates, accuracy, speed, heading, altitude, altitude_accuracy, updated in locations:
  535. 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)))
  536. def __unknown(self, connection, nick, command):
  537. connection.privmsg(nick, 'unknown command ("%s"); try "help"' % command)
  538. def __unknown_variable(self, connection, nick, variable):
  539. connection.privmsg(nick, 'unknown variable ("%s")' % variable)
  540. def __unset(self, connection, nick, login, arguments):
  541. try:
  542. variable = irclib.irc_lower(arguments.split(None, 1)[0])
  543. except IndexError:
  544. return self.__help(connection, nick, False, login, 'unset')
  545. if variable not in self.__unsetable:
  546. if variable in self.__variables:
  547. return connection.privmsg(nick, 'variable ("%s") is not unsetable' % variable)
  548. return self.__unknown_variable(connection, nick, variable)
  549. db, cursor = self.__db()
  550. 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,))
  551. db.commit()
  552. connection.privmsg(nick, 'variable ("%s") %s unset' % (variable, 'successfuly' if cursor.rowcount == 1 else 'already'))
  553. def __url(self, nick, granularity, location, coordinates):
  554. if granularity == 'best':
  555. location = '%f,%f' % coordinates
  556. 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)}))
  557. def __who(self, connection, nick):
  558. if self.__logins:
  559. connection.privmsg(nick, '\x02login nick nick mask\x0f')
  560. for login in sorted(self.__logins.values()):
  561. connection.privmsg(nick, '%-23s %s' % login)
  562. else:
  563. connection.privmsg(nick, 'nobody logged in')
  564. def __write(self):
  565. with open('locationbot.ini', 'w') as config:
  566. self.__config.write(config)
  567. def _connect(self):
  568. if len(self.server_list[0]) != 2:
  569. ssl = self.server_list[0][2]
  570. else:
  571. ssl = False
  572. if len(self.server_list[0]) == 4:
  573. password = self.server_list[0][3]
  574. else:
  575. password = None
  576. try:
  577. with warnings.catch_warnings():
  578. warnings.filterwarnings('ignore', r'socket\.ssl\(\) is deprecated\. Use ssl\.wrap_socket\(\) instead\.', DeprecationWarning)
  579. self.connect(self.server_list[0][0], self.server_list[0][1], self._nickname, password, getpass.getuser(), self._realname, localaddress = self.__hostname, ssl = ssl)
  580. except irclib.ServerConnectionError:
  581. pass
  582. def disconnect(self, message = 'oh no!'):
  583. ircbot.SingleServerIRCBot.disconnect(self, message)
  584. def error(self, error):
  585. traceback.print_exc()
  586. self.connection.privmsg(self.__nick, 'an error occured')
  587. def get_version(self):
  588. return 'locationbot ' + sys.platform
  589. def on_kick(self, connection, event):
  590. nick = event.arguments()[0]
  591. if not self.__channel(nick, event.target()):
  592. self.__logins.pop(nick, None)
  593. def on_nick(self, connection, event):
  594. nickmask = event.source()
  595. login = self.__logins.pop(irclib.nm_to_n(nickmask), (None,))[0]
  596. if login is not None:
  597. nick = event.target()
  598. self.__logins[nick] = (login, nick + '!' + irclib.nm_to_uh(nickmask))
  599. def on_nicknameinuse(self, connection, event):
  600. connection.nick(connection.get_nickname() + '_')
  601. def on_part(self, connection, event):
  602. nick = irclib.nm_to_n(event.source())
  603. if not self.__channel(nick, event.target()):
  604. self.__logins.pop(nick, None)
  605. def on_privmsg(self, connection, event):
  606. nickmask = event.source()
  607. nick = irclib.nm_to_n(nickmask)
  608. admin = self.__admin(nickmask)
  609. if not admin and not self.__channel(nick):
  610. return
  611. try:
  612. login = self.__login(None, nickmask, nick)
  613. try:
  614. command, arguments = event.arguments()[0].split(None, 1)
  615. except ValueError:
  616. command = event.arguments()[0].strip()
  617. arguments = ''
  618. command = irclib.irc_lower(command.lstrip('!'))
  619. if command == 'help':
  620. self.__help(connection, nick, admin, login, arguments)
  621. elif command == 'login':
  622. self.__login(connection, nickmask, nick, arguments)
  623. elif command == 'status':
  624. self.__status(connection, nick, login, arguments)
  625. elif not login and command == 'register':
  626. self.__register(connection, nick, arguments)
  627. elif login and command == 'logout':
  628. self.__logout(connection, nick)
  629. elif login and command == 'set':
  630. self.__set(connection, nickmask, nick, login, arguments)
  631. elif login and command == 'unset':
  632. self.__unset(connection, nick, login, arguments)
  633. elif admin and command == 'join':
  634. self.__join(connection, nick, arguments)
  635. elif admin and command == 'part':
  636. self.__part(connection, nick, arguments)
  637. elif admin and command == 'quit':
  638. self.__quit(connection, nick, arguments)
  639. elif admin and command == 'reload':
  640. self.__reload(connection, nick)
  641. elif admin and command == 'restart':
  642. self.__restart(connection)
  643. elif admin and command == 'say':
  644. self.__say(connection, nick, arguments)
  645. elif admin and command == 'who':
  646. self.__who(connection, nick)
  647. else:
  648. self.__unknown(connection, nick, command)
  649. except Exception, error:
  650. traceback.print_exc()
  651. connection.privmsg(nick, 'an error occurred')
  652. def on_quit(self, connection, event):
  653. self.__logins.pop(irclib.nm_to_n(event.source()), None)
  654. def on_welcome(self, connection, event):
  655. for channel in self.__channels:
  656. connection.join(channel)
  657. def start(self):
  658. latitude_thread = threading.Thread(None, self.__latitude)
  659. latitude_thread.daemon = True
  660. latitude_thread.start()
  661. geocode_cache_clean_thread = threading.Thread(None, self.__geocode_cache_clean)
  662. geocode_cache_clean_thread.daemon = True
  663. geocode_cache_clean_thread.start()
  664. if not self.__reloading:
  665. self._connect()
  666. else:
  667. self.__reloading = False
  668. for channel in self.__channels.symmetric_difference(self.channels.keys()):
  669. if channel in self.__channels:
  670. self.connection.join(channel)
  671. else:
  672. self.connection.part(channel)
  673. ping_next = datetime.utcnow() + timedelta(minutes = 1)
  674. while not self.__reloading:
  675. try:
  676. now = datetime.utcnow()
  677. if now >= ping_next:
  678. self.connection.ping(self.connection.server)
  679. ping_next = now + timedelta(minutes = 1)
  680. if self.__locations_lock.acquire(False):
  681. if self.__locations and self.__channels.issubset(self.channels.keys()):
  682. for nick, channel, granularity, location, coordinates, accuracy, speed, heading, altitude, altitude_accuracy in self.__locations:
  683. aux = []
  684. if accuracy is not None:
  685. aux.append('accuracy: ' + self.__distance(accuracy))
  686. if speed is not None:
  687. aux.append('speed: ' + self.__speed(speed))
  688. if heading is not None:
  689. aux.append(u'heading: ' + self.__heading(heading))
  690. if altitude is not None:
  691. aux.append('altitude: ' + self.__distance(altitude))
  692. if altitude_accuracy is not None:
  693. aux.append('altitude accuracy: ' + self.__distance(altitude_accuracy))
  694. if aux:
  695. aux = ' [%s]' % ', '.join(aux)
  696. else:
  697. aux = ''
  698. self.connection.notice(channel, '%s is in %s%s %s' % (nick, _encode(location), aux, self.__url(nick, granularity, location, coordinates)))
  699. self.__locations = []
  700. self.__locations_lock.release()
  701. except irclib.ServerNotConnectedError:
  702. self.jump_server()
  703. self.ircobj.process_once(0.2)
  704. latitude_thread.join()
  705. geocode_cache_clean_thread.join()
  706. with self.__latitude_timer_lock:
  707. if self.__latitude_timer is not None:
  708. self.__latitude_timer.cancel()
  709. self.__latitude_timer.join()
  710. with self.__geocode_cache_clean_timer_lock:
  711. if self.__geocode_cache_clean_timer is not None:
  712. self.__geocode_cache_clean_timer.cancel()
  713. self.__geocode_cache_clean_timer.join()
  714. return not self.__quiting
  715. def success(self):
  716. self.connection.privmsg(self.__nick, 'successfully reloaded')
  717. class _AddressMask(object):
  718. def __init__(self, function):
  719. self.function = function
  720. def __call__(self, nick, mask):
  721. if not self.function(nick, mask):
  722. nick, address = nick.split('@', 1)
  723. try:
  724. host = socket.gethostbyaddr(address)[0]
  725. except socket.herror:
  726. pass
  727. else:
  728. if host != address:
  729. return self.function(nick + '@' + host, mask)
  730. return False
  731. return True
  732. irclib.mask_matches = _AddressMask(reload(irclib).mask_matches)
  733. def _encode(string):
  734. try:
  735. return string.encode('latin1')
  736. except UnicodeEncodeError:
  737. return string.encode('utf8')
  738. def _meters_per_second_to_miles_per_hour(meters_per_second):
  739. return meters_per_second * 2.23693629
  740. def _meters_to_feet(meters):
  741. return meters * 3.2808399
  742. def _heading_to_direction(heading):
  743. heading %= 360
  744. if 348.75 < heading or heading <= 11.25:
  745. return 'N'
  746. elif 11.25 < heading <= 33.75:
  747. return 'NNE'
  748. elif 33.75 < heading <= 56.25:
  749. return 'NE'
  750. elif 56.25 < heading <= 78.75:
  751. return 'ENE'
  752. elif 78.75 < heading <= 101.25:
  753. return 'E'
  754. elif 101.25 < heading <= 123.75:
  755. return 'ESE'
  756. elif 123.75 < heading <= 146.25:
  757. return 'SE'
  758. elif 146.25 < heading <= 168.75:
  759. return 'SSE'
  760. elif 168.75 < heading <= 191.25:
  761. return 'S'
  762. elif 191.25 < heading <= 213.75:
  763. return 'SSW'
  764. elif 213.75 < heading <= 236.25:
  765. return 'SW'
  766. elif 236.25 < heading <= 258.75:
  767. return 'WSW'
  768. elif 258.75 < heading <= 281.25:
  769. return 'W'
  770. elif 281.25 < heading <= 303.75:
  771. return 'WNW'
  772. elif 303.75 < heading <= 326.25:
  773. return 'NW'
  774. else:
  775. return 'NNW'
  776. def _or(function, values):
  777. if values:
  778. for value in values:
  779. if function(value):
  780. return True
  781. return False
  782. if __name__ == '__main__':
  783. os.chdir(os.path.abspath(os.path.dirname(__file__)))
  784. pid = os.fork()
  785. if pid != 0:
  786. with open('locationbot.pid', 'w') as _file:
  787. _file.write('%u\n' % pid)
  788. sys.exit(0)
  789. sys.stdin = open('/dev/null')
  790. sys.stdout = open('locationbot.log', 'a', 1)
  791. sys.stderr = sys.stdout
  792. import locationbot
  793. bot = locationbot.LocationBot()
  794. try:
  795. while bot.start():
  796. import locationbot
  797. try:
  798. bot = reload(locationbot).LocationBot(bot)
  799. except (ImportError, SyntaxError), error:
  800. bot.error(error)
  801. else:
  802. bot.success()
  803. except KeyboardInterrupt:
  804. bot.disconnect()
  805. os.unlink('locationbot.pid')