<commit_before># -*- coding: utf-8 -*-
import sys, time

import simplejson
import random
import openerpweb

#----------------------------------------------------------
# OpenERP Web ajaxim Controllers
#----------------------------------------------------------
class PollServerMessageQueue(object):
    def __init__(self):
        # message queue
        self.messages = []
        # online users
        self.users = {}
        # should contains: {
        #   'user1234' : { s:1, m:"status message", timestamp: last_contact_timestamp }
        # }
    def userlist(self, req):
        userlist = [users for users in req.applicationsession['users']]
        
#        userlist = [
#                    {"u": "Guest130205108745.47", "s": {"s": 1, "m": ""}, "g": "Users"},
#                    {"u": "Guest130209838956.76", "s": {"s": 1, "m": ""}, "g": "Users"},
#                ]

        return userlist

    def write(self, m_type,  m_from, m_to, m_message, m_group):
        self.messages.append({'type': m_type, 'from': m_from, 'to': m_to, 'message': m_message, 'group': m_group})
        # when status message update users
        pass
    
    def read(self, recipient, timestamp):
        for msg in self.messages:
            if msg['to'] == recipient:
                return self.messages
            
    def gc():
        # remove message older than 300s from self.l
        # remove dead users from self.users
        pass

class PollServer(openerpweb.Controller):
    _cp_path = "/web_chat/pollserver"

    @openerpweb.httprequest
    def login(self, req, **kw):
                
        """
        --> POST http://ajaxim.com/wp-content/plugins/im/ajaxim.php/login
            Form Data
                username:""
                password:"<PASSWORD>"
        <-- 200 OK
            Content-Type:text/html

            {
                "r":"logged in",
                "u":"Guest130213866190.85",
                "s":"f9e1811536f19ad5b9e00376f9ff1532",
                "f":[
                    {"u":"Guest130205108745.47","s":{"s":1,"m":""},"g":"Users"},
                    {"u":"Guest130209838956.76","s":{"s":1,"m":""},"g":"Users"},
                ]
            }
        """
        mq = req.applicationsession.setdefault("web_chat", PollServerMessageQueue())
        
        #r = 'logged in'
        #u = generate random.randint(0,2**32)
        #s = cherrypy cookie id
        #f = mq.userlist()
        
#        username = 'Guest'+ str(random.randint(0, 2**32))
#        
#        if not req.applicationsession.get('users'):
#            req.applicationsession['users'] = [{'u': username, 's':{'s':1, 'm':''}, 'g':'Users'}]
#        else:
#            req.applicationsession['users'].append({'u': username, 's':{'s':1, 'm':''}, 'g':'Users'})
        req.applicationsession['users'] = [{'u': 'Guest1', 's':{'s':1, 'm':'111'}, 'g':'Users'},
                                           {'u': 'Guest2', 's':{'s':1, 'm':'222'}, 'g':'Users'},
                                           {'u': 'Guest3', 's':{'s':1, 'm':'333'}, 'g':'Users'}]
        
        # Temporary Guest1 is my current user
        req.applicationsession['current_user'] = 'Guest1'
        
        return """
            {
                "r":"logged in",
                "u":'Guest1',
                "s":"f9e1811536f19ad5b9e00376f9ff1532",
                "f":""" + str(mq.userlist(req)) + """
            }
        """

    @openerpweb.httprequest
    def logout(self, req):
        """
        --> GET http://im.ajaxim.com/logout
            { "r":"logged out" }
        """

    @openerpweb.httprequest
    def poll(self, req, **kw):
        
        mq = req.applicationsession.setdefault("web_chat", PollServerMessageQueue())
        print "================ poll ======= ", kw
        # Long Polling
        method = kw.get('method')
        """
        --> GET http://im.ajaxim.com/poll?callback=jsonp1302138663582&_1302138663582=
        <-- 200 OK
            Content-Type:text/html

            noop:
            jsonp1302138663582([]);

            roster user online:
            jsonp1302140366243([{"t":"s","s":"Guest130214038974.31","r":"all","m":"1:","g":"Users"}]);

            roster user left:
            jsonp1302140441577([{"t":"s","s":"Guest130214038974.31","r":"","m":"0:"}]);

            receive message:
            jsonp1302140191599([{"t":"m","s":"Guest130214008855.5","r":"Guest130214013134.26","m":"xxxxxx"}]);

            ('t' => $msg->type, 's' => $msg->from, 'r' => $msg->to, 'm' => $msg->message )
            mag type s or m
            echo '<script type="text/javascript">parent.AjaxIM.incoming('. json_encode($this->_pollParseMessages($messages)) .  ');</script>'

        """
        
        for i in range(60):
            received_msg = mq.read('Guest1', i);
            if received_msg:
                msg = self._pollParseMessages(received_msg)
                time.sleep(2)
            else:
                time.sleep(2)
            
        # for i in range(60):
            #r = mq.read(username,timestamp)
            # if messages
                # return r
            # if no message sleep 2s and retry
                # sleep 2
        # else
            # return emptylist
            
#        print "==============poll receive...", kw.get('callback')
#        # it's http://localhost:8002/web_chat/pollserver/poll?method=long?callback=jsonp1302147330483&_1302147330483=
        return '%s([{"t":"m","s":"Guest130214008855.5","r":"Guest130214013134.26","m":"xxxxxx"}]);'%kw.get('callback','')
        
    @openerpweb.jsonrequest
    def send(self, req, **kw):
        print "========= send ========", kw
        
        to = kw.get('to')
        message = kw.get('message')
        
        mq = req.applicationsession.setdefault("web_chat", PollServerMessageQueue())
        
        """
        --> GET http://im.ajaxim.com/send?callback=jsonp1302139980022&to=Guest130205108745.47&message=test&_1302139980022=
            callback: jsonp1302139980022
            to: Guest130205108745.47
            message: test
            _1302139980022:
<commit_msg>[FIX] Fixed dynamic return for poll method.<commit_after># -*- coding: utf-8 -*-
import sys, time

import simplejson
import random
import openerpweb

#----------------------------------------------------------
# OpenERP Web ajaxim Controllers
#----------------------------------------------------------
class PollServerMessageQueue(object):
    def __init__(self):
        # message queue
        self.messages = []
        # online users
        self.users = {}
        # should contains: {
        #   'user1234' : { s:1, m:"status message", timestamp: last_contact_timestamp }
        # }
    def userlist(self, req):
        userlist = [users for users in req.applicationsession['users']]
        
#        userlist = [
#                    {"u": "Guest130205108745.47", "s": {"s": 1, "m": ""}, "g": "Users"},
#                    {"u": "Guest130209838956.76", "s": {"s": 1, "m": ""}, "g": "Users"},
#                ]

        return userlist

    def write(self, m_type,  m_from, m_to, m_message, m_group):
        self.messages.append({'type': m_type, 'from': m_from, 'to': m_to, 'message': m_message, 'group': m_group})
        # when status message update users
        pass
    
    def read(self, recipient, timestamp):
        for msg in self.messages:
            if msg['to'] == recipient:
                return self.messages
            
    def gc():
        # remove message older than 300s from self.l
        # remove dead users from self.users
        pass

class PollServer(openerpweb.Controller):
    _cp_path = "/web_chat/pollserver"

    @openerpweb.httprequest
    def login(self, req, **kw):
                
        """
        --> POST http://ajaxim.com/wp-content/plugins/im/ajaxim.php/login
            Form Data
                username:""
                password:"<PASSWORD>"
        <-- 200 OK
            Content-Type:text/html

            {
                "r":"logged in",
                "u":"Guest130213866190.85",
                "s":"f9e1811536f19ad5b9e00376f9ff1532",
                "f":[
                    {"u":"Guest130205108745.47","s":{"s":1,"m":""},"g":"Users"},
                    {"u":"Guest130209838956.76","s":{"s":1,"m":""},"g":"Users"},
                ]
            }
        """
        mq = req.applicationsession.setdefault("web_chat", PollServerMessageQueue())
        
        #r = 'logged in'
        #u = generate random.randint(0,2**32)
        #s = cherrypy cookie id
        #f = mq.userlist()
        
#        username = 'Guest'+ str(random.randint(0, 2**32))
#        
#        if not req.applicationsession.get('users'):
#            req.applicationsession['users'] = [{'u': username, 's':{'s':1, 'm':''}, 'g':'Users'}]
#        else:
#            req.applicationsession['users'].append({'u': username, 's':{'s':1, 'm':''}, 'g':'Users'})
        req.applicationsession['users'] = [{'u': 'Guest1', 's':{'s':1, 'm':'111'}, 'g':'Users'},
                                           {'u': 'Guest2', 's':{'s':1, 'm':'222'}, 'g':'Users'},
                                           {'u': 'Guest3', 's':{'s':1, 'm':'333'}, 'g':'Users'}]
        
        # Temporary Guest1 is my current user
        req.applicationsession['current_user'] = 'Guest1'
        
        return """
            {
                "r":"logged in",
                "u":'Guest1',
                "s":"f9e1811536f19ad5b9e00376f9ff1532",
                "f":""" + str(mq.userlist(req)) + """
            }
        """

    @openerpweb.httprequest
    def logout(self, req):
        """
        --> GET http://im.ajaxim.com/logout
            { "r":"logged out" }
        """

    @openerpweb.httprequest
    def poll(self, req, **kw):
        
        mq = req.applicationsession.setdefault("web_chat", PollServerMessageQueue())
        print "================ poll ======= ", kw
        # Long Polling
        method = kw.get('method')
        """
        --> GET http://im.ajaxim.com/poll?callback=jsonp1302138663582&_1302138663582=
        <-- 200 OK
            Content-Type:text/html

            noop:
            jsonp1302138663582([]);

            roster user online:
            jsonp1302140366243([{"t":"s","s":"Guest130214038974.31","r":"all","m":"1:","g":"Users"}]);

            roster user left:
            jsonp1302140441577([{"t":"s","s":"Guest130214038974.31","r":"","m":"0:"}]);

            receive message:
            jsonp1302140191599([{"t":"m","s":"Guest130214008855.5","r":"Guest130214013134.26","m":"xxxxxx"}]);

            ('t' => $msg->type, 's' => $msg->from, 'r' => $msg->to, 'm' => $msg->message )
            mag type s or m
            echo '<script type="text/javascript">parent.AjaxIM.incoming('. json_encode($this->_pollParseMessages($messages)) .  ');</script>'

        """
        
        msg = []
        
        for i in range(5):
            received_msg = mq.read('Guest1', i);
            if received_msg:
                msg = self._pollParseMessages(received_msg)
                time.sleep(1)
            else:
                msg = []
                time.sleep(1)
            
        # for i in range(60):
            #r = mq.read(username,timestamp)
            # if messages
                # return r
            # if no message sleep 2s and retry
                # sleep 2
        # else
            # return emptylist

        msg = '[{"t":"m","s":"Guest130214008855.5","r":"Guest130214013134.26","m":"xxxxxx"}]'

#        # it's http://localhost:8002/web_chat/pollserver/poll?method=long?callback=jsonp1302147330483&_1302147330483=
        
        return '%s'%kw.get('callback', '') + '(' + msg + ');'
        
    @openerpweb.httprequest
    def send(self, req, **kw):
        print "========= send ========", kw
        
        to = kw.get('to')
        message = kw.get('message')
        
        mq = req.applicationsession.setdefault("web_chat", PollServerMessageQueue())
        
        """
        --> GET http://im.ajaxim.com/send?callback=jsonp1302139980022&to=Guest130205108745.47&message=test&_1302139980022=
            callback: jsonp1302139980022
            to: Guest130205108745.47
            message: test
            _1302139980022:

{'fraction_non_alphanumeric': 0.19279367408494336, 'fraction_numerical': 0.07198173962664058, 'mean_word_length': 1.7463622117752406, 'pattern_counts': {'":': 92, '<': 13, '<?xml version=': 0, '>': 35, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3379804', 'n_tokens_mistral': 4373, 'n_tokens_neox': 3735, 'n_words': 667}