コード例 #1
0
ファイル: leave.py プロジェクト: andrewrk/solidcomposer
    def execute(self):
        expire_date = datetime.now() - timedelta(seconds=settings.CHAT_TIMEOUT)
        appearances = Appearance.objects.filter(timestamp__lte=expire_date)

        for appearance in appearances:
            # generate leave messages in each room
            m = ChatMessage()
            m.room = appearance.room
            m.type = ChatMessage.LEAVE
            m.author = appearance.person
            m.save()

        appearances.delete()
コード例 #2
0
ファイル: leave.py プロジェクト: andrewrk/solidcomposer
    def execute(self):
        expire_date = datetime.now() - timedelta(seconds=settings.CHAT_TIMEOUT)
        appearances = Appearance.objects.filter(timestamp__lte=expire_date)
        
        for appearance in appearances:
            # generate leave messages in each room
            m = ChatMessage()
            m.room=appearance.room
            m.type=ChatMessage.LEAVE
            m.author=appearance.person
            m.save()

        appearances.delete()
コード例 #3
0
ファイル: views.py プロジェクト: andrewrk/solidcomposer
def ajax_say(request):
    room = get_obj_from_request(request.POST, 'room', ChatRoom)
    if room is None:
        return json_failure(design.bad_room_id)

    data = {
        'user': {
            'is_authenticated': request.user.is_authenticated(),
            'permission_read': room.permission_to_hear(request.user),
            'permission_write': room.permission_to_chat(request.user),
        },
        'success': False,
    }

    if not room.is_active():
        return json_failure(design.room_is_not_active)

    message = request.POST.get('message', '')

    if message == "":
        return json_failure(design.cannot_say_blank_message)

    if len(message) > ChatMessage._meta.get_field('message').max_length: #@UndefinedVariable
        return json_failure(design.message_too_long)

    if not data['user']['permission_write']:
        return json_failure(design.you_lack_write_permission)

    msgType = get_val(request.POST, 'type', ChatMessage.MESSAGE)
    if msgType not in [ChatMessage.MESSAGE, ChatMessage.ACTION]:
        msgType = ChatMessage.MESSAGE

    # we're clear. add the message
    m = ChatMessage()
    m.room = room
    m.type = msgType
    m.author = request.user
    m.message = message
    m.save()

    data['success'] = True
    return json_response(data)
コード例 #4
0
ファイル: room.py プロジェクト: TheTypoMaster/angular-chat
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
コード例 #5
0
ファイル: views.py プロジェクト: andrewrk/solidcomposer
def ajax_hear(request):
    """
    get new or all messages
    """
    last_message_str = request.GET.get('last_message', 'null')

    room = get_obj_from_request(request.GET, 'room', ChatRoom)
    if room is None:
        return json_failure(design.bad_room_id)

    # make sure user has permission to be in this room
    data = {
        'user': {
            'is_authenticated': request.user.is_authenticated(),
            'permission_read': room.permission_to_hear(request.user),
            'permission_write': room.permission_to_chat(request.user),
        },
        'room': room.to_dict(),
        'messages': [],
        'success': True
    }

    if request.user.is_authenticated():
        data['user'].update({
            'username': request.user.username,
        })

    if data['user']['permission_read']:
        def add_to_message(msg):
            return {
                'id': msg.id,
                'type': msg.type,
                'author': {
                    'username': msg.author.username,
                    'id': msg.author.id,
                },
                'message': msg.message,
                'timestamp': msg.timestamp,
            }

        if last_message_str == 'null':
            # get entire log for this chat.
            data['messages'] = [add_to_message(x) for x in ChatMessage.objects.filter(room=room)]
        else:
            try:
                last_message_id = int(last_message_str)
            except ValueError:
                last_message_id = 0

            data['messages'] = [add_to_message(x) for x in ChatMessage.objects.filter(room=room, id__gt=last_message_id)]

    if data['user']['permission_write']:
        # mark an appearance in the ChatRoom
        if request.user.is_authenticated() and room.is_active():
            appearances = Appearance.objects.filter(person=request.user, room=room)
            if appearances.count() > 0:
                appearances[0].save() # update the timestamp
            else:
                new_appearance = Appearance()
                new_appearance.room = room
                new_appearance.person = request.user
                new_appearance.save()

                # join message
                m = ChatMessage()
                m.room=room
                m.type=ChatMessage.JOIN
                m.author=request.user
                m.save()

    return json_response(data)
コード例 #6
0
ファイル: room.py プロジェクト: zdimon/angular-chat
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 }