File: base.py

package info (click to toggle)
groundcontrol 1.6.6-1
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 2,296 kB
  • ctags: 670
  • sloc: python: 3,486; sh: 26; makefile: 11
file content (180 lines) | stat: -rw-r--r-- 6,111 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
#
# Copyright 2009 Martin Owens
#
# 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 3 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, see <http://www.gnu.org/licenses/>
#
"""
Provides some basic methods and classes (which should be replaced)
"""

import os
import dbus
import yaml
import logging
import threading

from fnmatch import fnmatch
from lazr.uri import URI
from launchpadlib.launchpad import EDGE_SERVICE_ROOT, STAGING_SERVICE_ROOT
from GroundControl.xdgapp import XdgApplication
from GroundControl import __stage__, __appname__

def clean_api_url(service_root):
    """Create a reformed API URL"""
    web_root_uri = URI(service_root)
    web_root_uri.path = ""
    web_root_uri.host = web_root_uri.host.replace("api.", "", 1)
    return str(web_root_uri.ensureSlash())


PROJECT_NAME  = "Launchpad Ground Control"
PROJECT_PKG   = __appname__
PROJECT_XDG   = XdgApplication(PROJECT_PKG)
LAUNCHPAD_XDG = XdgApplication('launchpad')
LAUNCHPAD_OBJ = None
CONFIG_NAME   = 'settings.yaml'
GC_CONFIG     = yaml.load(PROJECT_XDG.get_config(CONFIG_NAME))
if not GC_CONFIG:
    GC_CONFIG = {}

# This sets up a user's default project directory
HOME_DIR = os.path.expanduser('~/')
DEFAULT_DIR   = GC_CONFIG.get('directory',
    os.path.join(HOME_DIR, _('Projects')))


# Allow user to specify a custom launchpad service
LP_SERVE_ROOT = GC_CONFIG.get('service', 'EDGE').lower()
if LP_SERVE_ROOT == 'edge':
    LP_SERVE_ROOT = EDGE_SERVICE_ROOT
elif LP_SERVE_ROOT == 'staging':
    LP_SERVE_ROOT = STAGING_SERVICE_ROOT
LP_WEB_ROOT   = clean_api_url(LP_SERVE_ROOT)

def set_logging(mode, logfile=None):
    """Set the logging for this session"""
    root = logging.getLogger()
    while len(root.handlers):
        root.removeHandler(root.handlers[0])

    # We will log as debug also if the log file exists.
    if os.path.exists(logfile) or mode == 'file':
        logging.basicConfig(level=logging.DEBUG,
            format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
            datefmt='%m-%d %H:%M',
            filename=logfile,
            filemode='w')
    else:
        if __stage__ == 'DEV' or mode == 'stdout':
            logging.basicConfig(level=logging.DEBUG,
                format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                datefmt='%m-%d %H:%M')
        else:
            logging.basicConfig(level=logging.ERROR)


set_logging(GC_CONFIG.get('logging', 'NONE').lower(),
    logfile=os.path.expanduser("~/groundcontrol.log"))

logging.debug("Using Sites: %s / %s" % (LP_SERVE_ROOT, LP_WEB_ROOT))


def listfiles(*dirs):
    """List files in a directory given a filtership"""
    fdir, pattern = os.path.split(os.path.join(*dirs))
    return [os.path.join(fdir, filename)
        for filename in os.listdir(os.path.abspath(fdir))
            if filename[0] != '.' and fnmatch(filename, pattern)]

class Thread(threading.Thread):
    """Special thread object for catching errors and logging them"""
    def run(self, *args, **kwargs):
        """The code to run when the thread us being run"""
        try:
            super(Thread, self).run(*args, **kwargs)
        except Exception, message:
            logging.exception(message)

class Events(object):
    """Simple event base class, may be able to replace with gobject"""
    signals = None

    def call_signal(self, name, *opts, **args):
        """All the named events"""
        if self.signals and self.signals.has_key(name):
            for signal in self.signals[name].values():
                method = signal[0]
                opts += signal[1]
                args.update(signal[2])
                method(*opts, **args)

    def connect_signal(self, name, method, *opts, **args):
        """Connect a method to a named event"""
        if not self.signals:
            self.signals = {}
        if not self.signals.has_key(name):
            self.signals[name] = {}
        # This will add any calls from different objects
        # but replace calls of the same method and same object.
        self.signals[name][id(method)] = [method, opts, args]

    def disconnect_signal(self, name, method):
        """Disconnect a method from a named event"""
        if self.signals.has_key(name):
            if self.signals[name].has_key(id(method)):
                del(self.signals[name][id(method)])
            if not self.signals[name]:
                del(self.signals[name])


NM_STATE_UNKNOWN = 0
NM_STATE_ASLEEP = 1
NM_STATE_CONNECTING = 2
NM_STATE_CONNECTED = 3
NM_STATE_DISCONNECTED = 4
NM_LOCATION = '/org/freedesktop/NetworkManager'
NM_OBJNAME = 'org.freedesktop.NetworkManager'
DBUS_LOCATION = '/org/freedesktop/DBus'
DBUS_OBJNAME = 'org.freedesktop.DBus'

from dbus.mainloop.glib import DBusGMainLoop

DBusGMainLoop(set_as_default=True)

bus = dbus.SystemBus()
dbus_objects = dbus.Interface(bus.get_object(DBUS_OBJNAME, DBUS_LOCATION), 
                              DBUS_OBJNAME).ListNames()

running_NM = True if NM_OBJNAME in dbus_objects else False

if running_NM:
    nm = bus.get_object(NM_OBJNAME, NM_LOCATION)

def is_online():
    """Return true if we're online"""
    if not running_NM:
        return True  #if NM is not running assume always connected
    else:
        return nm.state() == NM_STATE_CONNECTED

def set_online_changed(method):
    """Tie a method to a network manager status change"""
    if running_NM :
	bus.add_signal_receiver(method, 'StateChanged',
        NM_OBJNAME, NM_OBJNAME, NM_LOCATION)

def save_config(name=CONFIG_NAME, yaml=GC_CONFIG):
    """Save the ground control config"""
    PROJECT_XDG.set_config(name, yaml.dump(GC_CONFIG))