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