Ejemplo n.º 1
0
def save_message(request):
    '''
    Function save message owner in DB,

    Check message out on stop words and replace them.

    Add owner to opponent's contact list.

    If the message is first send notification to tpa side.

    parameters by POST: app_name,owner_id,room_id,message

    [server]/api/save_message

    Example: http://chat.localhost/api/save_message
    '''
    #import pdb; pdb.set_trace()
    b = json.loads(request.body)

    b['message'] = stop_words(b['message'])

    if(check_message(b['message']) == False):
        message = 'This message contains prohibited information!'
    else:
        message = b['message']         
    tpa = Tpa.objects.get(name=b['app_name'])
    owner = ChatUser.objects.get(tpa=tpa,user_id=int(b['owner_id']))
    
    if (owner.gender=='m'):
        balance = get_user_balance(tpa,owner)
        print balance
        if balance < 3:
            return  { 'status': 1, 'message': 'Your account is emply. Please replanish your account.' }
    room = ChatRoom.objects.get(tpa=tpa,id=int(b['room_id']))
    cm = ChatMessage()
    cm.tpa = tpa
    cm.user = owner
    cm.room = room
    cm.message = message
    gender = owner.gender
    cm.save()
    charge_for_chat(cm,room,tpa) #charging
    try:
        arr_participants = []
        for p in b['participants']:
            arr_participants.append(p.split('_')[1])
            mes = { 'action': 'show_message', 'room_id': b['room_id'], 
                    'message': {'id': cm.id, 
                                'created': str(cm.created.time().strftime('%H:%M:%S')),
                                'message':cm.message,
                                'room_id':cm.room_id,
                                'owner': serialize_user(owner)            
                                }
                  }
           
            bclient.publish(p, json.dumps(mes))
            opponent = ChatUser.objects.get(user_id=p.split('_')[1])
            #import pdb; pdb.set_trace()
            if owner != opponent:
                # adding contact
                add_me_to_contact_if_not_exist(tpa,owner,opponent,p)
                contact = _add_contact(tpa.name,owner.user_id,opponent.user_id)
                mes_contact = { 'action': 'update_contact' }
                mes_online = { 'action': 'update_users_online' }
                owner_chanel = '%s_%s' % (b['app_name'], owner.user_id)
                bclient.publish(owner_chanel, json.dumps(mes_contact))
                bclient.publish(owner_chanel, json.dumps(mes_online))
                if room.get_count_messages()<2999:
                    data = {'message': cm.message, 'id': cm.id, 'opponent': serialize_user(owner)}
                    mes = { 'action': 'show_new_message_notification', 'data': data }
                    bclient.publish('%s_%s' % (tpa.name, opponent.user_id), json.dumps(mes))
    except Exception, e:
        print e
Ejemplo n.º 2
0
def save_message(request):
    '''
    Function save message owner in DB,

    Check if user is available.

    Check message out on stop words and replace them.

    Add owner to opponent's contact list.

    If the message is first send notification to tpa side.

    parameters by POST: app_name,owner_id,room_id,message

    [server]/api/save_message

    Example: http://chat.localhost/api/save_message
    '''
    #import pdb; pdb.set_trace()
    b = json.loads(request.body)
    #time.sleep(2)

    b['message'] = stop_words(b['message'])

    if(check_message(b['message']) == False):
        message = 'This message contains prohibited information!'
    else:
        message = b['message']         
    tpa = Tpa.objects.get(name=b['app_name'])
    owner = ChatUser.objects.get(tpa=tpa,user_id=int(b['owner_id']))
    
    if (owner.gender=='m'):
        balance = get_user_balance(tpa,owner)
        if balance < 3:
            return  { 'status': 1, 'message': 'Your account is emply. Please replanish your account.' }  
        owner.activity = time.time()
        owner.save()

    room = ChatRoom.objects.get(tpa=tpa,id=int(b['room_id']))
    
    # Set servers locale to Kiev time to save same date of message for girl and man
    import pytz, datetime
    local = pytz.utc
    naive = datetime.datetime.strptime (time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()), "%Y-%m-%d %H:%M:%S")
    local_dt = local.localize(naive, is_dst=None)
    utc_dt = local_dt.astimezone (pytz.timezone ("Europe/Kiev"))
    
    cm = ChatMessage()
    cm.tpa = tpa
    cm.user = owner
    cm.room = room
    cm.message = message
    cm.created = utc_dt
    gender = owner.gender
    cm.save()
    charge_for_chat(cm,room,tpa) #charging
    
    #try:
    arr_participants = []
    for p in b['participants']:
        arr_participants.append(p.split('_')[1])
        mes = { 'action': 'show_message', 'room_id': b['room_id'], 
                'message': {'id': cm.id, 
                            'created': str(cm.created.time().strftime('%H:%M:%S')),
                            'message':cm.message,
                            'room_id':cm.room_id,
                            'owner': serialize_user(owner),  
                            'participants': b['participants']          
                            }
              }
        print 'send to %s' % p
	opponent = ChatUser.objects.get(user_id=p.split('_')[1])
        if owner != opponent:
            bclient.publish(p, json.dumps(mes))        
        
        #import pdb; pdb.set_trace()
        
        if owner != opponent:
	    
            # check accessebilities
            #import pdb; pdb.set_trace()
            check_avalible_url = get_url_by_name('check_accessebility',{'user_id': opponent.user_id, 'app_name': b['app_name']})
            print 'REQUEST_____%s' % check_avalible_url
            res = json.loads(requests.get(check_avalible_url).content)
            if(res['status']==1):
                print 'noooooo'
                mes = { 'action': 'say_busy', 'message': 'Sorry but I am busy now.', 'user_profile':  serialize_user(opponent)}
                owner_chanel = '%s_%s' % (b['app_name'], owner.user_id)
                bclient.publish(owner_chanel, json.dumps(mes))
            # adding contact 
            is_sent = False
            if opponent.gender == 'w':
                add_me_to_contact_if_not_exist(tpa,owner,opponent,p)
            #if it man just show multiinvite popup
            else:
                
                try:
                    cont = ChatContacts.objects.get(tpa=tpa,owner=opponent,contact=owner)
                except:
                    data = {'message': cm.message, 'opponent': serialize_user(owner), 'id': str(owner.user_id) }
                    mes = { 'action': 'show_multi_invite_notification', 'data': data }
                    bclient.publish('%s_%s' % (b['app_name'], opponent.user_id), json.dumps(mes))
                    is_sent = True                     
            contact = _add_contact(tpa.name,owner.user_id,opponent.user_id)
            mark_new_message(owner,opponent)
            if(opponent.is_online):
                mes_contact = { 'action': 'add_opponent_in_my_contact_list', 'user_id': opponent.user_id, 'profile': serialize_user(opponent) }
                mes_online = { 'action': 'update_users_online' }
                owner_chanel = '%s_%s' % (b['app_name'], owner.user_id)
                opponent_chanel = '%s_%s' % (b['app_name'], opponent.user_id)
                bclient.publish(owner_chanel, json.dumps(mes_contact))
                bclient.publish(owner_chanel, json.dumps(mes_online))
                if is_sent == False:
                    data = {'message': cm.message, 'id': cm.id, 'opponent': serialize_user(owner)}
                    mes = { 'action': 'show_new_message_notification', 'data': data }
                    bclient.publish('%s_%s' % (tpa.name, opponent.user_id), json.dumps(mes))
            # send commant to add this opponent to list of the active opponent in js
            mess_ac = { 'action': 'contact_activate', 'user_id': owner.user_id, 'profile': serialize_user(owner) }
            bclient.publish(opponent_chanel, json.dumps(mess_ac))
            
    #except Exception, e:
    #    print e
    
    

    return  { 'status': 0, 'message': b['message'], 'room_id': str(room.id), 'owner_id': str(owner.id), 'participants': arr_participants }