locationbot.py 37 KB

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