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

Last change on this file since 3421 was 3421, checked in by daduve, 3 years ago

Adding new function to share group in n4d variable and set user default at login screen

File size: 7.9 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,n4d_mode=None):
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    if not n4d_mode:
117        try:
118            f=open(filename)
119            data = json.loads(f.read())
120            f.close()
121        except:
122            return ([],[])
123    else:
124        try:
125            import xmlrpclib as x
126            c=x.ServerProxy("https://server:9779")
127            data=c.get_variable("","VariablesManager","EPOPTES_GROUPS")
128
129            #print "***** EPOPTES N4D DATA: [%s] ..."%data
130            # If not exists value to EPOPTES GROUP in N4D, .config/epoptes/groups.json is listed
131            if data==None or data=={}:
132                f=open(filename)
133                data = json.loads(f.read())
134                f.close()
135            #raise Exception
136        except:
137            return ([],[])
138   
139    saved_clients = {}
140
141    for key, cln in data['clients'].iteritems():
142        new = structs.Client('offline', cln['mac'], '', cln['alias'])
143        saved_clients[key] = new
144
145    groups = []
146    for grp in data['groups']:
147        members = {}
148        for key, dct in grp['members'].iteritems():
149            members[saved_clients[key]] = dct
150   
151        groups.append(structs.Group(grp['name'], members))
152   
153    return (saved_clients.values(), groups)
154   
155def save_groups(filename, model,n4d_mode=None):
156    """Save the groups and their members from model (gtk.ListStore)
157    in JSON format.
158    """
159
160    path = os.path.expanduser('~/.config/epoptes/')
161    try:
162        if not os.path.isdir(path):
163            os.makedirs(path)
164    except:
165        pass
166   
167    data = {'clients' : {}, 'groups' : []}
168    uid=0
169    uid_pairs = {}
170    saved_clients = []
171   
172    # Create a list with all the clients we want to save
173    for grp in model:
174        grp = grp[G_INSTANCE]
175        for cln in grp.get_members():
176            if cln not in saved_clients:
177                saved_clients.append(cln)
178   
179    for cln in saved_clients:
180        # Use an integer ID as a key instead of the memory address
181        data['clients'][uid] = {'mac' : cln.mac, 'alias' : cln.alias}
182        # Pair memory addresses with integer IDs
183        uid_pairs[cln] = uid
184        uid += 1
185
186    for grp in model:
187        grp = grp[G_INSTANCE]
188        members = {}
189       
190        # Get the IDs created above
191        for cln, props in grp.members.iteritems():
192            members[uid_pairs[cln]] = props
193       
194       
195        data['groups'].append({'name' : grp.name, 
196                               'members' : members})
197       
198    # Save the dict in JSON format
199    try:
200        f=open(filename, 'w')
201        f.write(json.dumps(data, indent=2))
202        f.close()
203        #print "JSON ESCRITO"
204    except:
205        pass
206    valor=str(n4d_mode)
207    #print "N4D_MODE POSEEEEEEE EL VALOR DE: %s" %valor
208    if n4d_mode!=None:
209        import xmlrpclib as x
210        c=x.ServerProxy("https://server:9779")
211
212        # Just in case EPOPTES_GROUPS Variable does not exist
213        #print c.add_variable(n4d_mode,"VariablesManager","EPOPTES_GROUPS",{},"","Epoptes Groups",[],False,False)
214        if c.add_group(n4d_mode,"EpoptesVariables",n4d_mode)[0]:
215
216                #print c.set_variable(n4d_mode,"VariablesManager","EPOPTES_GROUPS",data)
217                c.set_group(n4d_mode,"EpoptesVariables",n4d_mode,data)
218
219
220def write_history():
221    write_plain_file(os.path.join(path, 'history'), history)
222
223
224# The system settings are shared with epoptes-clients, that's why the caps.
225system = read_shell_file('/etc/default/epoptes')
226# TODO: check if the types, e.g. PORT=int, may cause problems.
227system.setdefault('PORT', 789)
228system.setdefault('SOCKET_GROUP', 'epoptes')
229system.setdefault('DIR', '/var/run/epoptes')
230# Allow running unencrypted, for clients with very low RAM.
231try:
232    if os.path.getsize('/etc/epoptes/server.crt') == 0:
233        system.setdefault('ENCRYPTION', False)
234except:
235    pass
236finally:
237    system.setdefault('ENCRYPTION', True)
238
239
240path = os.path.expanduser('~/.config/epoptes/')
241settings_file = os.path.join(path, 'settings')
242settings = read_ini_file(settings_file)
243if not settings.has_section('GUI'):
244    settings.add_section('GUI')
245user = {}
246if settings.has_option('GUI', 'thumbnails_width'):
247    user['thumbnails_width'] = settings.getint('GUI', 'thumbnails_width')
248if settings.has_option('GUI', 'thumbnails_height'):
249    user['thumbnails_height'] = settings.getint('GUI', 'thumbnails_height')
250if not settings.has_option('GUI', 'messages_default_title'):
251    settings.set('GUI', 'messages_default_title', _('Message from administrator'))
252if not settings.has_option('GUI', 'messages_use_markup'):
253    settings.set('GUI', 'messages_use_markup', 'False')
254if not settings.has_option('GUI', 'grabkbdptr'):
255    settings.set('GUI', 'grabkbdptr', 'False')
256
257history = read_plain_file(os.path.join(path, 'history'))
258
259# For debugging reasons, if ran from command line, dump the config
260if __name__ == '__main__':
261    print system
262
Note: See TracBrowser for help on using the repository browser.