source: skype/skyped.py @ 5245e9d

Last change on this file since 5245e9d 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
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
[5245e9d]37import sha
38from ConfigParser import ConfigParser
[4ddda13]39
[8237df5]40__version__ = "0.1.1"
[4ddda13]41
42SKYPE_SERVICE = 'com.Skype.API'
43CLIENT_NAME = 'SkypeApiPythonShell'
44
45def input_handler(fd, io_condition):
[5245e9d]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
[c15f71a]56
57def idle_handler(skype):
[3922d44]58        try:
59                skype.skype.SendCommand(skype.skype.Command(-1, "PING"))
60        except Skype4Py.SkypeAPIError, s:
61                dprint("Warning, pinging Skype failed (%s)." % (s))
[c15f71a]62        try:
[d86dfb1]63                time.sleep(2)
[c15f71a]64        except KeyboardInterrupt:
65                sys.exit("Exiting.")
[94bd28f]66        return True
[4ddda13]67
[a316c4e]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):
[5245e9d]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
[a316c4e]98
99def dprint(msg):
[8237df5]100        global options
101
102        if options.debug:
[a316c4e]103                print msg
104
[c15f71a]105class SkypeApi():
[94bd28f]106        def __init__(self):
[c15f71a]107                self.skype = Skype4Py.Skype()
[5268bd7]108                self.skype.OnNotify = self.recv
[c15f71a]109                self.skype.Attach()
[94bd28f]110
[5268bd7]111        def recv(self, msg_text):
[5245e9d]112                global options
[d86dfb1]113                if msg_text == "PONG":
114                        return
[c15f71a]115                if "\n" in msg_text:
[7613670]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'
[c15f71a]121                        prefix = " ".join(msg_text.split(" ")[:3])
122                        msg_text = ["%s %s" % (prefix, i) for i in " ".join(msg_text.split(" ")[3:]).split("\n")]
[7613670]123                else:
[c15f71a]124                        msg_text = [msg_text]
125                for i in msg_text:
[a75f2a7]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')
[52d779e]132                        dprint('<< ' + e)
[5245e9d]133                        if options.conn:
[af8675f]134                                try:
[5245e9d]135                                        options.conn.send(e + "\n")
[af8675f]136                                except IOError, s:
[a75f2a7]137                                        dprint("Warning, sending '%s' failed (%s)." % (e, s))
[c15f71a]138
139        def send(self, msg_text):
140                if not len(msg_text):
141                        return
[52d779e]142                e = msg_text.decode(locale.getdefaultlocale()[1])
143                dprint('>> ' + e)
[c15f71a]144                try:
[05cf927]145                        c = self.skype.Command(e, Block=True)
146                        self.skype.SendCommand(c)
147                        self.recv(c.Reply)
148                except Skype4Py.SkypeError:
[c15f71a]149                        pass
[8b3beef]150                except Skype4Py.SkypeAPIError, s:
[a75f2a7]151                        dprint("Warning, sending '%s' failed (%s)." % (e, s))
[4ddda13]152
[8237df5]153class Options:
154        def __init__(self):
[5245e9d]155                self.cfgpath = "/etc/skyped.conf"
[8237df5]156                self.daemon = True
157                self.debug = False
158                self.help = False
[7e450c3]159                self.host = "0.0.0.0"
[8237df5]160                self.port = 2727
161                self.version = False
[5245e9d]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
[8237df5]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:
[5245e9d]175        -c      --config        path to configuration file (default: %s)
[8237df5]176        -d      --debug         enable debug messages
177        -h      --help          this help
[7e450c3]178        -H      --host          set the tcp host (default: %s)
[8237df5]179        -n      --nofork        don't run as daemon in the background
180        -p      --port          set the tcp port (default: %d)
[5245e9d]181        -v      --version       display version information""" % (self.cfgpath, self.host, self.port)
[8237df5]182                sys.exit(ret)
183
[4ddda13]184if __name__=='__main__':
[8237df5]185        options = Options()
186        try:
[5245e9d]187                opts, args = getopt.getopt(sys.argv[1:], "c:dhH:np:v", ["config=", "daemon", "help", "host=", "nofork", "port=", "version"])
[8237df5]188        except getopt.GetoptError:
189                options.usage(1)
190        for opt, arg in opts:
[5245e9d]191                if opt in ("-c", "--config"):
192                        options.cfgpath = arg
193                elif opt in ("-d", "--debug"):
[8237df5]194                        options.debug = True
195                elif opt in ("-h", "--help"):
196                        options.help = True
[7e450c3]197                elif opt in ("-H", "--host"):
198                        options.host = arg
[8237df5]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)
[5245e9d]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:
[8237df5]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)
[7e450c3]231        server(options.host, options.port)
[c15f71a]232        try:
[3953172]233                skype = SkypeApi()
[8b3beef]234        except Skype4Py.SkypeAPIError, s:
[c15f71a]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.