-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathposten.py
executable file
·134 lines (100 loc) · 3.3 KB
/
posten.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
#!/usr/bin/env python
import json
import os
import pathlib
import time
import re
import datetime
import sys
import subprocess
import requests
def error(msg=''):
print('%{F#ff0000}', msg)
exit(0)
def load_config():
try:
with open(BASEDIR / 'config.json', 'r') as fh:
return json.load(fh)
except FileNotFoundError:
error('Config missing')
except json.decoder.JSONDecodeError:
error('Config invalid')
def convert_datetime(date):
m = re.findall(
pattern=r'\w+ \w+ [0-9.]+$',
string=date
)
date_string = m.pop()
date_string += f'{datetime.datetime.now().year}'
parsed_datetime = datetime.datetime.strptime(date_string, '%A %B %d %Y')
return parsed_datetime
def fetch_postal_data():
""" Fetches postal data from Posten.no """
cache_file = BASEDIR / 'cache.json'
postal_data = None
if os.path.exists(cache_file):
if time.time() - os.path.getmtime(cache_file) < 3600 * 4:
with open(cache_file, 'r') as fh:
postal_data = json.load(fh)
if postal_data is None:
result = requests.get(
url=API_URL,
headers={
'Referer': 'https://www.posten.no/en/delivery-mail',
'x-requested-with': 'XMLHttpRequest'
},
timeout=5
)
if result.status_code == 200:
postal_data = json.loads(result.content)
with open(cache_file, 'w+') as fh:
json.dump(postal_data, fh, indent=2)
else:
postal_data = {}
with open(cache_file, 'w+') as fh:
json.dump(postal_data, fh, indent=2)
error('No data')
return postal_data['nextDeliveryDays']
def bar_output():
next_delivery_date = fetch_postal_data()[0]
postal_date = next_delivery_date.split(' ')[0]
if postal_date in ['today', 'tomorrow']:
color_postal_date = postal_date
else:
color_postal_date = 'someday'
color = '%{{F{}}}'.format(CONFIG['colors'][color_postal_date])
return {
"icon": '',
"color": color,
"date": postal_date.capitalize(),
"unit": '',
}
def notify():
next_delivery_dates = fetch_postal_data()
dates_list = [ re.sub('(today|tomorrow) ', '', date) for date in next_delivery_dates ]
_output = ''
for date in dates_list:
_out = re.sub('(today|tomorrow) ', '', date)
_output += _out.rjust(25) + '\n'
subprocess.call(f"/usr/bin/notify-send 'Posten Delivery Dates' '{_output}'", shell=True)
return
def main():
if sys.argv.pop() == 'notify':
notify()
else:
DATA = bar_output()
print('{icon} {color}{date}'.format(**DATA))
BASEDIR = pathlib.Path(os.path.dirname(os.path.realpath(__file__)))
CONFIG = load_config()
API_URL = (
"https://www.posten.no/en/delivery-mail/_/component/main/1/leftRegion/11?postCode={postal_code}"
).format(**CONFIG)
if __name__ == "__main__":
try:
main()
except requests.ConnectTimeout:
error('Timeout') # https://fontawesome.com/icons/poo-storm?style=solid
except requests.ConnectionError:
error('Error')
except Exception as e: # pylint: disable=broad-except
error(f'Error: {e}') # https://fontawesome.com/icons/poo-storm?style=solid