source: skype/skyped.py @ 7613670

Last change on this file since 7613670 was 7613670, checked in by VMiklos <vmiklos@…>, at 2007-09-03T22:22:55Z

handle the case when the input is a multiline message

  • Property mode set to 100644
File size: 5.4 KB
Line 
1#!/usr/bin/env python
2#
3#   skyped.py
4
5#   Copyright (c) 2007 by Miklos Vajna <vmiklos@frugalware.org>
6#
7#   It uses several code from a very basic python CLI interface, available at:
8#
9#   http://forum.skype.com/index.php?showtopic=42640
10
11#   This program is free software; you can redistribute it and/or modify
12#   it under the terms of the GNU General Public License as published by
13#   the Free Software Foundation; either version 2 of the License, or
14#   (at your option) any later version.
15#
16#   This program is distributed in the hope that it will be useful,
17#   but WITHOUT ANY WARRANTY; without even the implied warranty of
18#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19#   GNU General Public License for more details.
20
21#   You should have received a copy of the GNU General Public License
22#   along with this program; if not, write to the Free Software
23#   Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
24#   USA.
25#
26
27import sys
28import os
29import signal
30import locale
31import time
32import dbus
33import dbus.service
34import dbus.mainloop.glib
35import gobject
36import socket
37import getopt
38
39__version__ = "0.1.1"
40
41SKYPE_SERVICE = 'com.Skype.API'
42CLIENT_NAME = 'SkypeApiPythonShell'
43
44# well, this is a bit hackish. we store the socket of the last connected client
45# here and notify it. maybe later notify all connected clients?
46conn = None
47
48def sig_handler(signum, frame):
49        mainloop.quit()
50
51def input_handler(fd, io_condition):
52        input = fd.recv(1024)
53        for i in input.split("\n"):
54                if i:
55                        for j in skype.send(i.strip()):
56                                fd.send((j + "\n").encode(locale.getdefaultlocale()[1]))
57        return True
58
59def server(host, port):
60        sock = socket.socket()
61        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
62        sock.bind((host, port))
63        sock.listen(1)
64        gobject.io_add_watch(sock, gobject.IO_IN, listener)
65
66def listener(sock, *args):
67        global conn
68        conn, addr = sock.accept()
69        fileno = conn.fileno()
70        gobject.io_add_watch(conn, gobject.IO_IN, input_handler)
71        return True
72
73def dprint(msg):
74        global options
75
76        if options.debug:
77                print msg
78
79class SkypeApi(dbus.service.Object):
80        def __init__(self):
81                bus = dbus.SessionBus()
82                try:
83                        self.skype_api = bus.get_object(SKYPE_SERVICE, '/com/Skype')
84                except dbus.exceptions.DBusException:
85                        sys.exit("Can't find any Skype instance. Are you sure you have started Skype?")
86
87                reply = self.send('NAME ' + CLIENT_NAME)
88                if reply[0] != 'OK':
89                        sys.exit('Could not bind to Skype client')
90
91                reply = self.send('PROTOCOL 5')
92                try:
93                        dbus.service.Object.__init__(self, bus, "/com/Skype/Client", bus_name='com.Skype.API')
94                except KeyError:
95                        sys.exit()
96
97        # skype -> client (async)
98        @dbus.service.method(dbus_interface='com.Skype.API')
99        def Notify(self, msg_text):
100                global conn
101                dprint('<< ' + msg_text)
102                if conn:
103                        conn.send(msg_text + "\n")
104
105        # client -> skype (sync, 5 sec timeout)
106        def send(self, msg_text):
107                if not len(msg_text):
108                        return
109                dprint('>> ' + msg_text)
110                try:
111                        reply = self.skype_api.Invoke(msg_text)
112                except dbus.exceptions.DBusException, s:
113                        reply = str(s)
114                        if(reply.startswith("org.freedesktop.DBus.Error.ServiceUnknown")):
115                                try:
116                                        self.remove_from_connection(dbus.SessionBus(), "/com/Skype/Client")
117                                except LookupError:
118                                        pass
119                                mainloop.quit()
120                if "\n" in reply:
121                        # crappy skype prefixes only the first line for
122                        # multiline messages so we need to do so for the other
123                        # lines, too. this is something like:
124                        # 'CHATMESSAGE id BODY first line\nsecond line' ->
125                        # 'CHATMESSAGE id BODY first line\nCHATMESSAGE id BODY second line'
126                        prefix = " ".join(reply.split(" ")[:3])
127                        reply = ["%s %s" % (prefix, i) for i in " ".join(reply.split(" ")[3:]).split("\n")]
128                else:
129                        reply = [reply]
130                for i in reply:
131                        dprint('<< ' + i)
132                return reply
133
134class Options:
135        def __init__(self):
136                self.daemon = True
137                self.debug = False
138                self.help = False
139                self.port = 2727
140                self.version = False
141
142        def usage(self, ret):
143                print """Usage: skyped [OPTION]...
144
145skyped is a daemon that acts as a tcp server on top of a Skype instance.
146
147Options:
148        -d      --debug         enable debug messages
149        -h      --help          this help
150        -n      --nofork        don't run as daemon in the background
151        -p      --port          set the tcp port (default: %d)
152        -v      --version       display version information""" % self.port
153                sys.exit(ret)
154
155if __name__=='__main__':
156        options = Options()
157        try:
158                opts, args = getopt.getopt(sys.argv[1:], "dhnp:v", ["daemon", "help", "nofork", "port=", "version"])
159        except getopt.GetoptError:
160                options.usage(1)
161        for opt, arg in opts:
162                if opt in ("-d", "--debug"):
163                        options.debug = True
164                elif opt in ("-h", "--help"):
165                        options.help = True
166                elif opt in ("-n", "--nofork"):
167                        options.daemon = False
168                elif opt in ("-p", "--port"):
169                        options.port = arg
170                elif opt in ("-v", "--version"):
171                        options.version = True
172        if options.help:
173                options.usage(0)
174        elif options.version:
175                print "skyped %s" % __version__
176                sys.exit(0)
177        elif options.daemon:
178                pid = os.fork()
179                if pid == 0:
180                        nullin = file('/dev/null', 'r')
181                        nullout = file('/dev/null', 'w')
182                        os.dup2(nullin.fileno(), sys.stdin.fileno())
183                        os.dup2(nullout.fileno(), sys.stdout.fileno())
184                        os.dup2(nullout.fileno(), sys.stderr.fileno())
185                else:
186                        print 'skyped is started on port %s, pid: %d' % (options.port, pid)
187                        sys.exit(0)
188        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
189        signal.signal(signal.SIGINT, sig_handler)
190        mainloop = gobject.MainLoop()
191        server('0.0.0.0', options.port)
192        while True:
193                skype = SkypeApi()
194                mainloop.run()
Note: See TracBrowser for help on using the repository browser.