source: skype/skyped.py @ 6af541d

Last change on this file since 6af541d was 6af541d, checked in by Miklos Vajna <vmiklos@…>, at 2008-02-23T02:13:59Z

skyped: automatically start skype if necessary

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