eae95b1ad5c6acaf524a7b93638ab33a628a20e7
[pywienerlinien] / gotovienna / cache.py
1 from os import path
2 import json
3 import shutil
4 import defaults
5 import realtime
6
7
8 def load(p, typ):
9     if path.exists(p):
10         try:
11             with open(p, 'r') as f:
12                 j = json.load(f)
13                 if type(j) == typ:
14                     return j
15                 else:
16                     print 'Unexpected content in cache file'
17                     print 'rebuilding cache'
18                     shutil.copy(p, p + '.bak')
19         except ValueError:
20             # FIXME check if empty
21             print 'Corrupt cache file'
22             print 'rebuilding cache'
23             shutil.copy(p, p + '.bak')
24
25     return None
26
27
28 class Lines(dict):
29     def __init__(self):
30         self.load()
31
32     def __setitem__(self, *args, **kwargs):
33         s = dict.__setitem__(self, *args, **kwargs)
34         self.save()
35         return s
36
37     def save(self):
38         with open(defaults.cache_lines, 'w') as fp:
39             json.dump(self, fp)
40
41     def load(self):
42         l = load(defaults.cache_lines, dict)
43         if l:
44             self.update(l)
45
46 lines = Lines()
47
48 class Stations(dict):
49     stations = None
50
51     def __init__(self, line):
52         """ loads cache files
53         behaves as dict of directions/stations of line
54         automatically saves cache on updates
55         """
56         if Stations.stations == None:
57             Stations.load()
58
59         self.current_line = line
60         if line in Stations.stations:
61             self.update(Stations.stations[line])
62         # FIXME maybe cause problems in the future, race conditions
63         Stations.stations[line] = self
64
65     def __setitem__(self, *args, **kwargs):
66         u = dict.__setitem__(self, *args, **kwargs)
67         Stations.save()
68         return u
69
70     @classmethod
71     def save(cls):
72         with open(defaults.cache_stations, 'w') as fp:
73             json.dump(Stations.stations, fp)
74
75     @classmethod
76     def load(cls):
77         s = load(defaults.cache_stations, dict)
78         if s:
79             cls.stations = s
80         else:
81             cls.stations = {}