Shinya Okano avatar Shinya Okano committed 2fb152a Merge

refs #6 merge t6

Comments (0)

Files changed (30)

 
 ::
 
-  easy_install Skype4Py
   easy_install django-skypehub
-# -*- coding:utf8 -*-
-from distutils.command.install_data import install_data
-from distutils.command.install import INSTALL_SCHEMES
+import os
 
-from setuptools import setup
+from setuptools import setup, find_packages
 
-import os
-import sys
-
-class osx_install_data(install_data):
-    # On MacOS, the platform-specific lib dir is /System/Library/Framework/Python/.../
-    # which is wrong. Python 2.5 supplied with MacOS 10.5 has an Apple-specific fix
-    # for this in distutils.command.install_data#306. It fixes install_lib but not
-    # install_data, which is why we roll our own install_data class.
-
-    def finalize_options(self):
-        # By the time finalize_options is called, install.install_lib is set to the
-        # fixed directory, so we set the installdir to install_lib. The
-        # install_data class uses ('install_data', 'install_dir') instead.
-        self.set_undefined_options('install', ('install_lib', 'install_dir'))
-        install_data.finalize_options(self)
-
-if sys.platform == "darwin":
-    cmdclasses = {'install_data': osx_install_data}
-else:
-    cmdclasses = {'install_data': install_data}
-
-def fullsplit(path, result=None):
-    """
-    Split a pathname into components (the opposite of os.path.join) in a
-    platform-neutral way.
-    """
-    if result is None:
-        result = []
-    head, tail = os.path.split(path)
-    if head == '':
-        return [tail] + result
-    if head == path:
-        return result
-    return fullsplit(head, [tail] + result)
-
-# Tell distutils to put the data_files in platform-specific installation
-# locations. See here for an explanation:
-# http://groups.google.com/group/comp.lang.python/browse_thread/thread/35ec7b2fed36eaec/2105ee4d9e8042cb
-for scheme in INSTALL_SCHEMES.values():
-    scheme['data'] = scheme['purelib']
-
-# Compile the list of packages available, because distutils doesn't have
-# an easy way to do this.
-packages, data_files = [], []
-root_dir = os.path.dirname(__file__)
-if root_dir != '':
-    os.chdir(root_dir)
-skypehub = 'skypehub'
-
-for dirpath, dirnames, filenames in os.walk('skypehub'):
-    # Ignore dirnames that start with '.'
-    for i, dirname in enumerate(dirnames):
-        if dirname.startswith('.'): del dirnames[i]
-    if '__init__.py' in filenames:
-        packages.append('.'.join(fullsplit(dirpath)))
-    elif filenames:
-        data_files.append([dirpath, [os.path.join(dirpath, f) for f in filenames]])
-
-# Small hack for working with bdist_wininst.
-# See http://mail.python.org/pipermail/distutils-sig/2004-August/004134.html
-if len(sys.argv) > 1 and sys.argv[1] == 'bdist_wininst':
-    for file_info in data_files:
-        file_info[0] = '\\PURELIB\\%s' % file_info[0]
 
 setup(
     name='django-skypehub',
-    version='0.2.1',
-    description='Django-skypehub is an app to use skype in remote api',
+    version='0.3.0',
+    description='Skype API bridge for Django',
     author='Shinya Okano',
     author_email='tokibito@gmail.com',
     url='http://bitbucket.org/tokibito/django-skypehub/',
-    packages = packages,
-    cmdclass = cmdclasses,
-    data_files = data_files,
+    packages=find_packages('src'),
+    package_dir={'': 'src'},
     license='BSD',
-    keywords='django skype webapp',
+    keywords='django skype',
     classifiers=[
         'Development Status :: 3 - Alpha',
         'Environment :: Web Environment',
         'Framework :: Django',
-        'Intended Audience :: Developers',
         'License :: OSI Approved :: BSD License',
-        'Natural Language :: English',
-        'Operating System :: OS Independent',
         'Programming Language :: Python',
-    ]
+    ],
+    install_requires=[
+        'Django',
+        'Skype4Py',
+    ],
+    zip_safe=False,
 )

skypehub/__init__.py

-VERSION = (0, 2, 1, None)

skypehub/admin.py

-from django.contrib import admin
-
-from skypehub.models import Message
-
-class MessageModelAdmin(admin.ModelAdmin):
-    list_display = ('sender', 'chat_name', 'body', 'ctime')
-    list_filter = ('chat_name', 'sender', 'ctime')
-    search_fields = ('sender', 'chat_name', 'body')
-
-admin.site.register(Message, MessageModelAdmin)

skypehub/decorators.py

-from django.conf import settings
-
-from skypehub.utils import get_skype, get_skype_hook_options
-
-def skype_required(view):
-    def _inner(request, *args, **kwargs):
-        hook_options = get_skype_hook_options()
-        skype = get_skype(**hook_options)
-        return view(request, skype, *args, **kwargs)
-    return _inner

skypehub/forms.py

-from django import forms
-
-class PostMessageForm(forms.Form):
-    message = forms.CharField()
-    chat = forms.CharField()
-
-class PostUserMessageForm(forms.Form):
-    message = forms.CharField()
-    username = forms.CharField()

skypehub/handlers.py

-from collections import defaultdict
-from select import select
-from time import time
-from struct import pack, unpack
-
-from skypehub.models import Message
-from skypehub.utils import is_windows
-
-def message_logging_receiver(handler, message, status):
-    Message.objects.create(
-        body=message.Body,
-        sender=message.Sender.Handle,
-        chat_name=message.Chat.Name,
-    )
-
-class OnMessageHandler(object):
-    """
-    Skype OnMessage event handler
-    """
-    default_statuses = ('RECEIVED',)
-    default_receivers = ()
-
-    def __init__(self, skype=None):
-        self.receivers = defaultdict(lambda: set()) 
-        for status in self.default_statuses:
-            for receiver in self.default_receivers:
-                self.receivers[status].add(receiver)
-        self.skype = skype
-
-    def connect(self, receiver, statuses=None):
-        if statuses is None:
-            statuses = list(self.default_statuses)
-        for status in statuses:
-            self.receivers[status].add(receiver)
-
-    def dispatch(self, message, status):
-        for receiver in self.receivers[status]:
-            receiver(self, message, status)
-
-class OnTimeHandler(object):
-    """
-    Skype OnTime event handler
-    by moriyoshi
-    """
-    def __init__(self, skype=None):
-        self.skype = skype
-        # TODO: socketpair does not work on Windows.
-        from socket import socketpair
-        self.pair = socketpair()
-        self.timepoints = []
-        self.callables = {}
-        self._callables = {}
-        self.id = 1
-
-    def connect(self, callable, time):
-        id = self.callables.get(callable, 0)
-        if not id:
-            id = self.id
-            self.id += 1
-            self.callables[callable] = id
-            self._callables[id] = callable
-        self.pair[1].send(pack("@ii", time, id))
-
-    def __call__(self):
-        wait = None
-        while True:
-            r, w, e = select([self.pair[0]], [], [], wait)
-            if r:
-                t, id = unpack("@ii", r[0].recv(8))
-                i = self.search_nearest(t)
-                self.timepoints.insert(i, (t, id))
-                wait = max(self.timepoints[0][0] - time(), 0)
-            else:
-                _time, id = self.timepoints.pop(0)
-                self._callables[id](self, _time)
-                if self.timepoints:
-                    wait = max(self.timepoints[0][0] - time(), 0)
-                else:
-                    wait = None
-
-    def search_nearest(self, time):
-        l = len(self.timepoints)
-        if l == 0:
-            return 0
-        s = 0
-        e = l
-
-        while True:
-            i = (s + e) // 2
-            if self.timepoints[i][0] < time:
-                s = i
-                i = (i + e) // 2
-                if i == l - 1:
-                    i = l
-                    break
-            else:
-                e = i
-                i = (s + i) // 2
-                if i == 0:
-                    break
-        return i
-
-
-on_message = OnMessageHandler()
-if is_windows():
-    def on_time():
-        import time
-        while True:
-            time.sleep(1)
-else:
-    on_time = OnTimeHandler()
-on_message.connect(message_logging_receiver)
Add a comment to this file

skypehub/management/__init__.py

Empty file removed.

Add a comment to this file

skypehub/management/commands/__init__.py

Empty file removed.

skypehub/management/commands/runskypebot.py

-import os
-import imp
-from optparse import make_option
-
-from django.conf import settings
-from django.core.management import BaseCommand
-from django.utils.daemonize import become_daemon
-from django.utils.importlib import import_module
-
-from skypehub.utils import skype
-
-class Command(BaseCommand):
-    option_list = BaseCommand.option_list + (
-        make_option('--daemonize', action='store_true',
-                dest='daemonize', help='daemonize bot.'),
-        make_option('--pidfile', dest='pidfile', default=None,
-                help='create pid file.'),
-    )
-    help = "run skype bot."
-
-    def handle(self, *args, **options):
-        # --daemonize
-        if options['daemonize']:
-            become_daemon()
-
-        # --pidfile
-        if options['pidfile']:
-            pidfile = open(options['pidfile'], 'w')
-            pidfile.write('%d' % os.getpid())
-            pidfile.close()
-
-        from skypehub.handlers import on_message, on_time
-
-        # load module
-        for app in settings.INSTALLED_APPS:
-            try:
-                app_path = import_module(app).__path__
-            except AttributeError:
-                continue
-            try:
-                imp.find_module('skypebot', app_path)
-            except ImportError:
-                continue
-            import_module("%s.skypebot" % app)
-
-        # attach skype
-        on_message.skype = skype
-        on_time.skype = skype
-        skype.OnMessageStatus = on_message.dispatch
-
-        try:
-            skype.Attach()
-            on_time()
-        except KeyboardInterrupt:
-            import sys
-            sys.exit()

skypehub/models.py

-# coding: utf-8
-from django.db import models
-
-class Message(models.Model):
-    body = models.TextField(u'本文')
-    sender = models.CharField(u'送信者', max_length=200, db_index=True)
-    chat_name = models.CharField(u'チャット名', max_length=100, db_index=True)
-    ctime = models.DateTimeField(u'作成日時', auto_now_add=True, db_index=True)
-
-    def __unicode__(self):
-        return self.body
-
-    class Meta:
-        ordering = ('-ctime',)
-        verbose_name = u'スカイプメッセージ'
-        verbose_name_plural = u'スカイプメッセージ'

skypehub/test.py

-class MockChat(object):
-    def __init__(self, name, topic=None):
-        self.Name = name
-        self.Topic = topic
-
-    def SendMessage(self, message):
-        pass
-
-
-class MockSkype(object):
-    def __init__(self, **options):
-        self.options = options
-        self.chats = []
-
-    def get_chats(self):
-        return self.chats
-
-    Chats = property(get_chats)
-
-    def CreateChatWith(self, name):
-        chat = MockChat('#%s/$test;test' % name)
-        self.add_chat(chat)
-        return chat
-
-    def add_chat(self, chat):
-        self.chats.append(chat)

skypehub/tests.py

-from django.test import TestCase
-
-from skypehub.decorators import skype_required
-from skypehub.views import _list_chats, _post_message
-from skypehub.utils import json
-from skypehub.test import MockSkype, MockChat
-
-
-class SkypeRequiredDecoratorTest(TestCase):
-    def test_decorate(self):
-        """skype_required decorator
-        """
-        decorated = skype_required(lambda req, skype: skype)
-        self.assertNotEqual(decorated, None)
-
-
-class SkypeViewListChatsTest(TestCase):
-    def setUp(self):
-        self.skype = MockSkype()
-        self.chat = MockChat('chatname', 'topic')
-        self.skype.add_chat(self.chat)
-
-    def test_list_chats(self):
-        response = _list_chats(None, self.skype)
-        self.assertEqual(json.loads(response.content), {
-          "chats": [
-            {
-              "topic": "topic",
-              "name": "chatname"
-            }
-          ]
-        })

skypehub/urls.py

-from django.conf.urls.defaults import *
-
-urlpatterns = patterns('skypehub.views',
-    url(r'^list_chats$', 'list_chats', name='skype_list_chats'),
-    url(r'^post_message', 'post_message', name='skype_post_message'),
-)

skypehub/utils.py

-#:coding=utf-8:
-
-import Skype4Py
-from Skype4Py.errors import SkypeError
-
-SKYPE_HOOK_OPTIONS = {
-    'Transport': 'x11',
-}
-
-
-def get_skype(**kwargs):
-    """return skype object.
-    """
-    options = kwargs or {}
-    return Skype4Py.Skype(**options)
-
-
-def get_skype_hook_options():
-    """return SKYPE_HOOK_OPTIONS
-    """
-    from django.conf import settings
-    if hasattr(settings, 'SKYPE_HOOK_OPTIONS'):
-        return settings.SKYPE_HOOK_OPTIONS
-    if is_windows():
-        return {}
-    return SKYPE_HOOK_OPTIONS
-
-
-def is_windows():
-    """Detect Windows platform.
-    """
-    import platform
-    return platform.system() == 'Windows'
-
-skype = get_skype(**get_skype_hook_options())

skypehub/views.py

-#:coding=utf-8:
-
-from django.utils import simplejson as json
-from django.http import HttpResponse
-
-from skypehub.utils import skype, SkypeError
-from skypehub.forms import PostMessageForm, PostUserMessageForm
-
-
-def make_json_response(content, status=200):
-    return HttpResponse(json.dumps(content, indent=2), content_type='application/javascript', status=status)
-
-
-def list_chats(request):
-    chats = []
-    for chat in skype.Chats:
-        chats.append({
-            'name': chat.Name,
-            'topic': chat.Topic,
-        })
-    return make_json_response({'chats': chats})
-
-def post_message(request):
-    form = PostMessageForm(request.POST or None)
-    try:
-        if form.is_valid():
-            chat = skype.Chat(form.cleaned_data['chat'])
-            if hasattr(chat, 'AsyncSendMessage'):
-                chat.AsyncSendMessage(form.cleaned_data['message'])
-            else:
-                chat.SendMessage(form.cleaned_data['message'])
-            return make_json_response({'result': 'ok'})
-        else:
-            form = PostUserMessageForm(request.POST or None)
-            if form.is_valid():
-                if hasattr(skype, 'AsyncSendMessage'):
-                    skype.AsyncSendMessage(form.cleaned_data['username'], form.cleaned_data['message'])
-                else:
-                    skype.SendMessage(form.cleaned_data['username'], form.cleaned_data['message'])
-                return make_json_response({'result': 'ok'})
-    except SkypeError, e:
-        # Invalid chat name (errno=105)
-        # or Sending a message to failes (errno=511)
-        if e.args[0] in [105, 511]:
-            return make_json_response({'result': e.args[1]}, status=403)
-        else:
-            raise e
-    return  make_json_response({'result': 'validation error.'})

src/skypehub/__init__.py

+VERSION = (0, 3, 0, 'dev')

src/skypehub/admin.py

+from django.contrib import admin
+
+from skypehub.models import Message
+
+
+class MessageModelAdmin(admin.ModelAdmin):
+    list_display = ('sender', 'chat_name', 'body', 'ctime')
+    list_filter = ('chat_name', 'sender', 'ctime')
+    search_fields = ('sender', 'chat_name', 'body')
+
+admin.site.register(Message, MessageModelAdmin)

src/skypehub/decorators.py

+from django.conf import settings
+
+from skypehub.utils import get_skype, get_skype_hook_options
+
+
+def skype_required(view):
+    def _inner(request, *args, **kwargs):
+        hook_options = get_skype_hook_options()
+        skype = get_skype(**hook_options)
+        return view(request, skype, *args, **kwargs)
+    return _inner

src/skypehub/forms.py

+# coding: utf-8
+from django import forms
+
+
+class PostMessageForm(forms.Form):
+    message = forms.CharField()
+    chat = forms.CharField()
+
+
+class PostUserMessageForm(forms.Form):
+    message = forms.CharField()
+    username = forms.CharField()

src/skypehub/handlers.py

+from collections import defaultdict
+from select import select
+from time import time
+from struct import pack, unpack
+
+from Skype4Py.errors import SkypeAPIError
+
+from skypehub.models import Message
+from skypehub.utils import is_windows, get_skype
+
+
+def message_logging_receiver(handler, message, status):
+    Message.objects.create(
+        body=message.Body,
+        sender=message.Sender.Handle,
+        chat_name=message.Chat.Name,
+    )
+
+
+class OnMessageHandler(object):
+    """
+    Skype OnMessage event handler
+    """
+    default_statuses = ('RECEIVED',)
+    default_receivers = ()
+
+    def __init__(self, skype=None):
+        self.receivers = defaultdict(lambda: set())
+        for status in self.default_statuses:
+            for receiver in self.default_receivers:
+                self.receivers[status].add(receiver)
+        self.skype = skype
+
+    def connect(self, receiver, statuses=None):
+        if statuses is None:
+            statuses = list(self.default_statuses)
+        for status in statuses:
+            self.receivers[status].add(receiver)
+
+    def dispatch(self, message, status):
+        try:
+            for receiver in self.receivers[status]:
+                receiver(self, message, status)
+        except SkypeAPIError, err:
+            # reconnect skype
+            get_skype(force_create=True)
+
+
+class OnTimeHandler(object):
+    """
+    Skype OnTime event handler
+    by moriyoshi
+    """
+    def __init__(self, skype=None):
+        self.skype = skype
+        # TODO: socketpair does not work on Windows.
+        from socket import socketpair
+        self.pair = socketpair()
+        self.timepoints = []
+        self.callables = {}
+        self._callables = {}
+        self.id = 1
+
+    def connect(self, callable, time):
+        id = self.callables.get(callable, 0)
+        if not id:
+            id = self.id
+            self.id += 1
+            self.callables[callable] = id
+            self._callables[id] = callable
+        self.pair[1].send(pack("@ii", time, id))
+
+    def __call__(self):
+        wait = None
+        while True:
+            r, w, e = select([self.pair[0]], [], [], wait)
+            if r:
+                t, id = unpack("@ii", r[0].recv(8))
+                i = self.search_nearest(t)
+                self.timepoints.insert(i, (t, id))
+                wait = max(self.timepoints[0][0] - time(), 0)
+            else:
+                _time, id = self.timepoints.pop(0)
+                self._callables[id](self, _time)
+                if self.timepoints:
+                    wait = max(self.timepoints[0][0] - time(), 0)
+                else:
+                    wait = None
+
+    def search_nearest(self, time):
+        l = len(self.timepoints)
+        if l == 0:
+            return 0
+        s = 0
+        e = l
+
+        while True:
+            i = (s + e) // 2
+            if self.timepoints[i][0] < time:
+                s = i
+                i = (i + e) // 2
+                if i == l - 1:
+                    i = l
+                    break
+            else:
+                e = i
+                i = (s + i) // 2
+                if i == 0:
+                    break
+        return i
+
+
+on_message = OnMessageHandler()
+if is_windows():
+    def on_time():
+        import time
+        while True:
+            time.sleep(1)
+else:
+    on_time = OnTimeHandler()
+on_message.connect(message_logging_receiver)
Add a comment to this file

src/skypehub/management/__init__.py

Empty file added.

Add a comment to this file

src/skypehub/management/commands/__init__.py

Empty file added.

src/skypehub/management/commands/runskypebot.py

+import os
+import imp
+from optparse import make_option
+
+from django.conf import settings
+from django.core.management import BaseCommand
+from django.utils.daemonize import become_daemon
+from django.utils.importlib import import_module
+
+
+class Command(BaseCommand):
+    option_list = BaseCommand.option_list + (
+        make_option('--daemonize', action='store_true',
+                    dest='daemonize', help='daemonize bot.'),
+        make_option('--pidfile', dest='pidfile', default=None,
+                    help='create pid file.'),
+    )
+    help = "run skype bot."
+
+    def handle(self, *args, **options):
+        # --daemonize
+        if options['daemonize']:
+            become_daemon()
+
+        # --pidfile
+        if options['pidfile']:
+            pidfile = open(options['pidfile'], 'w')
+            pidfile.write('%d' % os.getpid())
+            pidfile.close()
+
+        from skypehub.handlers import on_message, on_time
+        from skypehub.utils import get_skype
+
+        # load module
+        for app in settings.INSTALLED_APPS:
+            try:
+                app_path = import_module(app).__path__
+            except AttributeError:
+                continue
+            try:
+                imp.find_module('skypebot', app_path)
+            except ImportError:
+                continue
+            import_module("%s.skypebot" % app)
+
+        # attach skype
+        skype = get_skype()
+        on_message.skype = skype
+        on_time.skype = skype
+        skype.OnMessageStatus = on_message.dispatch
+
+        try:
+            skype.Attach()
+            on_time()
+        except KeyboardInterrupt:
+            import sys
+            sys.exit()

src/skypehub/models.py

+# coding: utf-8
+from django.db import models
+
+
+class Message(models.Model):
+    body = models.TextField(u'本文')
+    sender = models.CharField(u'送信者', max_length=200, db_index=True)
+    chat_name = models.CharField(u'チャット名', max_length=100, db_index=True)
+    ctime = models.DateTimeField(u'作成日時', auto_now_add=True, db_index=True)
+
+    def __unicode__(self):
+        return self.body
+
+    class Meta:
+        ordering = ('-ctime',)
+        verbose_name = u'スカイプメッセージ'
+        verbose_name_plural = u'スカイプメッセージ'

src/skypehub/test.py

+class MockChat(object):
+    def __init__(self, name, topic=None):
+        self.Name = name
+        self.Topic = topic
+
+    def SendMessage(self, message):
+        pass
+
+
+class MockSkype(object):
+    def __init__(self, **options):
+        self.options = options
+        self.chats = []
+
+    def get_chats(self):
+        return self.chats
+
+    Chats = property(get_chats)
+
+    def CreateChatWith(self, name):
+        chat = MockChat('#%s/$test;test' % name)
+        self.add_chat(chat)
+        return chat
+
+    def add_chat(self, chat):
+        self.chats.append(chat)

src/skypehub/tests.py

+from django.test import TestCase
+
+from skypehub.decorators import skype_required
+from skypehub.views import _list_chats, _post_message
+from skypehub.utils import json
+from skypehub.test import MockSkype, MockChat
+
+
+class SkypeRequiredDecoratorTest(TestCase):
+    def test_decorate(self):
+        """skype_required decorator
+        """
+        decorated = skype_required(lambda req, skype: skype)
+        self.assertNotEqual(decorated, None)
+
+
+class SkypeViewListChatsTest(TestCase):
+    def setUp(self):
+        self.skype = MockSkype()
+        self.chat = MockChat('chatname', 'topic')
+        self.skype.add_chat(self.chat)
+
+    def test_list_chats(self):
+        response = _list_chats(None, self.skype)
+        self.assertEqual(json.loads(response.content), {
+            "chats": [
+                {"topic": "topic",
+                 "name": "chatname"}
+            ]
+        })

src/skypehub/urls.py

+from django.conf.urls.defaults import url, patterns
+
+
+urlpatterns = patterns(
+    'skypehub.views',
+    url(r'^list_chats$', 'list_chats', name='skype_list_chats'),
+    url(r'^post_message', 'post_message', name='skype_post_message'),
+)

src/skypehub/utils.py

+# coding: utf-8
+
+from Skype4Py.errors import SkypeError
+
+
+SKYPE_HOOK_OPTIONS = {
+    'Transport': 'x11',
+}
+
+_skype = None
+
+
+def get_skype(force_create=False, **kwargs):
+    """return skype object.
+    """
+    global _skype
+    from Skype4Py import Skype
+    options = get_skype_hook_options()
+    options.update(kwargs)
+    if _skype is None or force_create:
+        _skype = Skype(**options)
+    return _skype
+
+
+def get_skype_hook_options():
+    """return SKYPE_HOOK_OPTIONS
+    """
+    from django.conf import settings
+    if hasattr(settings, 'SKYPE_HOOK_OPTIONS'):
+        return settings.SKYPE_HOOK_OPTIONS
+    if is_windows():
+        return {}
+    return SKYPE_HOOK_OPTIONS
+
+
+def is_windows():
+    """Detect Windows platform.
+    """
+    import platform
+    return platform.system() == 'Windows'

src/skypehub/views.py

+# coding: utf-8
+
+from django.utils import simplejson as json
+from django.http import HttpResponse
+
+from skypehub.utils import get_skype, SkypeError
+from skypehub.forms import PostMessageForm, PostUserMessageForm
+
+
+def make_json_response(content, status=200):
+    return HttpResponse(
+        json.dumps(content, indent=2),
+        content_type='application/javascript', status=status)
+
+
+def list_chats(request):
+    skype = get_skype()
+    chats = []
+    for chat in skype.Chats:
+        chats.append({
+            'name': chat.Name,
+            'topic': chat.Topic,
+        })
+    return make_json_response({'chats': chats})
+
+
+def post_message(request):
+    form = PostMessageForm(request.POST or None)
+    try:
+        skype = get_skype()
+        if form.is_valid():
+            chat = skype.Chat(form.cleaned_data['chat'])
+            if hasattr(chat, 'AsyncSendMessage'):
+                chat.AsyncSendMessage(form.cleaned_data['message'])
+            else:
+                chat.SendMessage(form.cleaned_data['message'])
+            return make_json_response({'result': 'ok'})
+        else:
+            form = PostUserMessageForm(request.POST or None)
+            if form.is_valid():
+                if hasattr(skype, 'AsyncSendMessage'):
+                    skype.AsyncSendMessage(
+                        form.cleaned_data['username'],
+                        form.cleaned_data['message'])
+                else:
+                    skype.SendMessage(
+                        form.cleaned_data['username'],
+                        form.cleaned_data['message'])
+                return make_json_response({'result': 'ok'})
+    except SkypeError, e:
+        # Invalid chat name (errno=105)
+        # or Sending a message to failes (errno=511)
+        if e.args[0] in [105, 511]:
+            return make_json_response({'result': e.args[1]}, status=403)
+        else:
+            raise e
+    return make_json_response({'result': 'validation error.'})
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.