locationbot.py 36 KB

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