Last active 1454995119

Revision b9db1c3cb7cc3c73fb43eba3626b74d27103454b

iinet_usage.py Raw
1#!/usr/bin/env python3
2from requests import get
3from os import environ
4from sys import exit, stderr, stdout
5
6STDOUT = stdout
7
8# http://stackoverflow.com/a/1094933
9def sizeof_fmt(num, suffix='B'):
10 for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:
11 if abs(num) < 1024.0:
12 return "%3.1f%s%s" % (num, unit, suffix)
13 num /= 1024.0
14 return "%.1f%s%s" % (num, 'Yi', suffix)
15
16def get_service_data(token=None, service=None):
17 url = "https://toolbox.iinet.net.au/cgi-bin/api.cgi?Usage&_TOKEN={}&_SERVICE={}"
18 try:
19 data = get(url.format(environ["IINET_TOKEN"], environ["IINET_SERVICE"])).json()
20 return data
21 except KeyError:
22 return False
23
24def prompt(p=None):
25 if p:
26 stderr.write(str(p))
27 return input()
28
29def format_usage(data):
30 try:
31 data = data["response"]["usage"]["traffic_types"][0]
32 return "{} remaining ({} used)".format(sizeof_fmt(data["allocation"] - data["used"]), sizeof_fmt(data["used"]))
33 except KeyError:
34 return False
35
36def refresh_token():
37 print("Tokens need refreshing", file=stderr)
38 from getpass import getpass
39 try:
40 yn = prompt("Want to do that now? [y] ") or "y"
41 if yn and yn[0].lower() == "y":
42 user = prompt("Username: ")
43 westnet = prompt("Westnet account? [n] ") or "n"
44 if westnet and westnet[0].lower() == "y":
45 user += "@westnet.com.au"
46 password = getpass()
47 data = get("https://toolbox.iinet.net.au/cgi-bin/api.cgi", params={"_USERNAME": user, "_PASSWORD": password}).json()
48 if "token" in data:
49 print("export IINET_TOKEN=" + data["token"])
50 print("\n".join([ "{}\t{}".format(i, sv["pk_v"]) for i, sv in enumerate(data["response"]["service_list"]) if "Usage" in sv["actions"] ]), file=stderr)
51 id_num = prompt("Please select a service (using the ID number): ") or ""
52 if id_num and id_num.isdigit():
53 print("export IINET_SERVICE=" + data["response"]["service_list"][int(id_num)]["s_token"])
54 else:
55 print("Invalid ID number, please try again", file=stderr)
56 return 1
57 return 0
58 else:
59 raise KeyboardInterrupt
60 except KeyboardInterrupt:
61 return 130
62
63def main():
64 data = format_usage(get_service_data())
65 if data:
66 print(data, file=stderr)
67 exit(0)
68 else:
69 exit(refresh_token())
70
71if __name__ == "__main__":
72 main()
zExample.txt Raw
1$ usage >> .bash_profile
2Tokens need refreshing
3Want to do that now? [y] y
4Username: {redacted}
5Westnet account? [n] y
6Password:
71 {my phone number}
84 {other number 1}
910 {other number 2}
1011 {other number 3}
1113 {email address}
12Please select a service (using the ID number): 1
13$ tail -n2 .bash_profile
14export IINET_TOKEN=RiceTYp{redacted}
15export IINET_SERVICE=90b41e3{redacted}
16$ source .bash_profile
17$ usage
183.4GiB remaining (286.8MiB used)
19$