diff src/plugins/plugin_misc_tarot.py @ 320:5fc5e6a7e5c3

plugin Tarot: added a launch method to automatically create a new room, invite players and create the game - xep-0249 (direct MUC invitation) is used with a custom attribute to invite other users - bridge: added tarotGameLaunch in frontend side
author Goffi <goffi@goffi.org>
date Fri, 06 May 2011 15:42:26 +0200
parents 7c79d4a8c9e6
children 809733b8d9be
line wrap: on
line diff
--- a/src/plugins/plugin_misc_tarot.py	Fri May 06 15:38:32 2011 +0200
+++ b/src/plugins/plugin_misc_tarot.py	Fri May 06 15:42:26 2011 +0200
@@ -25,8 +25,6 @@
 from twisted.words.protocols.jabber import client, jid, xmlstream
 from twisted.words.protocols.jabber import error as jab_error
 from twisted.words.protocols.jabber.xmlstream import IQ
-import os.path
-import pdb
 import random
 
 from zope.interface import implements
@@ -35,6 +33,8 @@
 from sat.tools.xml_tools import dataForm2xml
 from sat.tools.games import TarotCard
 
+from time import time
+
 try:
     from twisted.words.protocols.xmlstream import XMPPHandler
 except ImportError:
@@ -50,7 +50,7 @@
 "import_name": "Tarot",
 "type": "Misc",
 "protocols": [],
-"dependencies": ["XEP-0045"],
+"dependencies": ["XEP-0045", "XEP-0249"],
 "main": "Tarot",
 "handler": "yes",
 "description": _("""Implementation of Tarot card game""")
@@ -63,7 +63,9 @@
         info(_("Plugin Tarot initialization"))
         self.host = host
         self.games={}
+        self.waiting_inv = {} #Invitation waiting for people to join to launch a game
         self.contrats = [_('Passe'), _('Petite'), _('Garde'), _('Garde Sans'), _('Garde Contre')]
+        host.bridge.addMethod("tarotGameLaunch", ".communication", in_sign='ass', out_sign='', method=self.launchGame) #args: room_jid, players, profile
         host.bridge.addMethod("tarotGameCreate", ".communication", in_sign='sass', out_sign='', method=self.createGame) #args: room_jid, players, profile
         host.bridge.addMethod("tarotGameReady", ".communication", in_sign='sss', out_sign='', method=self.newPlayerReady) #args: player, referee, profile
         host.bridge.addMethod("tarotGameContratChoosed", ".communication", in_sign='ssss', out_sign='', method=self.contratChoosed) #args: player, referee, contrat, profile
@@ -76,6 +78,7 @@
         host.bridge.addSignal("tarotGameYourTurn", ".communication", signature='ss') #args: room_jid, profile
         host.bridge.addSignal("tarotGameScore", ".communication", signature='ssasass') #args: room_jid, xml_data, winners (list of nicks), loosers (list of nicks), profile
         host.bridge.addSignal("tarotGameInvalidCards", ".communication", signature='ssa(ss)a(ss)s') #args: room_jid, game phase, played_cards, invalid_cards, profile
+        host.trigger.add("MUC user joined", self.userJoinedTrigger)
         self.deck_ordered = []
         for value in ['excuse']+map(str,range(1,22)):
             self.deck_ordered.append(TarotCard(("atout",value)))
@@ -206,7 +209,7 @@
         players_data = game_data['players_data']
         excuse = TarotCard(("atout","excuse"))
 
-        #we first check if the Excuse was already player
+        #we first check if the Excuse was already played
         #and if somebody is waiting for a card
         for player in game_data['players']:
             if players_data[player]['wait_for_low']:
@@ -397,8 +400,67 @@
         self.host.profiles[profile].xmlstream.send(mess)
 
 
+    def userJoinedTrigger(self, room, user, profile):
+        """This trigger is used to check if we are waiting people in this room,
+        and to create a game if everybody is here"""
+        _room_jid = room.occupantJID.userhostJID()
+        if _room_jid in self.waiting_inv and len(room.roster) == 4:
+            #When we have 4 people in the room, we create the game
+            #TODO: check people identity
+            players = room.roster.keys()
+            del self.waiting_inv[_room_jid]
+            self.createGame(_room_jid.userhost(), players, profile_key=profile)
+        return True
+
+    def launchGame(self, players, profile_key='@DEFAULT@'):
+        """Launch a game: helper method to create a room, invite players, and create the tarot game
+        @param players: list for players jid"""
+        debug(_('Launching tarot game'))
+        profile = self.host.memory.getProfileName(profile_key)
+        if not profile:
+            error(_("Unknown profile"))
+            return
+
+        def tarotRoomJoined(room):
+            _room = room.occupantJID.userhostJID()
+            for player in players:
+                self.host.plugins["XEP-0249"].invite(jid.JID(player), room.occupantJID.userhostJID(), {"game":"Tarot"}, profile)
+            self.waiting_inv[_room] = (time(), players) #TODO: remove invitation waiting for too long, using the time data
+        
+        def after_init(ignore):
+            room_name = "sat_tarot_%s" % self.host.plugins["XEP-0045"].getUniqueName(profile_key)
+            print "\n\n===> room_name:", room_name
+            #muc_service = self.host.memory.getServerServiceEntity("conference", "text", profile)
+            muc_service = None
+            for service in self.host.memory.getServerServiceEntities("conference", "text", profile):
+                if not ".irc." in service.userhost():
+                    #FIXME: 
+                    #This awfull ugly hack is here to avoid an issue with openfire: the irc gateway
+                    #use "conference/text" identity (instead of "conference/irc"), there is certainly a better way
+                    #to manage this, but this hack fill do it for test purpose
+                    muc_service = service
+                    break
+            if not muc_service:
+                error(_("Can't find a MUC service"))
+                return
+            
+            _jid, xmlstream = self.host.getJidNStream(profile)
+            d = self.host.plugins["XEP-0045"].join(muc_service.userhost(), room_name, _jid.user, profile).addCallback(tarotRoomJoined)
+
+        client = self.host.getClient(profile)
+        if not client:
+            error(_('No client for this profile key: %s') % profile_key)
+            return
+        client.client_initialized.addCallback(after_init)
+
+
+
+
     def createGame(self, room_jid_param, players, profile_key='@DEFAULT@'):
-        """Create a new game"""
+        """Create a new game
+        @param room_jid_param: jid of the room
+        @param players: list of players nick (nick must exist in the room)
+        @param profile_key: %(doc_profile_key)s"""
         debug (_("Creating Tarot game"))
         room_jid = jid.JID(room_jid_param)
         profile = self.host.memory.getProfileName(profile_key)