source: skype/skyped.py @ 8237df5

Last change on this file since 8237df5 was 8237df5, checked in by VMiklos <vmiklos@…>, at 2007-08-21T22:33:14Z

skyped: added daemon code

  • Property mode set to 100644
File size: 4.9 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                        fd.send((skype.send(i.strip()) + "\n").encode(locale.getdefaultlocale()[1]))
56        return True
57
58def server(host, port):
59        sock = socket.socket()
60        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
61        sock.bind((host, port))
62        sock.listen(1)
63        gobject.io_add_watch(sock, gobject.IO_IN, listener)
64
65def listener(sock, *args):
66        global conn
67        conn, addr = sock.accept()
68        fileno = conn.fileno()
69        gobject.io_add_watch(conn, gobject.IO_IN, input_handler)
70        return True
71
72def dprint(msg):
73        global options
74
75        if options.debug:
76                print msg
77
78class SkypeApi(dbus.service.Object):
79        def __init__(self):
80                bus = dbus.SessionBus()
81                try:
82                        self.skype_api = bus.get_object(SKYPE_SERVICE, '/com/Skype')
83                except dbus.exceptions.DBusException:
84                        sys.exit("Can't find any Skype instance. Are you sure you have started Skype?")
85
86                reply = self.send('NAME ' + CLIENT_NAME)
87                if reply != 'OK':
88                        sys.exit('Could not bind to Skype client')
89
90                reply = self.send('PROTOCOL 5')
91                try:
92                        dbus.service.Object.__init__(self, bus, "/com/Skype/Client", bus_name='com.Skype.API')
93                except KeyError:
94                        sys.exit()
95
96        # skype -> client (async)
97        @dbus.service.method(dbus_interface='com.Skype.API')
98        def Notify(self, msg_text):
99                global conn
100                dprint('<< ' + msg_text)
101                if conn:
102                        conn.send(msg_text + "\n")
103
104        # client -> skype (sync, 5 sec timeout)
105        def send(self, msg_text):
106                if not len(msg_text):
107                        return
108                dprint('>> ' + msg_text)
109                try:
110                        reply = self.skype_api.Invoke(msg_text)
111                except dbus.exceptions.DBusException, s:
112                        reply = str(s)
113                        if(reply.startswith("org.freedesktop.DBus.Error.ServiceUnknown")):
114                                self.remove_from_connection(dbus.SessionBus(), "/com/Skype/Client")
115                                mainloop.quit()
116                dprint('<< ' + reply)
117                return reply
118
119class Options:
120        def __init__(self):
121                self.daemon = True
122                self.debug = False
123                self.help = False
124                self.port = 2727
125                self.version = False
126
127        def usage(self, ret):
128                print """Usage: skyped [OPTION]...
129
130skyped is a daemon that acts as a tcp server on top of a Skype instance.
131
132Options:
133        -d      --debug         enable debug messages
134        -h      --help          this help
135        -n      --nofork        don't run as daemon in the background
136        -p      --port          set the tcp port (default: %d)
137        -v      --version       display version information""" % self.port
138                sys.exit(ret)
139
140if __name__=='__main__':
141        options = Options()
142        try:
143                opts, args = getopt.getopt(sys.argv[1:], "dhnp:v", ["daemon", "help", "nofork", "port=", "version"])
144        except getopt.GetoptError:
145                options.usage(1)
146        for opt, arg in opts:
147                if opt in ("-d", "--debug"):
148                        options.debug = True
149                elif opt in ("-h", "--help"):
150                        options.help = True
151                elif opt in ("-n", "--nofork"):
152                        options.daemon = False
153                elif opt in ("-p", "--port"):
154                        options.port = arg
155                elif opt in ("-v", "--version"):
156                        options.version = True
157        if options.help:
158                options.usage(0)
159        elif options.version:
160                print "skyped %s" % __version__
161                sys.exit(0)
162        elif options.daemon:
163                pid = os.fork()
164                if pid == 0:
165                        nullin = file('/dev/null', 'r')
166                        nullout = file('/dev/null', 'w')
167                        os.dup2(nullin.fileno(), sys.stdin.fileno())
168                        os.dup2(nullout.fileno(), sys.stdout.fileno())
169                        os.dup2(nullout.fileno(), sys.stderr.fileno())
170                else:
171                        print 'skyped is started on port %s, pid: %d' % (options.port, pid)
172                        sys.exit(0)
173        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
174        signal.signal(signal.SIGINT, sig_handler)
175        mainloop = gobject.MainLoop()
176        server('localhost', options.port)
177        while True:
178                skype = SkypeApi()
179                mainloop.run()
Note: See TracBrowser for help on using the repository browser.