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