~ubuntu-branches/ubuntu/utopic/telepathy-python/utopic

« back to all changes in this revision

Viewing changes to src/client/managerregistry.py

  • Committer: Bazaar Package Importer
  • Author(s): Simon McVittie
  • Date: 2008-02-21 10:42:31 UTC
  • mfrom: (1.2.1 upstream) (7.1.10 hardy)
  • Revision ID: james.westby@ubuntu.com-20080221104231-88bloeih42cmsb0x
* New upstream version 0.15.0
* Don't mention Cohoba and telepathy-msn in description (-msn is now
  -butterfly, and Cohoba is obsolete)
* Standards-Version: 3.7.3 (no changes)
* Add XS-Dm-Upload-Allowed: yes so I can upload it in future

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# telepathy-python - Base classes defining the interfaces of the Telepathy framework
 
2
#
 
3
# Copyright (C) 2005 Collabora Limited
 
4
# Copyright (C) 2005 Nokia Corporation
 
5
#
 
6
# This library is free software; you can redistribute it and/or
 
7
# modify it under the terms of the GNU Lesser General Public
 
8
# License as published by the Free Software Foundation; either
 
9
# version 2.1 of the License, or (at your option) any later version.
 
10
#
 
11
# This library is distributed in the hope that it will be useful,
 
12
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 
14
# Lesser General Public License for more details.
 
15
#
 
16
# You should have received a copy of the GNU Lesser General Public
 
17
# License along with this library; if not, write to the Free Software
 
18
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 
19
 
 
20
"""
 
21
Loads .manager files according to
 
22
http://telepathy.freedesktop.org/wiki/FileFormats.
 
23
"""
 
24
 
 
25
import ConfigParser, os
 
26
import dircache
 
27
import dbus
 
28
import telepathy
 
29
 
 
30
 
 
31
_dbus_py_version = getattr(dbus, 'version', (0,0,0))
 
32
 
 
33
def _convert_pathlist(pathlist):
 
34
    dirlist = pathlist.split(":")
 
35
    # Reverse so least-important is first
 
36
    dirlist.reverse()
 
37
    dirs = []
 
38
    for path in dirlist:
 
39
        if len(path):
 
40
            path = os.path.abspath(os.path.expanduser(path))
 
41
            dirs.append(os.path.join(path, "telepathy", "managers"))
 
42
    return dirs
 
43
 
 
44
class ManagerRegistry:
 
45
    def __init__(self):
 
46
        self.services = {}
 
47
 
 
48
    def LoadManager(self, path):
 
49
        config = ConfigParser.RawConfigParser()
 
50
        config.read(path)
 
51
 
 
52
        cm_name = os.path.basename(path)[:-len(".manager")]
 
53
        self.services[cm_name] = {
 
54
            "name": cm_name,
 
55
            "busname": "org.freedesktop.Telepathy.ConnectionManager.%s" % cm_name,
 
56
            "objectpath": "/org/freedesktop/Telepathy/ConnectionManager/%s" % cm_name,
 
57
        }
 
58
        protocols = {}
 
59
 
 
60
        for section in set(config.sections()):
 
61
            if section.startswith('Protocol '):
 
62
                proto_name = section[len('Protocol '):]
 
63
                protocols[proto_name] = dict(config.items(section))
 
64
 
 
65
        if not protocols:
 
66
            raise ConfigParser.NoSectionError("no protocols found (%s)" % path)
 
67
 
 
68
        self.services[cm_name]["protos"] = protocols
 
69
 
 
70
    def LoadManagers(self):
 
71
        """
 
72
        Searches local and system wide configurations
 
73
 
 
74
        Can raise all ConfigParser errors. Generally filename member will be
 
75
        set to the name of the erronous file.
 
76
        """
 
77
 
 
78
        # Later items in the list are _more_ important
 
79
        all_paths = []
 
80
        if os.environ.has_key("XDG_DATA_DIRS"):
 
81
            all_paths += _convert_pathlist(os.environ["XDG_DATA_DIRS"])
 
82
        else:
 
83
            all_paths.append('/usr/share/telepathy/managers')
 
84
            all_paths.append('/usr/local/share/telepathy/managers')
 
85
 
 
86
        home = os.path.expanduser("~")
 
87
        if os.environ.has_key("XDG_DATA_HOME"):
 
88
            all_paths += _convert_pathlist(os.environ["XDG_DATA_HOME"])
 
89
        else:
 
90
            all_paths.append(os.path.join(home, ".local", "share", \
 
91
                "telepathy", "managers"))
 
92
 
 
93
        all_paths.append(os.path.join(home, ".telepathy", "managers"))
 
94
 
 
95
        for path in all_paths:
 
96
            if os.path.exists(path):
 
97
                for name in dircache.listdir(path):
 
98
                    if name.endswith('.manager'):
 
99
                        self.LoadManager(os.path.join(path, name))
 
100
 
 
101
    def GetProtos(self):
 
102
        """
 
103
        returns a list of protocols supported on this system
 
104
        """
 
105
        protos=set()
 
106
        for service in self.services.keys():
 
107
            if self.services[service].has_key("protos"):
 
108
                protos.update(self.services[service]["protos"].keys())
 
109
        return list(protos)
 
110
 
 
111
    def GetManagers(self, proto):
 
112
        """
 
113
        Returns names of managers that can handle the given protocol.
 
114
        """
 
115
        managers = []
 
116
        for service in self.services.keys():
 
117
            if "protos" in self.services[service]:
 
118
                if self.services[service]["protos"].has_key(proto):
 
119
                    managers.append(service)
 
120
        return managers
 
121
 
 
122
    def GetBusName(self, manager):
 
123
        assert(manager in self.services)
 
124
        assert('busname' in self.services[manager])
 
125
        return self.services[manager]['busname']
 
126
 
 
127
    def GetObjectPath(self, manager):
 
128
        assert(manager in self.services)
 
129
        assert('objectpath' in self.services[manager])
 
130
        return self.services[manager]['objectpath']
 
131
 
 
132
    def GetManager(self, manager):
 
133
        return telepathy.client.ConnectionManager(
 
134
            self.services[manager]['busname'],
 
135
            self.services[manager]['objectpath'])
 
136
 
 
137
    def GetParams(self, manager, proto):
 
138
        """
 
139
        Returns a dict of paramters for the given proto on the given manager.
 
140
        The keys will be the parameters names, and the values a tuple of (dbus
 
141
        type, default value, flags). If no default value is specified, the
 
142
        second item in the tuple will be None.
 
143
        """
 
144
 
 
145
        params = {}
 
146
        config = self.services[manager]["protos"][proto]
 
147
 
 
148
        for key, val in config.iteritems():
 
149
            if not key.startswith('param-'):
 
150
                continue
 
151
 
 
152
            name = key[len('param-'):]
 
153
            values = val.split()
 
154
            type = values[0]
 
155
            flags = 0
 
156
            default = None
 
157
 
 
158
            if "register" in values:
 
159
                flags |= telepathy.CONN_MGR_PARAM_FLAG_REGISTER
 
160
 
 
161
            if "required" in values:
 
162
                flags |= telepathy.CONN_MGR_PARAM_FLAG_REQUIRED
 
163
 
 
164
            for key, val in config.iteritems():
 
165
                if key.strip().startswith("default-"+name):
 
166
                    if _dbus_py_version < (0, 80):
 
167
                        default = dbus.Variant(val.strip(), signature=type)
 
168
                    else:
 
169
                        default = val.strip()
 
170
                        if type in 'uiqntxy':
 
171
                            default = int(default)
 
172
                        elif type == 'b':
 
173
                            if default.lower() in ('0', 'false'):
 
174
                                default = False
 
175
                            else:
 
176
                                default = True
 
177
                        elif type == 'd':
 
178
                            default = float(default)
 
179
                        # we don't support non-basic types
 
180
                    flags |= telepathy.CONN_MGR_PARAM_FLAG_HAS_DEFAULT
 
181
 
 
182
            params[name] = (type, default, flags)
 
183
 
 
184
        return params