Newer
Older
# -*- coding: utf-8 -*-
from __future__ import division
__copyright__ = "Copyright (C) 2014 Andreas Kloeckner"
__license__ = """
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
from django.utils.translation import (
ugettext as _, pgettext_lazy)
from django.shortcuts import ( # noqa
render, get_object_or_404, redirect)
from django.contrib import messages # noqa
from django.core.exceptions import PermissionDenied
import django.forms as forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
Andreas Klöckner
committed
from course.models import InstantMessage
from course.constants import (
participation_permission as pperm,
)
from course.models import Course # noqa
from course.utils import course_view, render_course_page
import sleekxmpp
import threading
# {{{ instant message
class InstantMessageForm(forms.Form):
message = forms.CharField(required=True, max_length=200,
label=pgettext_lazy("Instant message", "Message"))
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.form_class = "form-horizontal"
self.helper.label_class = "col-lg-2"
self.helper.field_class = "col-lg-8"
self.helper.add_input(
# Translators: literals in this file are about
# the instant messaging function.
pgettext_lazy("Send instant messages", "Send")))
super(InstantMessageForm, self).__init__(*args, **kwargs)
Andreas Klöckner
committed
_xmpp_connections = {} # type: Dict[int, CourseXMPP]
_disconnectors = [] # type: List[Disconnector]
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
class CourseXMPP(sleekxmpp.ClientXMPP):
def __init__(self, jid, password, recipient_jid):
sleekxmpp.ClientXMPP.__init__(self, jid, password)
self.recipient_jid = recipient_jid
self.add_event_handler("session_start", self.start)
self.add_event_handler("changed_status", self.wait_for_presences)
self.received = set()
self.presences_received = threading.Event()
def start(self, event):
self.send_presence()
self.get_roster()
def is_recipient_online(self):
groups = self.client_roster.groups()
for group in groups:
for jid in groups[group]:
if jid != self.recipient_jid:
continue
connections = self.client_roster.presence(jid)
for res, pres in connections.items():
return True
return False
def wait_for_presences(self, pres):
"""
Track how many roster entries have received presence updates.
"""
self.received.add(pres['from'].bare)
if len(self.received) >= len(self.client_roster.keys()):
self.presences_received.set()
else:
self.presences_received.clear()
class Disconnector(object):
def __init__(self, xmpp, course):
Andreas Klöckner
committed
# type: (CourseXMPP, Course) -> None
self.timer = None
self.xmpp = xmpp
self.course = course
Andreas Klöckner
committed
self.timer = threading.Timer(60, self) # type: ignore
self.timer.start()
def __call__(self):
Andreas Klöckner
committed
# type: () -> None
# print "EXPIRING XMPP", self.course.pk
del _xmpp_connections[self.course.pk]
self.xmpp.disconnect(wait=True)
_disconnectors.remove(self)
def get_xmpp_connection(course):
try:
return _xmpp_connections[course.pk]
except KeyError:
xmpp = CourseXMPP(
course.course_xmpp_id,
course.course_xmpp_password,
course.recipient_xmpp_id)
if xmpp.connect():
xmpp.process()
else:
_xmpp_connections[course.pk] = xmpp
xmpp.presences_received.wait(5)
xmpp.is_recipient_online()
_disconnectors.append(Disconnector(xmpp, course))
return xmpp
@course_view
def send_instant_message(pctx):
Andreas Klöckner
committed
if not pctx.has_permission(pperm.send_instant_message):
raise PermissionDenied(_("may not batch-download submissions"))
request = pctx.request
course = pctx.course
if not course.course_xmpp_id:
messages.add_message(request, messages.ERROR,
_("Instant messaging is not enabled for this course."))
return redirect("relate-course_page", pctx.course_identifier)
xmpp = get_xmpp_connection(pctx.course)
form_text = _("Recipient is <span class='label label-success'>"
"Online</span>.")
form_text = _("Recipient is <span class='label label-danger'>"
"Offline</span>.")
form_text = "<div class='well'>%s</div>" % form_text
if request.method == "POST":
form = InstantMessageForm(request.POST, request.FILES)
if form.is_valid():
msg = InstantMessage()
msg.participation = pctx.participation
msg.text = form.cleaned_data["message"]
msg.save()
try:
if not course.recipient_xmpp_id:
raise RuntimeError(_("no recipient XMPP ID"))
if not course.course_xmpp_password:
xmpp.send_message(
mto=course.recipient_xmpp_id,
mbody=form.cleaned_data["message"],
mtype='chat')
except Exception:
from traceback import print_exc
print_exc()
messages.add_message(request, messages.ERROR,
_("An error occurred while sending the message. "
"Sorry."))
else:
messages.add_message(request, messages.SUCCESS,
form = InstantMessageForm()
else:
form = InstantMessageForm()
return render_course_page(pctx, "course/generic-course-form.html", {
"form": form,
"form_text": form_text,
})
# }}}
# vim: foldmethod=marker