source: epoptes/trunk/fuentes/epoptes/common/config.py @ 295

Last change on this file since 295 was 295, checked in by mabarracus, 3 years ago

copy trusty epoptes code

File size: 6.7 KB
Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3
4###########################################################################
5# Configuration file parser and other default configuration variables.
6#
7# Copyright (C) 2011 Alkis Georgopoulos <alkisg@gmail.com>
8# Copyright (C) 2011 Fotis Tsamis <ftsamis@gmail.com>
9#
10# This program is free software: you can redistribute it and/or modify
11# it under the terms of the GNU General Public License as published by
12# the Free Software Foundation, either version 3 of the License, or
13# (at your option) any later version.
14#
15# This program is distributed in the hope that it will be useful,
16# but WITHOUT ANY WARRANTY; without even the implied warranty of
17# MERCHANTABILITY or FINESS FOR A PARTICULAR PURPOSE.  See the
18# GNU General Public License for more details.
19#
20# You should have received a copy of the GNU General Public License
21# along with this program.  If not, see <http://www.gnu.org/licenses/>.
22#
23# On Debian GNU/Linux systems, the complete text of the GNU General
24# Public License can be found in `/usr/share/common-licenses/GPL".
25###########################################################################
26
27import os
28import shlex
29import ConfigParser
30import json
31import gettext
32gettext.install('epoptes', unicode=True)
33import locale
34locale.textdomain('epoptes')
35
36from epoptes.core import structs
37from epoptes.common.constants import *
38
39def read_plain_file(filename):
40    """Return the whole contents of a plain text file into a string list.
41
42    If the file doesn't exist or isn't readable, return an empty list.
43    """
44   
45    try:
46        f = open(filename, 'r')
47        contents = [x.strip() for x in f.readlines()]
48        f.close()
49        return contents
50    except:
51        return []
52
53
54def write_plain_file(filename, contents):
55    """Write the contents string list to filename. Return True if successful.
56    """
57
58    try:
59        if not os.path.isdir(path):
60            os.makedirs(path)
61        f = open(filename, 'w')
62        f.write('\n'.join(contents))
63        return True
64    except:
65        return False
66
67
68def read_ini_file(filename):
69    """Return a ConfigParser from the contents of a configuration file.
70    """
71    conf = ConfigParser.ConfigParser()
72    try:
73        conf.read(filename)
74    except:
75        pass
76    return conf
77
78
79def write_ini_file(filename, contents):
80    """Write contents to a ConfigParser file. Return True if successful.
81    """
82    conf = contents
83    try:
84        conf.write(filename)
85        return True
86    except:
87        return False
88
89
90def read_shell_file(filename):
91    """Return the variables of a shell-like configuration file in a dict.
92
93    If the file doesn't exist or isn't readable, return an empty list.
94    Also strip all comments, if any.
95    """
96   
97    if not os.path.isfile(filename):
98        return {}
99    try:
100        f = open(filename, 'r')
101        contents = f.read()
102        f.close()
103        contents = shlex.split(contents, True)
104        # TODO: maybe return at least all the valid pairs?
105        return dict(v.split('=') for v in contents)
106    except:
107        return {}
108
109def read_groups(filename):
110    """Parse a JSON file and create the appropriate group and
111    client objects.
112   
113    Return a 2-tuple with a client instances list and a group
114    instances list.
115    """
116    try:
117        f=open(filename)
118        data = json.loads(f.read())
119        f.close()
120    except:
121        return ([],[])
122   
123    saved_clients = {}
124
125    for key, cln in data['clients'].iteritems():
126        new = structs.Client('offline', cln['mac'], '', cln['alias'])
127        saved_clients[key] = new
128
129    groups = []
130    for grp in data['groups']:
131        members = {}
132        for key, dct in grp['members'].iteritems():
133            members[saved_clients[key]] = dct
134   
135        groups.append(structs.Group(grp['name'], members))
136   
137    return (saved_clients.values(), groups)
138   
139def save_groups(filename, model):
140    """Save the groups and their members from model (gtk.ListStore)
141    in JSON format.
142    """
143
144    path = os.path.expanduser('~/.config/epoptes/')
145    try:
146        if not os.path.isdir(path):
147            os.makedirs(path)
148    except:
149        pass
150   
151    data = {'clients' : {}, 'groups' : []}
152    uid=0
153    uid_pairs = {}
154    saved_clients = []
155   
156    # Create a list with all the clients we want to save
157    for grp in model:
158        grp = grp[G_INSTANCE]
159        for cln in grp.get_members():
160            if cln not in saved_clients:
161                saved_clients.append(cln)
162   
163    for cln in saved_clients:
164        # Use an integer ID as a key instead of the memory address
165        data['clients'][uid] = {'mac' : cln.mac, 'alias' : cln.alias}
166        # Pair memory addresses with integer IDs
167        uid_pairs[cln] = uid
168        uid += 1
169
170    for grp in model:
171        grp = grp[G_INSTANCE]
172        members = {}
173       
174        # Get the IDs created above
175        for cln, props in grp.members.iteritems():
176            members[uid_pairs[cln]] = props
177       
178       
179        data['groups'].append({'name' : grp.name, 
180                               'members' : members})
181       
182    # Save the dict in JSON format
183    try:
184        f=open(filename, 'w')
185        f.write(json.dumps(data, indent=2))
186        f.close()
187    except:
188        pass
189
190def write_history():
191    write_plain_file(os.path.join(path, 'history'), history)
192
193
194# The system settings are shared with epoptes-clients, that's why the caps.
195system = read_shell_file('/etc/default/epoptes')
196# TODO: check if the types, e.g. PORT=int, may cause problems.
197system.setdefault('PORT', 789)
198system.setdefault('SOCKET_GROUP', 'epoptes')
199system.setdefault('DIR', '/var/run/epoptes')
200# Allow running unencrypted, for clients with very low RAM.
201try:
202    if os.path.getsize('/etc/epoptes/server.crt') == 0:
203        system.setdefault('ENCRYPTION', False)
204except:
205    pass
206finally:
207    system.setdefault('ENCRYPTION', True)
208
209
210path = os.path.expanduser('~/.config/epoptes/')
211settings_file = os.path.join(path, 'settings')
212settings = read_ini_file(settings_file)
213if not settings.has_section('GUI'):
214    settings.add_section('GUI')
215user = {}
216if settings.has_option('GUI', 'thumbnails_width'):
217    user['thumbnails_width'] = settings.getint('GUI', 'thumbnails_width')
218if settings.has_option('GUI', 'thumbnails_height'):
219    user['thumbnails_height'] = settings.getint('GUI', 'thumbnails_height')
220if not settings.has_option('GUI', 'messages_default_title'):
221    settings.set('GUI', 'messages_default_title', _('Message from administrator'))
222if not settings.has_option('GUI', 'messages_use_markup'):
223    settings.set('GUI', 'messages_use_markup', 'False')
224if not settings.has_option('GUI', 'grabkbdptr'):
225    settings.set('GUI', 'grabkbdptr', 'False')
226
227history = read_plain_file(os.path.join(path, 'history'))
228
229# For debugging reasons, if ran from command line, dump the config
230if __name__ == '__main__':
231    print system
232
Note: See TracBrowser for help on using the repository browser.