view src/plugins/plugin_misc_groupblog.py @ 462:d9456d94cd12

plugin groupblog: next-gen group blog first draft
author Goffi <goffi@goffi.org>
date Wed, 14 Mar 2012 23:45:01 +0100
parents cf005701624b
children 78e67a59d51d
line wrap: on
line source

#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
SAT plugin for microbloging with roster access
Copyright (C) 2009, 2010, 2011, 2012  Jérôme Poisson (goffi@goffi.org)

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""

from logging import debug, info, error
from twisted.internet import protocol, defer
from twisted.words.protocols.jabber import jid
from twisted.words.protocols.jabber import error as jab_error
import twisted.internet.error
from twisted.words.xish import domish
from sat.tools.xml_tools import ElementParser

from wokkel import disco, pubsub, data_form
from feed.atom import Entry, Author
import uuid
from time import time

NS_PUBSUB = 'http://jabber.org/protocol/pubsub'
#NS_PUBSUB_EXP = 'http://goffi.org/protocol/pubsub' #for non official features
NS_PUBSUB_EXP = NS_PUBSUB #XXX: we can't use custom namespace as Wokkel's PubSubService use official NS
NS_PUBSUB_ITEM_ACCESS = NS_PUBSUB_EXP + "#item-access"
NS_PUBSUB_CREATOR_JID_CHECK = NS_PUBSUB_EXP + "#creator-jid-check"
NS_PUBSUB_ITEM_CONFIG = NS_PUBSUB_EXP + "#item-config"
NS_PUBSUB_AUTO_CREATE = NS_PUBSUB + "#auto-create"
OPT_ROSTER_GROUPS_ALLOWED = 'pubsub#roster_groups_allowed'
OPT_ACCESS_MODEL = 'pubsub#access_model'
OPT_PERSIST_ITEMS = 'pubsub#persist_items'
OPT_MAX_ITEMS = 'pubsub#max_items'
OPT_NODE_TYPE = 'pubsub#node_type'
OPT_SUBSCRIPTION_TYPE = 'pubsub#subscription_type'
OPT_SUBSCRIPTION_DEPTH = 'pubsub#subscription_depth'
TYPE_COLLECTION = 'collection'

PLUGIN_INFO = {
"name": "Group blogging throught collections",
"import_name": "groupblog",
"type": "MISC",
"protocols": [],
"dependencies": ["XEP-0277"],
"main": "GroupBlog",
"handler": "no",
"description": _("""Implementation of microblogging with roster access""")
}

class NodeCreationError(Exception):
    pass

class NodeDeletionError(Exception):
    pass

class GroupBlog():
    """This class use a SàT PubSub Service to manage access on microblog"""

    def __init__(self, host):
        info(_("Group blog plugin initialization"))
        self.host = host

        host.bridge.addMethod("sendGroupBlog", ".plugin", in_sign='asss', out_sign='',
                               method=self.sendGroupBlog,
                               doc = { 'summary':"Send a microblog to a list of groups",
                                       'param_0':'list of groups which can read the microblog',
                                       'param_1':'text to send',
                                       'param_2':'%(doc_profile)s'
                                     })
        
    def _publishMblog(self, service, groups, message, client):
        """Actually publish the message on the group blog
        @param service: jid of the item-access pubsub service
        @param groups: set of groups allowed to see the item
        @param message: message to publish
        @param client: SatXMPPClient of the published"""
        mblog_item = self.host.plugins["XEP-0277"].data2entry({'content':message}, client.profile)
        form = data_form.Form('submit', formNamespace=NS_PUBSUB_ITEM_CONFIG)
        field = data_form.Field('list-multi', OPT_ROSTER_GROUPS_ALLOWED, values=groups)
        form.addField(field)
        mblog_item.addChild(form.toElement())
        defer_blog = self.host.plugins["XEP-0060"].publish(service, client.jid.userhost(), items=[mblog_item], profile_key=client.profile)
        defer_blog.addErrback(self._mblogPublicationFailed)

    def _mblogPublicationFailed(self, failure):
        #TODO
        pass

    @defer.inlineCallbacks
    def sendGroupBlog(self, groups, message, profile_key='@DEFAULT@'):
        """Publish a microblog to the node associated to the groups
        If the node doesn't exist, it is created, then the message is posted
        @param groups: list of groups allowed to retrieve the microblog
        @param message: microblog
        @profile_key: %(doc_profile)s
        """
        print "sendGroupBlog"
        profile = self.host.memory.getProfileName(profile_key)
        if not profile:
            error(_("Unknown profile"))
            return
        
        client = self.host.getClient(profile)
        if not client:
            error(_('No client for this profile key: %s') % profile_key)
            return
        
        yield client.client_initialized #we want to be sure that the client is initialized
        
        #we first check that we have a item-access pubsub server
        if not hasattr(client,"item_access_pubsub"):
            debug(_('Looking for item-access power pubsub server'))
            #we don't have any pubsub server featuring item access yet
            test = self.host.memory.getServerServiceEntities("pubsub", "service", profile)
            client.item_access_pubsub = None
            for entity in self.host.memory.getServerServiceEntities("pubsub", "service", profile):
                disco = yield client.disco.requestInfo(entity)
                if set([NS_PUBSUB_ITEM_ACCESS, NS_PUBSUB_AUTO_CREATE, NS_PUBSUB_CREATOR_JID_CHECK]).issubset(disco.features):
                    info(_("item-access powered pubsub service found: [%s]") % entity.full())
                    client.item_access_pubsub = entity

        if not client.item_access_pubsub:
            error(_("No item-access powered pubsub server found, can't post group blog"))
            return

        _groups = set(groups).intersection(client.roster.getGroups()) #We only keep group which actually exist
        #TODO: send an error signal if user want to post to non existant groups
        
        self._publishMblog(client.item_access_pubsub, _groups, message, client)