handle empty string (!= None)
[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) 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             out = ast.literal_eval(out)
108             
109         return out
110
111
112     def is_modifiable(self, key):
113         if self.options_config.has_key(key):
114             return False
115         elif self.user_config.has_key(key):
116             return True
117         elif self.system_config.has_key(key):
118             return False
119         else:
120             return True
121
122
123     def read_system_config(self):
124         name = '/etc/electrum.conf'
125         if os.path.exists(name):
126             try:
127                 import ConfigParser
128             except:
129                 print "cannot parse electrum.conf. please install ConfigParser"
130                 return
131                 
132             p = ConfigParser.ConfigParser()
133             p.read(name)
134             try:
135                 for k, v in p.items('client'):
136                     self.system_config[k] = v
137             except ConfigParser.NoSectionError:
138                 pass
139
140
141     def read_user_config(self):
142         name = os.path.join( user_dir(), 'electrum.conf')
143         if os.path.exists(name):
144             try:
145                 import ConfigParser
146             except:
147                 print "cannot parse electrum.conf. please install ConfigParser"
148                 return
149                 
150             p = ConfigParser.ConfigParser()
151             p.read(name)
152             try:
153                 for k, v in p.items('client'):
154                     self.user_config[k] = v
155             except ConfigParser.NoSectionError:
156                 pass
157
158
159     def init_path(self, wallet_path):
160         """Set the path of the wallet."""
161         if wallet_path is not None:
162             self.path = wallet_path
163             return
164
165         # Look for wallet file in the default data directory.
166         # Keeps backwards compatibility.
167         wallet_dir = user_dir()
168
169         # Make wallet directory if it does not yet exist.
170         if not os.path.exists(wallet_dir):
171             os.mkdir(wallet_dir)
172         self.path = os.path.join(wallet_dir, "electrum.dat")
173
174
175     def save_user_config(self):
176         import ConfigParser
177         config = ConfigParser.RawConfigParser()
178         config.add_section('client')
179         for k,v in self.user_config.items():
180             config.set('client', k, v)
181
182         with open( os.path.join( user_dir(), 'electrum.conf'), 'wb') as configfile:
183             config.write(configfile)
184         
185
186
187
188     def read_wallet_config(self, path):
189         """Read the contents of the wallet file."""
190         self.wallet_file_exists = False
191         self.init_path(path)
192         try:
193             with open(self.path, "r") as f:
194                 data = f.read()
195         except IOError:
196             return
197         try:
198             d = ast.literal_eval( data )  #parse raw data from reading wallet file
199             old_to_new(d)
200         except:
201             raise IOError("Cannot read wallet file.")
202
203         self.wallet_config = d
204         self.wallet_file_exists = True
205
206
207
208     def save(self):
209         self.save_wallet_config()
210
211
212     def save_wallet_config(self):
213         s = repr(self.wallet_config)
214         f = open(self.path,"w")
215         f.write( s )
216         f.close()
217         import stat
218         os.chmod(self.path,stat.S_IREAD | stat.S_IWRITE)
219