Last active 1454995119

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 quota = data["response"]["usage"]["traffic_types"][0]
32 qr = data["response"]["quota_reset"]
33 return "{} remaining ({} per day), {} used. Resets on the {}{}".format(
34 sizeof_fmt(quota["allocation"] - quota["used"]),
35 sizeof_fmt((quota["allocation"] - quota["used"]) /
36 qr["days_remaining"]),
37 sizeof_fmt(quota["used"]),
38 qr["anniversary"],
39 "st" if qr["anniversary"] == 1 else "nd" if qr["anniversary"] == 2 else "rd" if qr["anniversary"] == 3 else "th"
40 )
41 except KeyError:
42 return False
43
44def refresh_token():
45 print("Tokens need refreshing", file=stderr)
46 from getpass import getpass
47 try:
48 yn = prompt("Want to do that now? [y] ") or "y"
49 if yn and yn[0].lower() == "y":
50 user = prompt("Username: ")
51 westnet = prompt("Westnet account? [n] ") or "n"
52 if westnet and westnet[0].lower() == "y":
53 user += "@westnet.com.au"
54 password = getpass()
55 data = get("https://toolbox.iinet.net.au/cgi-bin/api.cgi",
56 params={"_USERNAME": user, "_PASSWORD": password}).json()
57 if "token" in data:
58 print("export IINET_TOKEN=" + data["token"])
59 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)
60 id_num = prompt("Please select a service (using the ID number): ") or ""
61 if id_num and id_num.isdigit():
62 print("export IINET_SERVICE=" + data["response"]["service_list"][int(id_num)]["s_token"])
63 else:
64 print("Invalid ID number, please try again", file=stderr)
65 return 1
66 return 0
67 else:
68 raise KeyboardInterrupt
69 except KeyboardInterrupt:
70 return 130
71
72def main():
73 data = format_usage(get_service_data())
74 if data:
75 print(data, file=stderr)
76 exit(0)
77 else:
78 exit(refresh_token())
79
80if __name__ == "__main__":
81 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
182.8GiB remaining (282.7MiB per day), 988.0MiB used. Resets on the 19th
19$