Home Forums Wiki Doc Install Extras Screenshots Source Code Projects Blog Users Groups Register
Glx-Dock / Cairo-Dock List of forums Technical discussions | Discussions techniques Password Encryption
The latest stable release is the *3.4.0* : How to install it here.
Note: We just switched from BZR to Git on Github! (only to host the code and your future pull requests)
Technical discussions | Discussions techniques

Subjects Author Language Messages Last message
[Locked] Password Encryption [Bug #193]
Page : 1 2 3
jesuisbenjamin English 58

jesuisbenjamin, Sunday 15 May 2011 à 17:09


Subscription date : 28 October 2009
Messages : 415
Hi,

Well i wrote a script called HomeMadeConfigParser which is doing a better job than what the ConfigParser does. It's not complete yet, since i made it to fit my needs. Perhaps it can be improved for others to use since it is taylor-made for CD.
You get data with or without comments and set data with those comments, so that doesn't mess up the interface.
Usage is quite simple:


>>> import HomeMadeConfigParser
>>> parser=HomeMadeConfigParser.Parser()
>>> 
parser.read('./applet.conf')
>>> 
parser.iterate(sectionwith_comments=Trueprevious_lines=1)
>>> 
parser.get(sectionkeytype='str')
>>> 
parser.set(sectionkeyvalue, [comment1comment2]) 
etc.



Hope it's useful. Code here, below.
Will post that on LP.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#       HomeMadeConfigParser.py
#       
#       Copyright 2011 jesuisbenjamin <jesuisbenjamin@emailofasearchenginenamedafterlensestolookfar.com>
#       
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#       
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#       
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.
#       

class Parser(object):
    
def __init__(self):
        
self.path ''
        
self.conf = []
        
object.__init__(self)
        
    
def read(selfpath_to_conf_file):
        
""" Reads configuration file into a list """
        
self.conf = []
        
self.path path_to_conf_file
        
try:
            
self.conffile open(self.path'r')
            
mold self.conffile.readlines()
            
self.conffile.close()
            
# clean up end of line
            
for line in mold:
                
line line.rstrip()
                if 
len(line) > 0:
                    
self.conf.append(line)
                else:
                    continue
        
except:
            print 
"HomeMadeConfigParser Error: an error occurred while handling"self.path
            raise
    
    def findSection
(selfsection):
        
""" Looks for a section and returns its index """
        
        
if len(self.conf) > 0:
            
section '['+section+']'
            
# iterate the configuration information
            
iter(self.conf)
            
item ''
            
index = -1
            
# look for section
            
while item != section:
                try:
                    
item i.next()
                    
index += 1
                except
:
                    
raise NoSectionError(section)
            return 
index
        
else:
            
raise NoSectionError
            
    def iterate
(selfsectionwith_comment=Falseprevious_lines=1):
        
""" Returns a list of options in [key, value] lists
        for the given section.
        with_comment     (bool) --     set to False by default. Returns 
                                    comments if    set to True.
        previous_lines     (int)  --    set to 1 by default. Represents index
                                    of lines to return where 0 is the section
                                    name. To return previous lines set value
                                    to -n.
        """
        
if isinstance(sectionstr) \
        and 
isinstance(with_commentbool) \
        and 
isinstance(previous_linesint) \
        and 
previous_lines 2:
            
pass
        
else:
            
raise ArgError((sectionwith_commentprevious_lines))
        
# list in which we return options
        
option_list = []
        
# index of section
        
index self.findSection(section)
        
# add previous lines to list if any:
        # pre_index is the index of the previous line
        # it is set to 0 so we can enter loop
        
pre_index 0
        
# as long as there are previous lines to fetch
        
while previous_lines 1:
                
# get index of previous line relative to index
                
pre_index index previous_lines
                
# check we don't go below head of list
                
if pre_index > -1:
                    
# append to our output list
                    
option_list.append(self.conf[pre_index])
                else:
                    
pass
                
# reduce
                
previous_lines += 1
        
# if section found look for following options
        
option ' '
        
# as long as we don't reach next section
        
while option[0] != '[':
            
index += 1
            
try:
                
option self.conf[index]
                if 
with_comment == False and option[0] == '#':
                    
# if we don't want comments
                    
continue
                
elif with_comment == True and option[0] == '#':
                    
# if we do want comment
                    
option_list.append(option)
                else:
                    
# we got an option and return it as a pair
                    
pair option.split('=')
                    
# append the pair to the list
                    
option_list.append(pair)
            
except:
                
# we reached end of config
                
return option_list
        
return option_list
    
    def options
(selfsection):
        
""" Returns a list of options for a given section. """
        
pairs self.iterate(section)
        
options = []
        for 
pair in pairs:
            
options.append(pair[0])
        return 
options
    
    def sections
(self):
        
""" Returns a list of sections. """
        
sections = []
        for 
line in self.conf:
            if 
line[0] == '[':
                
sections.append(line.strip('[').strip(']'))
            else:
                continue
        return 
sections
    
    def get
(selfsectionkeyoutput_type='str'):
        
""" Returns the value of option based on given section and key. """
        
options self.iterate(section)
        
iter(options)
        
item ''
        
while item != key:
            try:
                
pair i.next()
                
item pair[0]
            
except:
                
# reached end of list
                
raise NoKeyError(key)
        
# format the output
        
if len(pair[-1]) > 0:
            if 
output_type == 'int':
                try:
                    
value int(pair[-1])
                
except:
                    
raise BadTypeError(output_typepair[-1])
            
elif output_type == 'float':
                try:
                    
value float(pair[-1])
                
except:
                    
raise BadTypeError(output_typepair[-1])
            
elif output_type == 'bool':
                if 
str.lower(pair[-1]) in 'true' or str.lower(pair[-1]) in 'false':
                    
value str.lower(pair[-1]) in 'true'
                
else:
                    
raise BadTypeError(output_typepair[-1])
            else:
                
# in that case we need a string
                
value str(pair[-1])
        else:
            
value pair[-1]
        return 
value
                    
    def set
(selfsectionkeyvalue=''comment=[]):
        
""" Sets new key-value pair to end of section,
        optionally preceded by a comment. If no value is
        specified, the key alone is added. If key exists
        its value is replaced, otherwise it is appended
        at the end of the section. Comment should be a list
        each item of which is a comment line preceding the key.
        """
        
# check requirements:
        
if isinstance(comment, list):
            
pass
        
else:
            
raise BadTypeError('list'comment)
        
# check configuration data is present
        
if len(self.conf) > 0:
            
pass
        
else:
            
raise NoListError()
        
# compose line
        
line key+'='+value
        
# find section and get index of following line
        
index self.findSection(section
        
# now we iterate the section to find the key
        
while True:
            try:
                
index += 1
                option 
self.conf[index]
                if 
option[0] == '[':
                    
# we reached next section
                    # must insert at end of section
                    
mode 'i'
                    
break
                
elif '=' in option:
                    
# we should have key=value pair
                    
pair option.split('=')
                    if 
pair[0] == key:
                        
# we found the matching key
                        # we replace its value by the new
                        
mode 'r'
                        
break
                    else:
                        
# key not matching
                        # keep looking
                        
continue
                else:
                    
# we don't need other lines:
                    # keep looking
                    
continue
            
except:
                
# reached end of configuration list
                # can append to end of list
                
mode 'a'
                
break
        
# now we know where and how we want to write
        
if len(comment) == 0:
            if 
mode == 'i':
                
# check if next section is preceded by icon tag
                
if self.conf[index-1][0:2] == '#[':
                    
index index-1
                
# insert line at current index
                
self.conf.insert(indexline)
            
elif mode == 'r':
                
# replace value at current index
                
self.conf[index] = line
            
else:
                
# mode == a
                
self.conf.append(line)
        
# if we want to add preceding comments
        
else:
            if 
mode == 'i':
                for 
item in comment:
                    
self.conf.insert(indexitem)
                    
index += 1
                self
.conf.insert(indexline)
            
elif mode == 'r':
                
# we write backwards
                # replace value at current index
                
self.conf[index] = line
                
# then we reverse te comment list:
                
comment.reverse()
                
# insert them at index (pushing the following forward)
                
for item in comment:
                    
self.conf.insert(indexitem)
            else:
                
# mode == a
                # first write comments
                
for item in comment:
                    
self.conf.append(item)
                
# then write key-value
                
self.conf.append(line)

    
def write(selfpath_to_file=''with_comments=True):
        
""" Writes the content of the configuration to a file.
        It writes the file with comments by default, if any.
        If no path is provided, it will use the path from read().
        """ 
        
if len(path_to_file) > 0:
            
self.path path_to_file
        elif len
(self.path) > 2:
            if 
len(self.conf) > 0:
                try:
                    
conffile open(self.path'w')
                    for 
line in self.conf:
                        if 
with_comments == True and line[0] == '#':
                            
conffile.write(line+'\n')
                        
elif with_comments == False and line [0] == '#':
                            
pass
                        elif not isinstance
(with_commentsbool):
                            print 
self.ArgError
                            conffile
.close()
                            print 
self.WriteError
                            
return None
                        
else:
                            
conffile.write(line+'\n'+'\n')
                    
conffile.close()
                
except:
                    print 
"HomeMadeConfigParser Error: an error occurred while handling"self.path
                    raise
            
else:
                
raise NoListError
        
else:
            
raise NoPathError



class NoSectionError(Exception):
    
def __init__(selfsection):
        
self.value "HomeMadeConfigParser found no section called "+section+"."
    
def __str__(self):
        return 
repr(self.value)

class 
NoKeyError(Exception):
    
def __init__(selfkey):
        
self.value "HomeMadeConfigParser found no key called "+key+"."
    
def __str__(self):
        return 
repr(self.key)
    
class 
NoListError(Exception):
    
def __init__(self):
        
self.value "HomeMadeConfigParser found no configuration data to parse. " \
        
"Run Parser.read() to fetch data."
    
def __str__(self):
        return 
repr(self.value)

class 
NoPathError(Exception):
    
def __init__(self):
        
self.value "HomeMadeConfigParser needs a valid path to file to write data to."
    
def __str__(self):
        return 
repr(self.value)    
    
class 
ArgError(Exception):
    
def __init__(selfargs):
        
self.value "HomeMadeConfigParser received bad argument(s) in method: "args
    def __str__
(self):
        return 
repr(self.value)
    
class 
BadTypeError(Exception):
    
def __init__(selfexpectedreceived):
        
self.value "HomeMadeConfigParser: The value type did not match the expected type. " \
        
" Expected type was '"+expected+"', but received '"+str(received)+"'."
    
def __str__(self):
        return 
repr(self.value)

        

matttbe, Sunday 15 May 2011 à 23:23


Subscription date : 24 January 2009
Messages : 12573
Thanks for sharing!

jesuisbenjamin, Monday 16 May 2011 à 22:45


Subscription date : 28 October 2009
Messages : 415
Ok, i ran across some new trouble:

for some reason CD keeps reloading the user conf file (/current_theme/plugins/...) from the conf file in the source (/third-party/...) each time CD starts up.
I thought CD should do so only if the source conf file's version was higher than the user conf file?

So now in my applet, mail account details are written to the user conf file (and i can see the changes happening in that file) but when i restart CD, the conf file is wiped clean and replaced with the source conf file. So mail accounts and user preferences are lost. I am writing to file through my own HomeMadeConfigParser script -- i don't know if that makes any difference.

Any idea what's happening?

B.

fabounet, Tuesday 17 May 2011 à 12:24


Subscription date : 30 November 2007
Messages : 17118
the dock shouldn't rewrite the conf file, maybe the versions mismatch (the version on the top of the file, and the version of the applet in the auto-load.conf.
what gives the debug output of cairo-dock ?

anyway, to prevent custom keys from disappearing if ever the conf file is updated, put a 0 after the widget key
(for instance:)
#s0 A string:
string 


but another possibility would be to store such info in another file, and let the user configure the accounts from a dialog window (or a simple gtk window).

matttbe, Sunday 29 March 2015 à 14:22


Subscription date : 24 January 2009
Messages : 12573
(spams have been removed)

Technical discussions | Discussions techniques

Subjects Author Language Messages Last message
[Locked] Password Encryption [Bug #193]
Page : 1 2 3
jesuisbenjamin English 58


Glx-Dock / Cairo-Dock List of forums Technical discussions | Discussions techniques Password Encryption Top

Online users :

Powered by ElementSpeak © 2007 Adrien Pilleboue, 2009-2013 Matthieu Baerts.
Dock based on CSS Dock Menu (Ndesign) with jQuery. Icons by zgegball
Cairo-Dock is a free software under GNU-GPL3 licence. First stable version created by Fabounet.
Many thanks to TuxFamily for the web Hosting and Mav for the domain name.