source: tags/0.1.1/config.py @ 335

Revision 137, 6.9 KB checked in by marc, 5 years ago (diff)

Tagged 0.1.1

Line 
1#! /usr/bin/env python
2# -*- coding: utf8 -*-
3#
4# Itaka is free software; you can redistribute it and/or modify
5# it under the terms of the GNU General Public License as published by
6# the Free Software Foundation; either version 2 of the License, or
7# any later version.
8#
9# Itaka is distributed in the hope that it will be useful,
10# but WITHOUT ANY WARRANTY; without even the implied warranty of
11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12# GNU General Public License for more details.
13#
14# You should have received a copy of the GNU General Public License
15# along with Itaka; if not, write to the Free Software
16# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17#
18# Copyright 2003-2007 Marc E. <santusmarc_at_gmail.com>.
19# http://itaka.jardinpresente.com.ar
20#
21# $Id: config.py 126 2007-06-06 05:59:44Z marc $
22
23""" Itaka Configuration Parser and Engine """
24
25# It works by the core initiating the main instance, and the
26# modules accessing the global values variables set up by the initation.
27
28import ConfigParser, os, sys, shutil, traceback
29
30# Set up instance
31config = ConfigParser.ConfigParser()
32
33# Set up global variables
34local_config = os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), "itaka.conf")
35
36# Version (do not change)
37version = "0.1"
38revision = "$Rev"
39
40# Check system or specify per os.name standard
41system = os.name
42
43# Support darwin specific stuff
44platform = None
45if (sys.platform.startswith("darwin")): platform = "darwin"
46
47# Specify console output settings.
48# 'normal' is for all normal operation mesages and warnings (not including errors)
49# 'debug' is for all messages through self.console.debug
50# 'quiet' is to quiet all errors. (totally quiet is in conjunction with 'normal')
51output = {'normal': False, 'debug': False, 'quiet': False}
52
53# Itaka images/ directory
54# prefix will be changed on install to specify where the installed files are
55image_dir = os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), "share/images/")
56prefix = "/usr/share/itaka/images/"
57if os.path.exists(prefix):
58    image_dir = prefix
59
60# See if our images are there before starting
61if not os.path.exists(image_dir):
62    print "[*] ERROR: Could not find images directory '%s'" % (image_dir)
63    sys.exit(1)
64
65# Save path for screenshots (system-specific specified later on)
66save_path = os.getcwd()
67
68if os.environ.get('HOME') is not None:
69    save_path = os.path.join(os.environ.get('HOME'), ".itaka")
70else:
71    save_path = os.environ.get('TMP') or os.environ.get('TEMP')
72
73# Use notifications where libnotify is available
74notifyavailable = False
75if system == "posix" and platform != "darwin":
76    try:
77        import pynotify
78        notifyavailable = True
79
80        if not pynotify.init("Itaka"):
81            print "[*] WARNING: Pynotify module is failing, disabling notifications"
82            notifyavailable = False
83    except ImportError:
84        print "[*] WARNING: Pynotify module is missing, disabling notifications"
85        notifyavailable = False
86
87# User's configuration values
88values = {}
89
90class ConfigParser:             
91    def load(self, notify=True):
92        """Set up and load configuration. """
93        self.configfile = None
94
95        # Check routine
96        if system in ("posix"):
97            if not (os.path.exists(os.path.join(os.environ['HOME'], ".itaka/itaka.conf"))):
98                self.create(os.path.join(os.environ['HOME'], ".itaka/itaka.conf"))
99            else:
100                self.configfile = os.path.join(os.environ['HOME'], ".itaka/itaka.conf")
101        elif (system == "nt"):
102            if not (os.path.exists(os.path.join(os.environ['APPDATA'], "itaka/itaka.ini"))):
103                self.create(os.path.join(os.environ['APPDATA'], "itaka/itaka.ini"))
104            else:
105                self.configfile = os.path.join(os.environ['APPDATA'], "itaka/itaka.ini")
106        else:
107            # Generic system/paths (using local)       
108            if (os.path.exists(local_config)):
109                self.configfile = local_config
110            else:       
111                self.create(local_config)
112        # Read and assign values from the configuration file
113        try:
114            config.read(self.configfile)
115            if output['normal']: print "[*] Read configuration (%s)" % (self.configfile)
116
117        except:
118            if output['normal']: print "[*] ERROR: Could not read configuration file (%s)" % (self.configfile)
119            if output['debug']: traceback.print_exc()
120
121        """ Retrieve values and return them as a dict."""
122        global values
123        values = {}
124        # Get values as a dict and return it
125        for section in config.sections():
126            values[section] = dict(config.items(section))
127        return values
128
129    def save(self, valuesdict):
130        """ Saves a dict containing the configuration."""
131        # Unpack the dict into section, option, value
132        for section in valuesdict.keys():
133            for key, value in valuesdict[section].items():
134                config.set(section, key, value)
135
136        # Save
137        try:
138            config.write(open(self.configfile, 'w'))
139            if output['normal']: print "[*] Saving configuration... "   
140        except:         
141            if not output['quiet']: print "[*] ERROR: Could not write configuration file %s" % (self.configfile)
142            if output['debug']: traceback.print_exc()
143
144    def update(self, section, key, value):
145        """ Update a specific key's value."""   
146        config.set(section, key, value)
147        # Save
148        try:
149            config.write(open(self.configfile, 'w'))
150            if output['normal']: print "[*] Updating configuration key %s to %s" % (key, value)
151        except:
152            if not output['quiet']: print "[*] ERROR: Could not write configuration file %s" % (self.configfile)
153            if output['debug']: traceback.print_exc()
154
155    def create(self, path):
156        """ Create a configuration file from default values. """
157        # Create sections
158        for section in ('server', 'screenshot', 'html'): config.add_section(section)
159
160        if output['normal']: print "[*] Creating default configuration..."
161        # Set default values
162        config.set("server", "port", 8000)
163        config.set("server", "notify", notifyavailable)
164
165        config.set("screenshot", "format", "jpeg")
166        config.set("screenshot", "quality", 30)
167        config.set("screenshot", "path", save_path)
168
169        config.set("html", "html", '<html><body><img src="screenshot" alt="If you are seeing this message it means there was an error in Itaka or you are using a text-only browser." border="0"></a></body</html>')
170
171        # Check if the directory exists, if not create it
172        # and write the config file with its variables
173        if not (os.path.exists(os.path.dirname(path))):
174            shutil.os.mkdir(os.path.dirname(path))
175
176        try:
177            config.write(open(path, 'w'))
178        except:
179            if not output['quiet']: print "[*] ERROR: Could not write configuration file %s" % (path)
180            if output['debug']: traceback.print_exc()
181
182        self.configfile = path         
Note: See TracBrowser for help on using the repository browser.