Revert "added TypeError category to existing exception"
[electrum-nvc.git] / lib / simple_config.py
1 import json, ast
2 import os, ast
3 from util import user_dir, print_error
4
5 from version import ELECTRUM_VERSION, SEED_VERSION
6
7
8
9 class SimpleConfig:
10     """
11 The SimpleConfig class is responsible for handling operations involving
12 configuration files.  The constructor reads and stores the system and 
13 user configurations from electrum.conf into seperate dictionaries within
14 a SimpleConfig instance then reads the wallet file.
15 """
16     def __init__(self, options={}):
17
18         # system conf, readonly
19         self.system_config = {}
20         self.read_system_config()
21
22         # user conf, writeable
23         self.user_dir = user_dir()
24         self.user_config = {}
25         self.read_user_config()
26
27         # command-line options
28         self.options_config = options
29
30         self.wallet_config = {}
31         self.wallet_file_exists = False
32         self.init_path(self.options_config.get('wallet_path'))
33         print_error( "path", self.path )
34         if self.path:
35             self.read_wallet_config(self.path)
36             
37             
38             
39         
40
41     def set_key(self, key, value, save = False):
42         # find where a setting comes from and save it there
43         if self.options_config.get(key) is not None:
44             print "Warning: not changing '%s' because it was passed as a command-line option"%key
45             return
46
47         elif self.user_config.get(key) is not None:
48             self.user_config[key] = value
49             if save: self.save_user_config()
50
51         elif self.system_config.get(key) is not None:
52             if str(self.system_config[key]) != str(value):
53                 print "Warning: not changing '%s' because it was set in the system configuration"%key
54
55         elif self.wallet_config.get(key) is not None:
56             self.wallet_config[key] = value
57             if save: self.save_wallet_config()
58
59         else:
60             # add key to wallet config
61             self.wallet_config[key] = value
62             if save: self.save_wallet_config()
63
64
65     def get(self, key, default=None):
66         """Retrieve the filepath of the configuration file specified in the 'key' parameter."""
67         # 1. command-line options always override everything
68         if self.options_config.has_key(key) and self.options_config.get(key) is not None:
69             out = self.options_config.get(key)
70
71         # 2. user configuration 
72         elif self.user_config.has_key(key):
73             out = self.user_config.get(key)
74
75         # 2. system configuration
76         elif self.system_config.has_key(key):
77             out = self.system_config.get(key)
78
79         # 3. use the wallet file config
80         else:
81             out = self.wallet_config.get(key)
82
83         if out is None and default is not None:
84             out = default
85
86         # try to fix the type
87         if default is not None and type(out) != type(default):
88             import ast
89             try:
90                 out = ast.literal_eval(out)
91             except:
92                 print "type error, using default value"
93                 out = default
94
95         return out
96
97
98     def is_modifiable(self, key):
99         """Check if the config file is modifiable."""
100         if self.options_config.has_key(key):
101             return False
102         elif self.user_config.has_key(key):
103             return True
104         elif self.system_config.has_key(key):
105             return False
106         else:
107             return True
108
109
110     def read_system_config(self):
111         """Parse and store the system config settings in electrum.conf into system_config[]."""
112         name = '/etc/electrum.conf'
113         if os.path.exists(name):
114             try:
115                 import ConfigParser
116             except ImportError:
117                 print "cannot parse electrum.conf. please install ConfigParser"
118                 return
119                 
120             p = ConfigParser.ConfigParser()
121             p.read(name)
122             try:
123                 for k, v in p.items('client'):
124                     self.system_config[k] = v
125             except ConfigParser.NoSectionError:
126                 pass
127
128
129     def read_user_config(self):
130         """Parse and store the user config settings in electrum.conf into user_config[]."""
131         if not self.user_dir: return
132
133         name = os.path.join( self.user_dir, 'electrum.conf')
134         if os.path.exists(name):
135             try:
136                 import ConfigParser
137             except ImportError:
138                 print "cannot parse electrum.conf. please install ConfigParser"
139                 return
140                 
141             p = ConfigParser.ConfigParser()
142             p.read(name)
143             try:
144                 for k, v in p.items('client'):
145                     self.user_config[k] = v
146             except ConfigParser.NoSectionError:
147                 pass
148
149
150     def init_path(self, path):
151         """Set the path of the wallet."""
152
153         if not path:
154             path = self.get('default_wallet_path')
155
156         if path is not None:
157             self.path = path
158             return
159
160         # Look for wallet file in the default data directory.
161         # Make wallet directory if it does not yet exist.
162         if not os.path.exists(self.user_dir):
163             os.mkdir(self.user_dir)
164         self.path = os.path.join(self.user_dir, "electrum.dat")
165
166
167     def save_user_config(self):
168         if not self.user_dir: return
169
170         import ConfigParser
171         config = ConfigParser.RawConfigParser()
172         config.add_section('client')
173         for k,v in self.user_config.items():
174             config.set('client', k, v)
175
176         with open( os.path.join( self.user_dir, 'electrum.conf'), 'wb') as configfile:
177             config.write(configfile)
178         
179
180
181
182     def read_wallet_config(self, path):
183         """Read the contents of the wallet file."""
184         try:
185             with open(self.path, "r") as f:
186                 data = f.read()
187         except IOError:
188             return
189         try:
190             d = ast.literal_eval( data )  #parse raw data from reading wallet file
191         except:
192             raise IOError("Cannot read wallet file.")
193
194         self.wallet_config = d
195         self.wallet_file_exists = True
196
197
198
199     def save(self):
200         self.save_wallet_config()
201
202
203     def save_wallet_config(self):
204         s = repr(self.wallet_config)
205         f = open(self.path,"w")
206         f.write( s )
207         f.close()
208         if self.get('gui') != 'android':
209             import stat
210             os.chmod(self.path,stat.S_IREAD | stat.S_IWRITE)
211