wifigeoloc

Client for the Geolocation API of Mozilla and Google
git clone git://r-36.net/wifigeoloc
Log | Files | Refs | README | LICENSE

wifigeoloc (1903B)


      1 #!/usr/bin/env python3
      2 # coding=utf-8
      3 #
      4 # See LICENSE for license details.
      5 # by 20h
      6 #
      7 
      8 import os
      9 import sys
     10 import json
     11 import getopt
     12 import urllib.request, urllib.error
     13 
     14 apikey="something"
     15 bases = [
     16 	("moz", "https://location.services.mozilla.com/v1/geolocate?key=%s"),
     17 	("google", "https://www.googleapis.com/geolocation/v1/geolocate?key=&s")
     18 ]
     19 
     20 def usage(app):
     21 	app = os.path.basename(app)
     22 	sys.stderr.write("usage: %s [-h] [-a apikey] [-b baseuri]"\
     23 			" [-s service] mac [mac ...]\n" % (app))
     24 	sys.exit(1)
     25 
     26 def main(args):
     27 	global apikey
     28 	global bases
     29 
     30 	try:
     31 		opts, largs = getopt.getopt(args[1:], "a:b:s:")
     32 	except getopt.GetoptError as err:
     33 		print(str(err))
     34 		usage(args[0])
     35 
     36 	service = "moz"
     37 	lapikey = apikey
     38 	baseuri = None
     39 	
     40 	for o, a in opts:
     41 		if o == "-h":
     42 			usage(args[0])
     43 		elif o == "-a":
     44 			apikey = a
     45 		elif o == "-b":
     46 			baseuri = a
     47 		elif o == "-s":
     48 			service = a
     49 		else:
     50 			assert False, "unhandled option"
     51 
     52 	if len(largs) < 1:
     53 		usage(args[0])
     54 	
     55 	if baseuri == None:
     56 		for serv in bases:
     57 			if serv[0] == service:
     58 				baseuri = serv[1]
     59 
     60 		if baseuri == None:
     61 			sys.stderr.write("service '%s' not supported.\n" %\
     62 					(service))
     63 			return 1
     64 	uri = baseuri % (apikey)
     65 
     66 	sendjson = {}
     67 	sendjson["wifiAccessPoints"] = []
     68 	for mac in largs:
     69 		sendjson["wifiAccessPoints"].append({"macAddress": mac})
     70 
     71 	jsons = json.dumps(sendjson).encode("utf-8")
     72 	req = urllib.request.Request(uri)
     73 	req.add_header("Content-Type", "application/json")
     74 	fd = urllib.request.urlopen(req, data=jsons)
     75 	answer = json.loads(fd.read().decode("utf-8"))
     76 	fd.close()
     77 
     78 	if "error" in answer:
     79 		print(answer)
     80 		return 1
     81 
     82 	if "accuracy" in answer and "location" in answer:
     83 		if answer["accuracy"] > 30000:
     84 			return 1
     85 		print("%s,%s,%s" % (answer["location"]["lat"],\
     86 				answer["location"]["lng"],\
     87 				answer["accuracy"]))
     88 	else:
     89 		return 1
     90 
     91 	return 0
     92 
     93 if __name__ == "__main__":
     94 	sys.exit(main(sys.argv))
     95