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