source: skype/skyped.py @ a3262d1e

Last change on this file since a3262d1e was 5245e9d, checked in by Miklos Vajna <vmiklos@…>, at 2008-01-12T01:36:54Z

skyped: add authentication support
this is not yet ssl, but better than nothing

  • Property mode set to 100644
File size: 6.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 gobject
33import socket
34import getopt
35import Skype4Py
36import threading
37import sha
38from ConfigParser import ConfigParser
39
40__version__ = "0.1.1"
41
42SKYPE_SERVICE = 'com.Skype.API'
43CLIENT_NAME = 'SkypeApiPythonShell'
44
45def input_handler(fd, io_condition):
46        global options
47        if options.buf:
48                for i in options.buf:
49                        skype.send(i.strip())
50                options.buf = None
51        else:
52                input = fd.recv(1024)
53                for i in input.split("\n"):
54                        skype.send(i.strip())
55                return True
56
57def idle_handler(skype):
58        try:
59                skype.skype.SendCommand(skype.skype.Command(-1, "PING"))
60        except Skype4Py.SkypeAPIError, s:
61                dprint("Warning, pinging Skype failed (%s)." % (s))
62        try:
63                time.sleep(2)
64        except KeyboardInterrupt:
65                sys.exit("Exiting.")
66        return True
67
68def server(host, port):
69        sock = socket.socket()
70        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
71        sock.bind((host, port))
72        sock.listen(1)
73        gobject.io_add_watch(sock, gobject.IO_IN, listener)
74
75def listener(sock, *args):
76        global options
77        options.conn, addr = sock.accept()
78        lines = options.conn.recv(512).split('\n')
79        ret = 0
80        nlines = []
81        for i in lines:
82                if i.startswith("USERNAME") and i.split(' ')[1].strip() == options.config.username:
83                        ret += 1
84                elif i.startswith("PASSWORD") and sha.sha(i.split(' ')[1].strip()).hexdigest() == options.config.password:
85                        ret += 1
86                else:
87                        nlines.append(i)
88        del lines
89        if ret == 2:
90                dprint("Username and password OK.")
91                options.buf = nlines
92                input_handler(None, None)
93                gobject.io_add_watch(options.conn, gobject.IO_IN, input_handler)
94                return True
95        else:
96                dprint("Username and/or password WRONG.")
97                return False
98
99def dprint(msg):
100        global options
101
102        if options.debug:
103                print msg
104
105class SkypeApi():
106        def __init__(self):
107                self.skype = Skype4Py.Skype()
108                self.skype.OnNotify = self.recv
109                self.skype.Attach()
110
111        def recv(self, msg_text):
112                global options
113                if msg_text == "PONG":
114                        return
115                if "\n" in msg_text:
116                        # crappy skype prefixes only the first line for
117                        # multiline messages so we need to do so for the other
118                        # lines, too. this is something like:
119                        # 'CHATMESSAGE id BODY first line\nsecond line' ->
120                        # 'CHATMESSAGE id BODY first line\nCHATMESSAGE id BODY second line'
121                        prefix = " ".join(msg_text.split(" ")[:3])
122                        msg_text = ["%s %s" % (prefix, i) for i in " ".join(msg_text.split(" ")[3:]).split("\n")]
123                else:
124                        msg_text = [msg_text]
125                for i in msg_text:
126                        # use utf-8 here to solve the following problem:
127                        # people use env vars like LC_ALL=en_US (latin1) then
128                        # they complain about why can't they receive latin2
129                        # messages.. so here it is: always use utf-8 then
130                        # everybody will be happy
131                        e = i.encode('UTF-8')
132                        dprint('<< ' + e)
133                        if options.conn:
134                                try:
135                                        options.conn.send(e + "\n")
136                                except IOError, s:
137                                        dprint("Warning, sending '%s' failed (%s)." % (e, s))
138
139        def send(self, msg_text):
140                if not len(msg_text):
141                        return
142                e = msg_text.decode(locale.getdefaultlocale()[1])
143                dprint('>> ' + e)
144                try:
145                        c = self.skype.Command(e, Block=True)
146                        self.skype.SendCommand(c)
147                        self.recv(c.Reply)
148                except Skype4Py.SkypeError:
149                        pass
150                except Skype4Py.SkypeAPIError, s:
151                        dprint("Warning, sending '%s' failed (%s)." % (e, s))
152
153class Options:
154        def __init__(self):
155                self.cfgpath = "/etc/skyped.conf"
156                self.daemon = True
157                self.debug = False
158                self.help = False
159                self.host = "0.0.0.0"
160                self.port = 2727
161                self.version = False
162                # well, this is a bit hackish. we store the socket of the last connected client
163                # here and notify it. maybe later notify all connected clients?
164                self.conn = None
165                # this will be read first by the input handler
166                self.buf = None
167
168
169        def usage(self, ret):
170                print """Usage: skyped [OPTION]...
171
172skyped is a daemon that acts as a tcp server on top of a Skype instance.
173
174Options:
175        -c      --config        path to configuration file (default: %s)
176        -d      --debug         enable debug messages
177        -h      --help          this help
178        -H      --host          set the tcp host (default: %s)
179        -n      --nofork        don't run as daemon in the background
180        -p      --port          set the tcp port (default: %d)
181        -v      --version       display version information""" % (self.cfgpath, self.host, self.port)
182                sys.exit(ret)
183
184if __name__=='__main__':
185        options = Options()
186        try:
187                opts, args = getopt.getopt(sys.argv[1:], "c:dhH:np:v", ["config=", "daemon", "help", "host=", "nofork", "port=", "version"])
188        except getopt.GetoptError:
189                options.usage(1)
190        for opt, arg in opts:
191                if opt in ("-c", "--config"):
192                        options.cfgpath = arg
193                elif opt in ("-d", "--debug"):
194                        options.debug = True
195                elif opt in ("-h", "--help"):
196                        options.help = True
197                elif opt in ("-H", "--host"):
198                        options.host = arg
199                elif opt in ("-n", "--nofork"):
200                        options.daemon = False
201                elif opt in ("-p", "--port"):
202                        options.port = arg
203                elif opt in ("-v", "--version"):
204                        options.version = True
205        if options.help:
206                options.usage(0)
207        elif options.version:
208                print "skyped %s" % __version__
209                sys.exit(0)
210        # parse our config
211        if not os.path.exists(options.cfgpath):
212                print "Can't find configuration file at '%s'." % options.cfgpath
213                print "Use the -c option to specify an alternate one."
214                sys.exit(1)
215        options.config = ConfigParser()
216        options.config.read(options.cfgpath)
217        options.config.username = options.config.get('skyped', 'username').split('#')[0]
218        options.config.password = options.config.get('skyped', 'password').split('#')[0]
219        dprint("Parsing config file '%s' done, username is '%s'." % (options.cfgpath, options.config.username))
220        if options.daemon:
221                pid = os.fork()
222                if pid == 0:
223                        nullin = file('/dev/null', 'r')
224                        nullout = file('/dev/null', 'w')
225                        os.dup2(nullin.fileno(), sys.stdin.fileno())
226                        os.dup2(nullout.fileno(), sys.stdout.fileno())
227                        os.dup2(nullout.fileno(), sys.stderr.fileno())
228                else:
229                        print 'skyped is started on port %s, pid: %d' % (options.port, pid)
230                        sys.exit(0)
231        server(options.host, options.port)
232        try:
233                skype = SkypeApi()
234        except Skype4Py.SkypeAPIError, s:
235                sys.exit("%s. Are you sure you have started Skype?" % s)
236        gobject.idle_add(idle_handler, skype)
237        gobject.MainLoop().run()
Note: See TracBrowser for help on using the repository browser.