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