Exemple #1
0
def add_message_to_channel(request, channel_name, message, myself=False):
    """
    Add message to specific channel.

    :Args:
      - request (:class:`django.http.HttpRequest`): Django Request
      - channel_name (`string`): Channel name
      - message (:class:`dict`): Sputnik message
      - myself (:class:`bool`): Should client also recieve that message.
    """

    import sputnik
    from booki.utils.log import print_stack

    try:
        clnts = sputnik.smembers("sputnik:channel:%s:channel" % channel_name)
    except:
        print_stack(None)
        return

    message["channel"] = channel_name
    message["clientID"] = request.clientID

    for c in clnts:
        if not myself and c == request.sputnikID:
            continue

        if c.strip() != '':
            try:
                sputnik.push("ses:%s:messages" % c, json.dumps(message))
            except:
                print_stack(None)
Exemple #2
0
def addMessageToChannel2(clientID,
                         sputnikID,
                         channelName,
                         message,
                         myself=False):
    import sputnik
    from booki.utils.log import print_stack

    try:
        clnts = sputnik.smembers("sputnik:channel:%s:channel" % channelName)
    except:
        print_stack(None)
        return

    message["channel"] = channelName
    message["clientID"] = clientID

    for c in clnts:
        if not myself and c == sputnikID:
            continue

        if c.strip() != '':
            try:
                sputnik.push("ses:%s:messages" % c, json.dumps(message))
            except:
                logger.debug('*ERROR PUSH*')
Exemple #3
0
def add_message_to_channel(request, channel_name, message, myself=False):
    """
    Add message to specific channel.

    :Args:
      - request (:class:`django.http.HttpRequest`): Django Request
      - channel_name (`string`): Channel name
      - message (:class:`dict`): Sputnik message
      - myself (:class:`bool`): Should client also recieve that message.
    """

    import sputnik
    from booki.utils.log import print_stack

    try:
        clnts = sputnik.smembers("sputnik:channel:%s:channel" % channel_name)
    except:
        print_stack(None)
        return

    message["channel"] = channel_name
    message["clientID"] = request.clientID

    for c in clnts:
        if not myself and c == request.sputnikID:
            continue

        if c.strip() != '':
            try:
                sputnik.push("ses:%s:messages" % c, serializeJson(message))
            except:
                print_stack(None)
Exemple #4
0
def addMessageToChannel2(clientID, sputnikID, channelName, message, myself=False):
    import sputnik
    from booki.utils.log import print_stack

    try:
        clnts = sputnik.smembers("sputnik:channel:%s:channel" % channelName)
    except:
        print_stack(None)
        return

    message["channel"] = channelName
    message["clientID"] = clientID

    for c in clnts:
        if not myself and c == sputnikID:
            continue

        if c.strip() != '':
            try:
                sputnik.push("ses:%s:messages" % c, serializeJson(message))
            except:
                logger.debug('*ERROR PUSH*')
Exemple #5
0
def addMessageToChannel(request, channelName, message, myself = False ):
    """
    Add message to specific channel.

    @type request: C{django.http.HttpRequest}
    @param request: Django Request.
    @type channelName: C{string}
    @param channelName: Channel name.
    @type message: C{dict}
    @param message: Sputnik message.
    @type myself: C{bool}
    @keyword myself: Should client also recieve that message.
    """

    import sputnik

    # TODO
    # not iterable
    try:
        clnts = sputnik.smembers("sputnik:channel:%s:channel" % channelName)
    except:
        from booki.utils.log import printStack
        printStack(None)
        return

    message["channel"] = channelName
    message["clientID"] = request.clientID

    for c in clnts:
        if not myself and c == request.sputnikID:
            continue

        if c.strip() != '':
            try:
                sputnik.push( "ses:%s:messages" % c, simplejson.dumps(message))
            except:
                pass
Exemple #6
0
def addMessageToChannel(request, channelName, message, myself=False):
    """
    Add message to specific channel.

    @type request: C{django.http.HttpRequest}
    @param request: Django Request.
    @type channelName: C{string}
    @param channelName: Channel name.
    @type message: C{dict}
    @param message: Sputnik message.
    @type myself: C{bool}
    @keyword myself: Should client also recieve that message.
    """

    import sputnik

    # TODO
    # not iterable
    try:
        clnts = sputnik.smembers("sputnik:channel:%s:channel" % channelName)
    except:
        from booki.utils.log import printStack
        printStack(None)
        return

    message["channel"] = channelName
    message["clientID"] = request.clientID

    for c in clnts:
        if not myself and c == request.sputnikID:
            continue

        if c.strip() != '':
            try:
                sputnik.push("ses:%s:messages" % c, simplejson.dumps(message))
            except:
                pass
Exemple #7
0
    def _delete_notifications(self):
        # TODO
        # this is just playground
        # we must create separate tool to push messages through the sputnik channel from API endpoints
        # without having clientID in request

        # message_info
        channel_name = "/chat/{}/".format(self._book.id)
        clnts = sputnik.smembers(
            "sputnik:channel:{}:channel".format(channel_name))
        message = {
            'channel': channel_name,
            "command": "message_info",
            "from": self.request.user.username,
            "email": self.request.user.email,
            "message_id": "user_delete_chapter",
            "message_args": [self.request.user.username, self._chapter.title]
        }

        for c in clnts:
            if c.strip() != '':
                sputnik.push("ses:%s:messages" % c, json.dumps(message))

        # chapter delete
        channel_name = "/booktype/book/{}/{}/".format(
            self._book.id, self._book.version.get_version())
        clnts = sputnik.smembers(
            "sputnik:channel:{}:channel".format(channel_name))
        message = {
            'channel': channel_name,
            "command": "chapter_delete",
            "chapterID": self._chapter.id
        }

        for c in clnts:
            if c.strip() != '':
                sputnik.push("ses:%s:messages" % c, json.dumps(message))

        # notificatoin message
        message = {
            'channel': channel_name,
            'command': 'notification',
            'message': 'notification_chapter_was_deleted',
            'username': self.request.user.username,
            'message_args': (self._chapter.title, )
        }

        for c in clnts:
            if c.strip() != '':
                sputnik.push("ses:%s:messages" % c, json.dumps(message))
Exemple #8
0
    def _delete_notifications(self):
        # TODO
        # this is just playground
        # we must create separate tool to push messages through the sputnik channel from API endpoints
        # without having clientID in request

        # message_info
        channel_name = "/chat/{}/".format(self._book.id)
        clnts = sputnik.smembers("sputnik:channel:{}:channel".format(channel_name))
        message = {
            'channel': channel_name,
            "command": "message_info",
            "from": self.request.user.username,
            "email": self.request.user.email,
            "message_id": "user_delete_chapter",
            "message_args": [self.request.user.username, self._chapter.title]
        }

        for c in clnts:
            if c.strip() != '':
                sputnik.push("ses:%s:messages" % c, json.dumps(message))

        # chapter delete
        channel_name = "/booktype/book/{}/{}/".format(self._book.id, self._book.version.get_version())
        clnts = sputnik.smembers("sputnik:channel:{}:channel".format(channel_name))
        message = {
            'channel': channel_name,
            "command": "chapter_delete",
            "chapterID": self._chapter.id
        }

        for c in clnts:
            if c.strip() != '':
                sputnik.push("ses:%s:messages" % c, json.dumps(message))

        # notificatoin message
        message = {
            'channel': channel_name,
            'command': 'notification',
            'message': 'notification_chapter_was_deleted',
            'username': self.request.user.username,
            'message_args': (self._chapter.title,)
        }

        for c in clnts:
            if c.strip() != '':
                sputnik.push("ses:%s:messages" % c, json.dumps(message))
Exemple #9
0
    def post(self, request, *args, **kwargs):
        # TODO test it and cover with tests
        book_security = BookSecurity(request.user, self._get_book())
        user = request.user
        can_upload_attachment = book_security.has_perm(
            'edit.upload_attachment')

        if not user.is_superuser and not can_upload_attachment and self._book.owner != user:
            raise PermissionDenied

        stat = BookStatus.objects.filter(book=self._book)[0]

        if 'file' not in request.FILES:
            raise ValidationError({'file': ['"file" is required.']})

        file_data = request.FILES['file']
        attname, attext = os.path.splitext(file_data.name)
        available_extensions = ('jpg', 'png', 'jpeg', 'gif')
        if attext.rsplit('.', 1)[-1].lower() not in available_extensions:
            raise ValidationError({
                'file': [
                    'Not supported extension. Available extensions: {}'.format(
                        ' '.join(available_extensions))
                ]
            })

        with transaction.atomic():
            att = Attachment(
                version=self._book.version,
                # must remove this reference
                created=datetime.datetime.now(),
                book=self._book,
                status=stat)
            att.save()

            att.attachment.save('{}{}'.format(booktype_slugify(attname),
                                              attext),
                                file_data,
                                save=False)
            att.save()

        # notificatoin message
        channel_name = "/booktype/book/{}/{}/".format(
            self._book.id, self._book.version.get_version())
        clnts = sputnik.smembers(
            "sputnik:channel:{}:channel".format(channel_name))

        message = {
            'channel': channel_name,
            'command': 'notification',
            'message': 'notification_new_attachment_uploaded',
            'username': self.request.user.username,
            'message_args': (att.get_name(), )
        }

        for c in clnts:
            if c.strip() != '':
                sputnik.push("ses:%s:messages" % c, json.dumps(message))

        # response
        serializer_instance = self.serializer_class(att)

        return Response(serializer_instance.data,
                        status=status.HTTP_201_CREATED)
Exemple #10
0
    def post(self, request, *args, **kwargs):
        # TODO test it and cover with tests
        book_security = BookSecurity(request.user, self._get_book())
        user = request.user
        can_upload_attachment = book_security.has_perm('edit.upload_attachment')

        if not user.is_superuser and not can_upload_attachment and self._book.owner != user:
            raise PermissionDenied

        stat = BookStatus.objects.filter(book=self._book)[0]

        if 'file' not in request.FILES:
            raise ValidationError({'file': ['"file" is required.']})

        file_data = request.FILES['file']
        attname, attext = os.path.splitext(file_data.name)
        available_extensions = ('jpg', 'png', 'jpeg', 'gif')
        if attext.rsplit('.', 1)[-1].lower() not in available_extensions:
            raise ValidationError({'file': [
                'Not supported extension. Available extensions: {}'.format(
                    ' '.join(available_extensions))
            ]})

        with transaction.atomic():
            att = Attachment(
                version=self._book.version,
                # must remove this reference
                created=datetime.datetime.now(),
                book=self._book,
                status=stat
            )
            att.save()

            att.attachment.save(
                '{}{}'.format(booktype_slugify(attname), attext),
                file_data,
                save=False
            )
            att.save()

        # notificatoin message
        channel_name = "/booktype/book/{}/{}/".format(self._book.id,
                                                      self._book.version.get_version())
        clnts = sputnik.smembers(
            "sputnik:channel:{}:channel".format(channel_name))

        message = {
            'channel': channel_name,
            'command': 'notification',
            'message': 'notification_new_attachment_uploaded',
            'username': self.request.user.username,
            'message_args': (att.get_name(),)
        }

        for c in clnts:
            if c.strip() != '':
                sputnik.push("ses:%s:messages" % c, json.dumps(message))

        # response
        serializer_instance = self.serializer_class(att)

        return Response(serializer_instance.data, status=status.HTTP_201_CREATED)
Exemple #11
0
    def create(self, validated_data):
        chapter = super(ChapterListCreateSerializer, self).create(validated_data)

        # create toc
        book = self.context['view']._book
        book_version = self.context['view']._book.version
        weight = len(book_version.get_toc()) + 1

        for itm in BookToc.objects.filter(version=book_version, book=book).order_by("-weight"):
            itm.weight = weight
            itm.save()
            weight -= 1

        toc_item = BookToc(
            version=book_version, book=book, name=chapter.title, chapter=chapter, weight=1, typeof=1
        )
        toc_item.save()

        # create chapter history
        history = logChapterHistory(
            chapter=chapter,
            content=chapter.content,
            user=self.context['request'].user,
            comment="created via api",
            revision=chapter.revision
        )

        # create book history
        if history:
            logBookHistory(
                book=book,
                version=book_version,
                chapter=chapter,
                chapter_history=history,
                user=self.context['request'].user,
                kind='chapter_create'
            )

        # TODO
        # this is just playground
        # we must create separate tool to push messages through the sputnik channel from API endpoints
        # without having clientID in request

        # message_info
        channel_name = "/chat/{}/".format(book.id)
        clnts = sputnik.smembers("sputnik:channel:{}:channel".format(channel_name))
        message = {
            'channel': channel_name,
            "command": "message_info",
            "from": self.context['request'].user.username,
            "email": self.context['request'].user.email,
            "message_id": "user_new_chapter",
            "message_args": [self.context['request'].user.username, chapter.title]
        }

        for c in clnts:
            if c.strip() != '':
                sputnik.push("ses:%s:messages" % c, json.dumps(message))

        # chapter_create
        channel_name = "/booktype/book/{}/{}/".format(book.id, book_version.get_version())
        clnts = sputnik.smembers("sputnik:channel:{}:channel".format(channel_name))
        message = {
            'channel': channel_name,
            "command": "chapter_create",
            "chapter": (chapter.id, chapter.title, chapter.url_title, 1, chapter.status.id,
                        chapter.lock_type, chapter.lock_username, "root", toc_item.id, "normal", None)
        }

        for c in clnts:
            if c.strip() != '':
                sputnik.push("ses:%s:messages" % c, json.dumps(message))

        # notificatoin message
        message = {
            'channel': channel_name,
            'command': 'notification',
            'message': 'notification_chapter_was_created',
            'username': self.context['request'].user.username,
            'message_args': (chapter.title,)
        }

        for c in clnts:
            if c.strip() != '':
                sputnik.push("ses:%s:messages" % c, json.dumps(message))

        return chapter