print -> print_error
[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 # old stuff.. should be removed at some point
9 def replace_keys(obj, old_key, new_key):
10     if isinstance(obj, dict):
11         if old_key in obj:
12             obj[new_key] = obj[old_key]
13             del obj[old_key]
14         for elem in obj.itervalues():
15             replace_keys(elem, old_key, new_key)
16     elif isinstance(obj, list):
17         for elem in obj:
18             replace_keys(elem, old_key, new_key)
19
20 def old_to_new(d):
21     replace_keys(d, 'blk_hash', 'block_hash')
22     replace_keys(d, 'pos', 'index')
23     replace_keys(d, 'nTime', 'timestamp')
24     replace_keys(d, 'is_in', 'is_input')
25     replace_keys(d, 'raw_scriptPubKey', 'raw_output_script')
26
27
28
29 class SimpleConfig:
30
31     def __init__(self, options=None):
32
33         # system conf, readonly
34         self.system_config = {}
35         self.read_system_config()
36
37         # user conf, writeable
38         self.user_config = {}
39         self.read_user_config()
40
41         # command-line options
42         self.options_config = {}
43         if options:
44             if options.server: self.options_config['server'] = options.server
45             if options.proxy: self.options_config['proxy'] = options.proxy
46             if options.gui: self.options_config['gui'] = options.gui
47
48
49         self.wallet_config = {}
50         self.wallet_file_exists = False
51         path = None
52         if options:
53             # this will call read_wallet_config only if there is a wallet_path value in options
54             try:
55                 path = options.wallet_path
56             except:
57                 pass
58         if not path:
59             path = self.get('default_wallet_path')
60         print_error( "path", path )
61         if path:
62             self.read_wallet_config(path)
63             
64             
65         
66
67     def set_key(self, key, value, save = False):
68         # find where a setting comes from and save it there
69         if self.options_config.get(key) is not None:
70             print "Warning: not changing '%s' because it was passed as a command-line option"%key
71             return
72
73         elif self.user_config.get(key) is not None:
74             self.user_config[key] = value
75             if save: self.save_user_config()
76
77         elif self.system_config.get(key) is not None:
78             if str(self.system_config[key]) != str(value):
79                 print "Warning: not changing '%s' because it was set in the system configuration"%key
80
81         elif self.wallet_config.get(key) is not None:
82             self.wallet_config[key] = value
83             if save: self.save_wallet_config()
84
85         else:
86             # add key to wallet config
87             self.wallet_config[key] = value
88             if save: self.save_wallet_config()
89
90
91     def get(self, key, default=None):
92         # 1. command-line options always override everything
93         if self.options_config.has_key(key):
94             # print "found", key, "in options"
95             out = self.options_config.get(key)
96
97         # 2. user configuration 
98         elif self.user_config.has_key(key):
99             out = self.user_config.get(key)
100
101         # 2. system configuration
102         elif self.system_config.has_key(key):
103             out = self.system_config.get(key)
104
105         # 3. use the wallet file config
106         else:
107             out = self.wallet_config.get(key)
108
109         if out is None and default is not None:
110             out = default
111
112         # try to fix the type
113         if default is not None and type(out) != type(default):
114             import ast
115             try:
116                 out = ast.literal_eval(out)
117             except:
118                 print "type error, using default value"
119                 out = default
120
121         return out
122
123
124     def is_modifiable(self, key):
125         if self.options_config.has_key(key):
126             return False
127         elif self.user_config.has_key(key):
128             return True
129         elif self.system_config.has_key(key):
130             return False
131         else:
132             return True
133
134
135     def read_system_config(self):
136         name = '/etc/electrum.conf'
137         if os.path.exists(name):
138             try:
139                 import ConfigParser
140             except:
141                 print "cannot parse electrum.conf. please install ConfigParser"
142                 return
143                 
144             p = ConfigParser.ConfigParser()
145             p.read(name)
146             try:
147                 for k, v in p.items('client'):
148                     self.system_config[k] = v
149             except ConfigParser.NoSectionError:
150                 pass
151
152
153     def read_user_config(self):
154         name = os.path.join( user_dir(), 'electrum.conf')
155         if os.path.exists(name):
156             try:
157                 import ConfigParser
158             except:
159                 print "cannot parse electrum.conf. please install ConfigParser"
160                 return
161                 
162             p = ConfigParser.ConfigParser()
163             p.read(name)
164             try:
165                 for k, v in p.items('client'):
166                     self.user_config[k] = v
167             except ConfigParser.NoSectionError:
168                 pass
169
170
171     def init_path(self, wallet_path):
172         """Set the path of the wallet."""
173         if wallet_path is not None:
174             self.path = wallet_path
175             return
176
177         # Look for wallet file in the default data directory.
178         # Keeps backwards compatibility.
179         wallet_dir = user_dir()
180
181         # Make wallet directory if it does not yet exist.
182         if not os.path.exists(wallet_dir):
183             os.mkdir(wallet_dir)
184         self.path = os.path.join(wallet_dir, "electrum.dat")
185
186
187     def save_user_config(self):
188         import ConfigParser
189         config = ConfigParser.RawConfigParser()
190         config.add_section('client')
191         for k,v in self.user_config.items():
192             config.set('client', k, v)
193
194         with open( os.path.join( user_dir(), 'electrum.conf'), 'wb') as configfile:
195             config.write(configfile)
196         
197
198
199
200     def read_wallet_config(self, path):
201         """Read the contents of the wallet file."""
202         self.init_path(path)
203         try:
204             with open(self.path, "r") as f:
205                 data = f.read()
206         except IOError:
207             return
208         try:
209             d = ast.literal_eval( data )  #parse raw data from reading wallet file
210             old_to_new(d)
211         except:
212             raise IOError("Cannot read wallet file.")
213
214         self.wallet_config = d
215         self.wallet_file_exists = True
216
217
218
219     def save(self):
220         self.save_wallet_config()
221
222
223     def save_wallet_config(self):
224         s = repr(self.wallet_config)
225         f = open(self.path,"w")
226         f.write( s )
227         f.close()
228         import stat
229         os.chmod(self.path,stat.S_IREAD | stat.S_IWRITE)
230