Пример #1
0
def factory(prefix, controller):
	"""This is the function that FSO's frameworkd will call to start this subsystem"""
	from logging import getLogger as get_logger
	log = get_logger('opimd')
	
	# Claim the bus name
	# TODO Check for exceptions
	SystemBus().request_name(DBUS_BUS_NAME_FSO)
	
	from backend_manager import BackendManager
	from domain_manager import DomainManager
	
	# Load plugins
	DomainManager.init(os.getcwdu())
	backend_manager = BackendManager(os.getcwdu())
	
	dbus_objects = []
	
	# Create a list of all d-bus objects to make frameworkd happy
	for dbus_obj in DomainManager.enumerate_dbus_objects():
		dbus_objects.append(dbus_obj)

	dbus_objects.append(backend_manager)
	
	log.info('opimd subsystem loaded')
	
	return dbus_objects
Пример #2
0
def factory(prefix, subsystem):
    #----------------------------------------------------------------------------#
    """
    frameworkd factory method.
    """
    # TODO Check for exceptions

    global INIT

    if INIT:
        return []

    try:
        phoneutils.init()
    except:
        logger.error('Failed to init libphone-utils!')

    DomainManager.init()
    type_manager = TypeManager()

    dbus_objects = []

    # Create a list of all d-bus objects
    for dbus_obj in DomainManager.enumerate_dbus_objects():
        logger.debug("adding object %s" % dbus_obj)
        dbus_objects.append(dbus_obj)

    dbus_objects.append(type_manager)

    INIT = True

    return dbus_objects
Пример #3
0
def main_pyneo():
	"""This is the function that will be used to launch pypimd for pyneo"""
	log_open('pypimd', LOG_NDELAY|LOG_PID|LOG_PERROR, LOG_DAEMON)
	
	DBusGMainLoop(set_as_default=True)
	
	# Claim the bus name
	# TODO Check for exceptions
	SystemBus().request_name(DBUS_BUS_NAME_PYNEO)
	
	# Workaround for relative imports of pyneod stuff, see
	# http://mail.python.org/pipermail/python-list/2007-May/438250.html
	sys.path.append('/usr/share/pyneod')
	
	from backend_manager import BackendManager
	from domain_manager import DomainManager

	# Load plugins
	DomainManager.init(os.getcwdu())
	BackendManager(os.getcwdu())
	
	# 3-2-1-Go!
	main_loop = MainLoop()
	main_loop.run()
	
	log_close()
	return 0
	def __init__(self):
		self._domain_handlers = {}
		self._entry_ids = []
		
		for domain in _DOMAINS:
		 self._domain_handlers[domain] = DomainManager.get_domain_handler(domain)
		self.load_entries_from_file()
	def __init__(self):
		self._domain_handlers = {}
		self._entry_ids = []
		
		for domain in _DOMAINS:
		 self._domain_handlers[domain] = DomainManager.get_domain_handler(domain)

		self.load_entries()
		self.install_signal_handlers()
Пример #6
0
	def register_backend(class_, backend):
		"""Register a backend and register it with all supported PIM domains
		
		@param backend The backend object to register"""
		class_._backends.append(backend)
		syslog(LOG_INFO, "Registered backend " + backend.name)
		
		for domain in backend.get_supported_domains():
			domain_handler = DomainManager.get_domain_handler(domain)
			if domain_handler: domain_handler.register_backend(backend)
Пример #7
0
    def build_sql_query(self, query_desc):
        """Modify a raw SQL query with some others rules."""

        query = query_desc['sql']
        params = []

        for name, value in query_desc.iteritems():
            #skip system fields
            if name.startswith('_'):
                #FIXME: put this in a central place!
                if name not in ('_limit', '_limit_start',
                                '_resolve_phonenumber',
                                '_retrieve_full_contact'):
                    raise InvalidField("Query rule '%s' does not exist." %
                                       (name, ))
                else:
                    continue
            elif name.startswith('@'):
                if name[1:] not in DomainManager.get_domains():
                    raise InvalidField("Domain '%s' does not exist." %
                                       (name[1:], ))
                else:
                    continue

        limit_start = 0
        if '_limit_start' in query_desc:
            try:
                limit_start = int(query_desc['_limit_start'])
            except:
                raise InvalidField("_limit_start should be an integer value")

        limit_end = -1
        if '_limit' in query_desc:
            try:
                limit_end = int(query_desc['_limit'])
            except:
                raise InvalidField("_limit should be an integer value")

        if (limit_start != 0 or limit_end != -1):
            query = "SELECT * FROM (" + query + ") LIMIT ?,?"
            params.extend([limit_start, limit_end])

        return {'Query': query, 'Parameters': params}
Пример #8
0
    def get_content(self, ids, join_parameters, other_fields=[]):
        cur = self.con.cursor()
        res = []
        query = self.build_retrieve_query(join_parameters)
        row_index = 0
        for id in ids:
            cur.execute(query, {'id': id})
            tmp = self.sanitize_result(cur.fetchall())

            #FIXME: Here we check for @Contacts, but we should handle crazier joins.
            if join_parameters.get('full') and tmp.has_key('@Contacts'):
                contact_domain = DomainManager.get_domain_handler('Contacts')
                if type(tmp.get('@Contacts')) != list:
                    #make it a list for easier handling
                    tmp['@Contacts'] = [
                        tmp['@Contacts'],
                    ]
                tmp['@Contacts'] = map(
                    lambda x: dbus.Dictionary(x, signature='sv'),
                    contact_domain.db_handler.get_content(
                        tmp['@Contacts'], {}))
                if len(tmp['@Contacts']) == 1:
                    tmp['@Contacts'] = tmp['@Contacts'][0]
                #get full contact content!
                pass
            tmp['Path'] = self.domain.id_to_path(id)
            tmp['EntryId'] = id
            # include any other custom field from query
            try:
                for field, value in other_fields[row_index].iteritems():
                    tmp[field] = value
            except IndexError:
                pass

            row_index += 1
            res.append(tmp)
        cur.close()
        return res
Пример #9
0
 def __init__(self, domain):
     self.domain = domain
     self.domainManager = DomainManager(domain)
     self.checkHealth()
Пример #10
0

#----------------------------------------------------------------------------#
# Test domain manager
#----------------------------------------------------------------------------#
from domain_manager import DomainManager

class DummyDomain(object):
	name = 'DummyDomain'
	def get_dbus_objects(self): yield self
	def register_backend(self, backend): pass

dd = DummyDomain()

# Try adding a dummy domain and make sure it gets listed
DomainManager.init('')
DomainManager.register_domain(dd)

if DomainManager.get_domain_handler('DummyDomain') == dd:
	print "Domain registration OK"
else:
	print "Domain registration FAILED"

# Make sure the D-Bus object listing works, too
obj_ok = False
for obj in DomainManager.enumerate_dbus_objects():
	if obj == dd: obj_ok = True

if obj_ok:
	print "D-Bus domain object listing OK"
else:
Пример #11
0
		
		# Make sure the requested contact exists
		if num_id >= len(self._contacts): raise InvalidContactIDError()
		
		return self._contacts[num_id].get_content()


	@dbus_method(_DIN_ENTRY, "s", "a{sv}", rel_path_keyword="rel_path")
	def GetMultipleFields(self, field_list, rel_path):
		num_id = int(rel_path[1:])
		
		# Make sure the requested contact exists
		if num_id >= len(self._contacts): raise InvalidContactIDError()
		
		# Break the string up into a list
		fields = field_list.split(',')
		new_field_list = []
			
		for field_name in fields:
			# Make sure the field list entries contain no spaces and aren't empty
			field_name = field_name.strip()
			if field_name: new_field_list.append(field_name)
			
		return self._contacts[num_id].get_fields(new_field_list)



###  Initalization  ###

DomainManager.register_domain(ContactDomain())
Пример #12
0
	@dbus_method(_DIN_ENTRY, "s", "", rel_path_keyword="rel_path")
	def MoveToFolder(self, new_folder_name, rel_path):
		"""Moves a message into a specific folder, if it exists
		
		@param new_folder_name Name of new folder
		@param rel_path Relative part of D-Bus object path, e.g. '/4'"""
		num_id = int(rel_path[1:])
		
		# Make sure the requested message exists
		if num_id >= len(self._messages): raise InvalidMessageIDError()
		
		message = self._messages[num_id]
		
		# Notify old folder of the move
		folder_name = message['Folder']
		folder_id = self.get_folder_id_from_name(folder_name)
		folder = self._folders[folder_id]
		folder.notify_message_move(num_id, new_folder_name)
		
		# Register message with new folder
		message['Folder'] = new_folder_name
		folder_id = self.get_folder_id_from_name(new_folder_name)
		folder = self._folders[folder_id]
		folder.register_message(num_id)



###  Initalization  ###

DomainManager.register_domain(MessageDomain())
Пример #13
0
    def build_search_query(self, query_desc):
        """Recieves a dictionary and makes an sql query that returns all the
        id's of those who meet the dictionaries restrictions"""
        params = []
        not_first = False

        if '_at_least_one' in query_desc:
            table_join_operator = " UNION "
        else:
            table_join_operator = " INTERSECT "
        query = ""
        for name, value in query_desc.iteritems():
            #skip system fields
            if name.startswith('_'):
                #FIXME: put this in a central place!
                if name not in ('_at_least_one', '_sortdesc', '_sortby',
                                '_limit', '_limit_start',
                                '_resolve_phonenumber',
                                '_retrieve_full_contact'):
                    raise InvalidField("Query rule '%s' does not exist." %
                                       (name, ))
                else:
                    continue
            elif name.startswith('@'):
                if name[1:] not in DomainManager.get_domains():
                    raise InvalidField("Domain '%s' does not exist." %
                                       (name[1:], ))
                else:
                    continue

            if not_first:
                query = query + table_join_operator

            not_first = True

            #handle type searching
            if name.startswith('<') or name.startswith('>'):
                pos = 1
                if (name[1] == '='):
                    pos = 2
                operator = name[:pos]
                name = name[pos:]
            elif name.startswith('!'):
                operator = '!='
                name = name[1:]
            else:
                operator = '='

            if name.startswith('$'):
                field_type = name[1:]
                table = self.get_table_name_from_type(field_type)
                if not table:
                    raise InvalidField("Type '%s' does not exist." %
                                       (field_type, ))
                query = query + "SELECT DISTINCT " + self.db_prefix + "_id FROM " + \
                        table + " WHERE ("
            else:
                field_type = self.domain.field_type_from_name(name)
                table = self.get_table_name(name)
                if not table:
                    raise InvalidField(
                        "Field '%s' is reserved for internal use." % (name, ))
                query = query + "SELECT DISTINCT " + self.db_prefix + "_id FROM " + \
                        table + " WHERE field_name = ? AND ("
                params.append(str(name))
            #If multi values, make OR connections
            comp_string = self.get_value_compare_string(
                field_type, name, operator)

            if type(value) == Array or type(value) == list:
                first_val = True

                for val in value:
                    if first_val:
                        first_val = False
                    else:
                        query = query + " OR "

                    query = query + comp_string
                    params.append(
                        self.get_value_compare_object(field_type, name, val))
            else:
                query = query + comp_string
                params.append(
                    self.get_value_compare_object(field_type, name, value))

            query = query + ")"

        #If there are no restrictions get everything
        if query == "":
            query = "SELECT " + self.db_prefix + "_id FROM " + self.db_prefix
        if '_sortby' in query_desc:
            sortby = query_desc['_sortby']
            query = "SELECT DISTINCT " + self.db_prefix + "_id FROM (" + query + \
                        ") JOIN " + self.get_table_name(sortby) + " USING (" + \
                        self.db_prefix + "_id) WHERE field_name = ? ORDER BY value"
            params.append(sortby)
            if '_sortdesc' in query_desc:
                query = query + " DESC"

        limit_start = 0
        if '_limit_start' in query_desc:
            try:
                limit_start = int(query_desc['_limit_start'])
            except:
                raise InvalidField("_limit_start should be an integer value")

        limit_end = -1
        if '_limit' in query_desc:
            try:
                limit_end = int(query_desc['_limit'])
            except:
                raise InvalidField("_limit should be an integer value")

        if (limit_start != 0 or limit_end != -1):
            query = query + " LIMIT ?,?"
            params.extend([limit_start, limit_end])

        return {'Query': query, 'Parameters': params}