view src/gaim-remote.py @ 12360:3153661f4d5c

[gaim-migrate @ 14664] Faceprint is concerned about 2 things: 1)some of the random colors are very close together. as best we can tell, there are two ways to fix this 1a) for each proposed color, iterate the entire list of selected colors, looking to ensure that it is not too close to any of them. this is an O(n^2) operation, with n >= 220 (the current number of colors we look for) 1b) iterate the entire set of possible colors, skipping ahead by some guess (rather than iterating by 1). this is an O(n^3) operation, where n is 65535/(whatever we skip ahead by). This is not only a more expensive operation, but because of the nature of the color list, it is not _necessarily_ going to yield more predictable results, skipping ahead 5 (or any other number) does not necessarily guarantee that you've skipped 5 very similar colors. 2) as you can see, either solution to #1 is potentially a resource hog. #1a is a random delay, #1b is inherently expensive. How often #1a will exceed the bound #1b, if ever, is unknown. rather than doing either of these, we settled on a middle course: a .h file has been created containing a set of colors. currently the set we were previously hard coded to. Gaim will search that list for usable colors and start randomly looking only if that list does not contain sufficient usable colors. ideally this list would be generated to have colors that are known to be a "safe" distance appart, that is colors that you can tell appart. and Ideally it would have a (small) multiple of the number of colors we are searching for. This should ensure that IF we go to randomly searching, we need do so only for a few colors. Right now I have no good way to generate a "safe" list of colors though. committer: Tailor Script <tailor@pidgin.im>
author Luke Schierer <lschiere@pidgin.im>
date Mon, 05 Dec 2005 21:46:47 +0000
parents 64fadbf3810f
children 2e4e02b72e43
line wrap: on
line source

#!/usr/bin/python

import dbus
import re
import urllib
import sys

import xml.dom.minidom 

xml.dom.minidom.Element.all   = xml.dom.minidom.Element.getElementsByTagName

obj = dbus.SessionBus().get_object("org.gaim.GaimService", "/org/gaim/GaimObject")
gaim = dbus.Interface(obj, "org.gaim.GaimInterface")

class CheckedObject:
    def __init__(self, obj):
        self.obj = obj

    def __getattr__(self, attr):
        return CheckedAttribute(self, attr)

class CheckedAttribute:
    def __init__(self, cobj, attr):
        self.cobj = cobj
        self.attr = attr
        
    def __call__(self, *args):
        result = self.cobj.obj.__getattr__(self.attr)(*args)
        if result == 0:
            raise "Error: " + self.attr + " " + str(args) + " returned " + str(result)
        return result
            
cgaim = CheckedObject(gaim)

urlregexp = r"^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?"

def extendlist(list, length, fill):
    if len(list) < length:
        return list + [fill] * (length - len(list))
    else:
        return list

def convert(value):
    try:
        return int(value)
    except:
        return value

def findaccount(accountname, protocolname):
    try:
        # prefer connected accounts
        account = cgaim.GaimAccountsFindConnected(accountname, protocolname)
        return account
    except:
        # try to get any account and connect it
        account = cgaim.GaimAccountsFindAny(accountname, protocolname)
        print gaim.GaimAccountGetUsername(account)
        gaim.GaimAccountSetStatusVargs(account, "online", 1)
        gaim.GaimAccountConnect(account)
        return account
    

def execute(uri):
    match = re.match(urlregexp, uri)
    protocol = match.group(2)
    if protocol is not None:
        protocol = "prpl-" + protocol
    command = match.group(5)
    paramstring = match.group(7) 
    params = {}
    if paramstring is not None:
        for param in paramstring.split("&"):
            key, value = extendlist(param.split("=",1), 2, "")
            params[key] = urllib.unquote(value)

    accountname = params.get("account", "")

    if command == "goim":
        print params
        account = findaccount(accountname, protocol)
        conversation = cgaim.GaimConversationNew(1, account, params["screenname"])
        if "message" in params:
            im = cgaim.GaimConversationGetImData(conversation)
            gaim.GaimConvImSend(im, params["message"])
        return None

    elif command == "gochat":
        account = findaccount(accountname, protocol)
        connection = cgaim.GaimAccountGetConnection(account)
        return gaim.ServJoinChat(connection, params)

    elif command == "addbuddy":
        account = findaccount(accountname, protocol)
        return cgaim.GaimBlistRequestAddBuddy(account, params["screenname"],
                                              params.get("group", ""), "")

    elif command == "setstatus":
        if "account" in params:
            accounts = [cgaim.GaimAccountsFindAny(accountname, protocol)]
        else:
            accounts = gaim.GaimAccountsGetAllActive()

        for account in accounts:
            status = cgaim.GaimAccountGetStatus(account, params["status"])
            for key, value in params.items():
                if key not in ["status", "account"]:
                    gaim.GaimStatusSetAttrString(status, key, value)
            gaim.GaimAccountSetStatusVargs(account, params["status"], 1)
        return None

    elif command == "getinfo":
        account = findaccount(accountname, protocol)
        connection = cgaim.GaimAccountGetConnection(account)
        return gaim.ServGetInfo(connection, params["screenname"])

    elif command == "quit":
        return gaim.GaimCoreQuit()

    elif command == "uri":
        return None

    else:
        match = re.match(r"(\w+)\s*\(([^)]*)\)", command)
        if match is not None:
            name = match.group(1)
            argstr = match.group(2)
            if argstr == "":
                args = []
            else:
                args = argstr.split(",")
            fargs = []
            for arg in args:
                fargs.append(convert(arg.strip()))
            return gaim.__getattr__(name)(*fargs)
        else:
            # introspect the object to get parameter names and types
            # this is slow because the entire introspection info must be downloaded
            data = dbus.Interface(obj, "org.freedesktop.DBus.Introspectable").\
                   Introspect()
            introspect = xml.dom.minidom.parseString(data).documentElement
            for method in introspect.all("method"):
                if command == method.getAttribute("name"):
                    methodparams = []
                    for arg in method.all("arg"):
                        if arg.getAttribute("direction") == "in":
                            value = params[arg.getAttribute("name")]
                            type = arg.getAttribute("type")
                            if type == "s":
                                methodparams.append(value)
                            elif type == "i":
                                methodparams.append(int(value))
                            else:
                                raise "Don't know how to handle type \"%s\"" % type
                    return gaim.__getattr__(command)(*methodparams)
            raise "Unknown command: %s" % command


if len(sys.argv) == 1:
    print """This program uses DBus to communicate with gaim.

Usage:

    %s "command1" "command2" ...

Each command is of one of the three types:

    [protocol:]commandname?param1=value1&param2=value2&...
    FunctionName?param1=value1&param2=value2&...
    FunctionName(value1,value2,...)

The second and third form are provided for completeness but their use
is not recommended; use gaim-send or gaim-send-async instead.  The
second form uses introspection to find out the parameter names and
their types, therefore it is rather slow.

Examples of commands:

    jabber:goim?screenname=testone@localhost&message=hi
    jabber:gochat?room=TestRoom&server=conference.localhost
    jabber:getinfo?screenname=testone@localhost
    jabber:addbuddy?screenname=my friend

    setstatus?status=away&message=don't disturb
    quit

    GaimAccountsFindConnected?name=&protocol=prpl-jabber
    GaimAccountFindConnected(,prpl-jabber)
""" % sys.argv[0]

for arg in sys.argv[1:]:
    print execute(arg)