Subversion Repositories basico

Rev

Rev 42 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
4 t00mlabs 1
#!/usr/bin/python3
2
# -*- coding: utf-8 -*-
3
# File: basico.py
4
# Author: Tomás Vírseda
5
# License: GPL v3
6
# Description: Main entry point por Basico app
7
import os
73 t00mlabs 8
# -*- coding: utf-8 -*-
4 t00mlabs 9
import sys
73 t00mlabs 10
import codecs
11
sys.stdout = codecs.getwriter("iso-8859-1")(sys.stdout, 'xmlcharrefreplace')
4 t00mlabs 12
import traceback as tb
13
import imp
14
import signal
41 t00mlabs 15
from pprint import pprint
4 t00mlabs 16
from os.path import abspath, sep as SEP
17
from configparser import SafeConfigParser, ExtendedInterpolation
31 t00mlabs 18
# import urllib.request
4 t00mlabs 19
 
32 t00mlabs 20
import selenium
21
 
20 t00mlabs 22
import gi
23
gi.require_version('Gtk', '3.0')
24
from gi.repository import Gtk
4 t00mlabs 25
 
20 t00mlabs 26
from .utils import Utils
4 t00mlabs 27
from .log import get_logger
28
from .gui import GUI
29
from .iconmanager import IconManager
30
from .sap import SAP
31
from .settings import Settings
32
from .uifuncs import UIFuncs
33
from .menus import Menus
34
from .projects import Projects
35
from .tasks import Tasks
36
from .plugins import Plugins
37
from .callbacks import Callback
38
from .notify import Notification
73 t00mlabs 39
#from .stats import Stats
34 t00mlabs 40
from .database import Database
35 t00mlabs 41
from .driver import SeleniumDriver
4 t00mlabs 42
from .env import ROOT, APP, LPATH, GPATH, FILE
43
 
44
 
45
class Basico:
46
    def __init__(self):
47
        """Main class: the entry point for Basico.
48
        It stands for Controller.
49
        """
28 t00mlabs 50
 
51
        # Create local paths if they do not exist
29 t00mlabs 52
        for entry in LPATH:
53
            if not os.path.exists(LPATH[entry]):
54
                os.makedirs(LPATH[entry])
55
 
32 t00mlabs 56
 
4 t00mlabs 57
        self.log = get_logger(self.__class__.__name__, FILE['LOG'])
32 t00mlabs 58
        #~ self.log.info("Starting Basico")
28 t00mlabs 59
 
4 t00mlabs 60
        self.services = {}
61
        try:
62
            services = {
63
                'GUI'       :   GUI(),
20 t00mlabs 64
                'Utils'     :   Utils(),
4 t00mlabs 65
                'UIF'       :   UIFuncs(),
66
                'Menus'     :   Menus(),
67
                'SAP'       :   SAP(),
68
                'Settings'  :   Settings(),
69
                'Notify'    :   Notification(),
70
                'Tasks'     :   Tasks(),
71
                'IM'        :   IconManager(),
72
                'Plugins'   :   Plugins(),
73
                'Callbacks' :   Callback(),
73 t00mlabs 74
                #'Stats'     :   Stats(),
35 t00mlabs 75
                'DB'        :   Database(),
76
                'Driver'    :   SeleniumDriver()
4 t00mlabs 77
            }
78
            self.register_services(services)
79
        except Exception as error:
80
            self.log.error(error)
81
            raise
82
 
83
 
21 t00mlabs 84
    def setup(self):
23 t00mlabs 85
        """
86
        Setup Basico Envrionment
87
        Info about ConfigParser options:
35 t00mlabs 88
        https://docs.python.org/3/library/configparser.html#interpolation-of-values
89
        https://docs.python.org/3/library/configparser.html#configparser.ConfigParser.optionxform
23 t00mlabs 90
        """
22 t00mlabs 91
        self.log.debug("Setting up Basico environment")
92
        self.log.debug("Global path: %s" % GPATH['ROOT'])
93
        self.log.debug("Local path: %s" % LPATH['ROOT'])
94
 
95
        # Set up config
96
        CONFIG_FILE = self.get_file('CNF')
97
        self.config = SafeConfigParser(interpolation=ExtendedInterpolation())
98
        self.config.optionxform = str
99
 
100
        # Save config
101
        if not os.path.exists(CONFIG_FILE):
102
            self.log.debug('Configuration file not found. Creating a new one')
103
            with open(CONFIG_FILE, 'w') as configfile:
104
                self.config.write(configfile)
105
            self.log.info('Config file initialited')
106
 
23 t00mlabs 107
 
4 t00mlabs 108
    def get_config(self):
109
        CONFIG_FILE = self.get_file('CNF')
110
        self.config.read(CONFIG_FILE)
111
 
112
        return self.config
113
 
114
 
115
    def get_file(self, name):
116
        try:
117
            return FILE[name]
118
        except:
119
            self.log.error(self.get_traceback())
120
 
121
 
122
    def get_app_info(self, var):
123
        try:
124
            return APP[var]
125
        except:
126
            return None
127
 
128
 
129
    def get_var(self, name, scope='global'):
130
        if scope == 'global':
131
            return GPATH[name]
132
        else:
133
            return LPATH[name]
134
 
135
 
136
    def list_services(self):
137
        """Return a dictionary of services"""
138
        return self.services
139
 
140
 
141
    def get_service(self, name):
142
        """Get/Start a registered service
143
        @type name: name of the service
144
        @param name: given a service name it returns the associated
145
        class. If service was not running it is started.
146
        """
147
        try:
148
            service = self.services[name]
149
            if service.is_started():
150
                return service
151
            else:
152
                service.start(self, name)
153
                return service
154
        except KeyError as service:
155
            self.log.error("Service %s not registered or not found" % service)
156
            raise
157
 
20 t00mlabs 158
 
4 t00mlabs 159
    def register_services(self, services):
160
        """Register a list of services
161
        @type services: dict
162
        @param services: a dictionary of name:class for each service
163
        """
164
        for name in services:
165
            self.register_service(name, services[name])
166
 
167
 
168
    def register_service(self, name, service):
169
        """Register a new service
170
        @type name: string
171
        @param name: name of the service
172
        @type service: class
173
        @param service: class which contains the code
174
        """
175
        try:
176
            self.services[name] = service
177
        except Exception as error:
178
            self.log.error(error)
179
 
180
 
181
    def deregister_service(self, name):
182
        """Deregister a running service
183
        @type name: string
184
        @param name: name of the service
185
        """
186
        self.services[name].end()
187
        self.services[name] = None
35 t00mlabs 188
        self.log.debug("Service %s stopped" % name)
4 t00mlabs 189
 
190
 
191
    def check(self):
20 t00mlabs 192
        '''
23 t00mlabs 193
        Check Basico environment
20 t00mlabs 194
        '''
23 t00mlabs 195
        utils = self.get_service("Utils")
196
        uif = self.get_service('UIF')
35 t00mlabs 197
        driver = self.get_service('Driver')
4 t00mlabs 198
 
32 t00mlabs 199
        # Show Selenium version
200
        self.log.debug("Selenium version: %s" % selenium.__version__)
201
 
202
        # Check proper GTK version
23 t00mlabs 203
        GTK_VERSION = uif.check_gtk_version()
4 t00mlabs 204
 
32 t00mlabs 205
        # Check Gecko webdrver
35 t00mlabs 206
        GECKO_DRIVER = driver.check()
23 t00mlabs 207
 
35 t00mlabs 208
        run = GTK_VERSION and GECKO_DRIVER
23 t00mlabs 209
 
210
        if run:
211
            self.log.info("Basico environment ready!")
212
            return True
20 t00mlabs 213
        else:
23 t00mlabs 214
            self.log.error("Error(s) found checking Basico environment")
215
            return False
20 t00mlabs 216
 
217
 
218
 
219
 
4 t00mlabs 220
    def stop(self):
221
        """For each service registered, it executes the 'end' method
222
        (if any) to finalize them properly.
223
        """
224
 
225
        # Deregister all services loaded
226
        self.deregister_service('GUI')
227
        for name in self.services:
228
            try:
35 t00mlabs 229
                if name != 'GUI':
230
                    self.deregister_service(name)
231
            except Exception as error:
73 t00mlabs 232
                self.log.error(self.get_traceback())
233
                raise
35 t00mlabs 234
 
4 t00mlabs 235
        self.log.info("Basico finished")
236
 
237
 
238
    def get_traceback(self):
239
        return tb.format_exc()
240
 
241
 
242
    def run(self):
243
        try:
244
            self.gui = self.get_service('GUI')
245
            self.gui.run()
246
        except:
247
            self.log.error(self.get_traceback())
248
 
249
 
250
def main():
251
    #DOC: http://stackoverflow.com/questions/16410852/keyboard-interrupt-with-with-python-gtk
252
    signal.signal(signal.SIGINT, signal.SIG_DFL)
253
    basico = Basico()
21 t00mlabs 254
    basico.setup()
23 t00mlabs 255
    ok = basico.check()
256
    if ok:
4 t00mlabs 257
        basico.run()
258
    sys.exit(0)