source: skype/skyped.py @ 52d779e

Last change on this file since 52d779e was 52d779e, checked in by VMiklos <vmiklos@…>, at 2007-09-04T19:29:42Z

skyped: fix receiving / sending accents again

  • Property mode set to 100644
File size: 4.9 KB
RevLine 
[4ddda13]1#!/usr/bin/env python
[cd3022c]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
[4ddda13]27import sys
[8237df5]28import os
[4ddda13]29import signal
30import locale
31import time
32import gobject
33import socket
[8237df5]34import getopt
[c15f71a]35import Skype4Py
36import threading
[4ddda13]37
[8237df5]38__version__ = "0.1.1"
[4ddda13]39
40SKYPE_SERVICE = 'com.Skype.API'
41CLIENT_NAME = 'SkypeApiPythonShell'
42
43# well, this is a bit hackish. we store the socket of the last connected client
44# here and notify it. maybe later notify all connected clients?
45conn = None
46
47def input_handler(fd, io_condition):
[94bd28f]48        input = fd.recv(1024)
49        for i in input.split("\n"):
[c15f71a]50                skype.send(i.strip())
51        return True
52
53def idle_handler(skype):
54        skype.send("PING")
55        try:
56                time.sleep(10)
57        except KeyboardInterrupt:
58                sys.exit("Exiting.")
[94bd28f]59        return True
[4ddda13]60
[a316c4e]61def server(host, port):
62        sock = socket.socket()
63        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
64        sock.bind((host, port))
65        sock.listen(1)
66        gobject.io_add_watch(sock, gobject.IO_IN, listener)
67
68def listener(sock, *args):
69        global conn
70        conn, addr = sock.accept()
71        fileno = conn.fileno()
72        gobject.io_add_watch(conn, gobject.IO_IN, input_handler)
73        return True
74
75def dprint(msg):
[8237df5]76        global options
77
78        if options.debug:
[a316c4e]79                print msg
80
[c15f71a]81class SkypeApi():
[94bd28f]82        def __init__(self):
[c15f71a]83                self.skype = Skype4Py.Skype()
84                self.skype._API.Handlers.append(Skype4Py.utils.WeakCallableRef(self.recv))
85                self.skype._API._Handler = self.recv
86                self.skype.Attach()
[94bd28f]87
[c15f71a]88        def recv(self, mode, msg_text):
[94bd28f]89                global conn
[c15f71a]90                if mode != "rece_api":
[94bd28f]91                        return
[c15f71a]92                if "\n" in msg_text:
[7613670]93                        # crappy skype prefixes only the first line for
94                        # multiline messages so we need to do so for the other
95                        # lines, too. this is something like:
96                        # 'CHATMESSAGE id BODY first line\nsecond line' ->
97                        # 'CHATMESSAGE id BODY first line\nCHATMESSAGE id BODY second line'
[c15f71a]98                        prefix = " ".join(msg_text.split(" ")[:3])
99                        msg_text = ["%s %s" % (prefix, i) for i in " ".join(msg_text.split(" ")[3:]).split("\n")]
[7613670]100                else:
[c15f71a]101                        msg_text = [msg_text]
102                for i in msg_text:
[52d779e]103                        e = i.encode(locale.getdefaultlocale()[1])
104                        dprint('<< ' + e)
[c15f71a]105                        if conn:
[52d779e]106                                conn.send(e + "\n")
[c15f71a]107
108        def send(self, msg_text):
109                if not len(msg_text):
110                        return
[52d779e]111                e = msg_text.decode(locale.getdefaultlocale()[1])
112                dprint('>> ' + e)
[c15f71a]113                try:
[52d779e]114                        self.skype._DoCommand(e)
[c15f71a]115                except Skype4Py.ISkypeError:
116                        pass
[67496f7]117                except Skype4Py.errors.ISkypeAPIError, s:
[52d779e]118                        dprint("Warning, seding '%s' failed (%s)." % (e, s))
[4ddda13]119
[8237df5]120class Options:
121        def __init__(self):
122                self.daemon = True
123                self.debug = False
124                self.help = False
125                self.port = 2727
126                self.version = False
127
128        def usage(self, ret):
129                print """Usage: skyped [OPTION]...
130
131skyped is a daemon that acts as a tcp server on top of a Skype instance.
132
133Options:
134        -d      --debug         enable debug messages
135        -h      --help          this help
136        -n      --nofork        don't run as daemon in the background
137        -p      --port          set the tcp port (default: %d)
138        -v      --version       display version information""" % self.port
139                sys.exit(ret)
140
[4ddda13]141if __name__=='__main__':
[8237df5]142        options = Options()
143        try:
144                opts, args = getopt.getopt(sys.argv[1:], "dhnp:v", ["daemon", "help", "nofork", "port=", "version"])
145        except getopt.GetoptError:
146                options.usage(1)
147        for opt, arg in opts:
148                if opt in ("-d", "--debug"):
149                        options.debug = True
150                elif opt in ("-h", "--help"):
151                        options.help = True
152                elif opt in ("-n", "--nofork"):
153                        options.daemon = False
154                elif opt in ("-p", "--port"):
155                        options.port = arg
156                elif opt in ("-v", "--version"):
157                        options.version = True
158        if options.help:
159                options.usage(0)
160        elif options.version:
161                print "skyped %s" % __version__
162                sys.exit(0)
163        elif options.daemon:
164                pid = os.fork()
165                if pid == 0:
166                        nullin = file('/dev/null', 'r')
167                        nullout = file('/dev/null', 'w')
168                        os.dup2(nullin.fileno(), sys.stdin.fileno())
169                        os.dup2(nullout.fileno(), sys.stdout.fileno())
170                        os.dup2(nullout.fileno(), sys.stderr.fileno())
171                else:
172                        print 'skyped is started on port %s, pid: %d' % (options.port, pid)
173                        sys.exit(0)
[53b71d3]174        server('0.0.0.0', options.port)
[c15f71a]175        try:
[3953172]176                skype = SkypeApi()
[c15f71a]177        except Skype4Py.errors.ISkypeAPIError, s:
178                sys.exit("%s. Are you sure you have started Skype?" % s)
179        gobject.idle_add(idle_handler, skype)
180        gobject.MainLoop().run()
Note: See TracBrowser for help on using the repository browser.