locationbot.py 35 KB

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