def initialization(request,app_name,user_id, contact_id): ''' Chat initialization. Request gets follows information: 1. Check if user is authenticated. 2. User profile. 3. Contact list. 4. User online list excepting contact. 5. Full user online list. ''' tpa = Tpa.objects.get(name=app_name) #bclient.publish('150032', {'mess':'hello', 'action': 'ping'}) #1 #is_login_url = get_url_by_name('is_login',{'user_id':user_id,'app_name':app_name,'signal_server': TPA_SERVER}) #owner = requests.get(is_login_url).content #is_login = json.loads(is_login) #2 get_profile_url = get_url_by_name('get_profile',{'user_id':user_id,'app_name':app_name,'signal_server': TPA_SERVER}) owner = requests.get(get_profile_url).content owner = json.loads(owner) #3 get_contact_url = get_url_by_name('get_contact_list',{'user_id':user_id,'app_name':app_name,'signal_server': TPA_SERVER}) contact = requests.get(get_contact_url).content contact = json.loads(contact) #4 get_online_url = get_url_by_name('get_online_except_contact',{'user_id':user_id,'app_name':app_name,'signal_server': TPA_SERVER}) online_except_contact = requests.get(get_online_url).content online_except_contact = json.loads(online_except_contact) #5 get_online_url = get_url_by_name('get_online',{'user_id':user_id,'app_name':app_name,'signal_server': TPA_SERVER}) online_full = requests.get(get_online_url).content online_full = json.loads(online_full) return {'status': 0, 'online_except_contact': online_except_contact, 'contact': contact, 'owner': owner, 'online_full': online_full}
def login(request, user_id, app_name): """ Login function. Set couple variables request.session['is_auth'] request.session['user_id'] [server]/api/[user_id]/[app_name]login Example: http://chat.localhost/api/150014/tpa1com/login http://chat.localhost/api/150043/tpa1com/login http://chat.localhost/api/150031/tpa1com/login in session to determitate authentication status """ try: cuser = ChatUser.objects.get(user_id=user_id) except: url = get_url_by_name("get_profile_from_tpa", {"user_id": user_id, "app_name": app_name}) # print 'REQUEST_____%s' % url responce = requests.get(url) cuser = ChatUser.objects.get(user_id=user_id) request.session["is_auth"] = "true" request.session["user_id"] = user_id # return { 'status': 0, 'user_id': user_id, 'username': cuser.name } from djapp.settings import TPA_SERVER return redirect("http://%s/video-chat" % TPA_SERVER)
def send_charge_request(): sql = '''select chat_chatroom.id, chat_chatroom.activity, chat_chatroom.is_charging_text, chat_chatroom.is_charging_video, chat_chatroom.is_charging_audio, chat_tpa.price_text_chat, chat_tpa.price_video, chat_tpa.price_audio, chat_tpa.name as app_name, chat_tpa.timeout_chating from chat_chatroom, chat_tpa where chat_chatroom.tpa_id = chat_tpa.id and chat_chatroom.is_closed = 0 and (is_charging_text="%s" or is_charging_video="%s" or is_charging_audio="%s")''' % (1,1,1) rooms = bd.select(sql) data = [] url = False for room in rooms.record: #url = room['charge_url'] url = get_url_by_name('charge_request',{ 'app_name': room["app_name"]}) # select users from room sql = ''' select chat_chatuser.user_id, chat_chatuser.gender from chat_chatuser, chat_chatuser2room where chat_chatuser2room.user_id = chat_chatuser.id and chat_chatuser2room.room_id = %s ''' % room['id'] users = bd.select(sql) for u in users.record: #print 'room %s user %s' % (room['id'],u['gender']) if u['gender'] == 'm': man = u['user_id'] else: woman = u['user_id'] if(room['is_charging_text']==1): now = int(time.time()) timeout = room['activity']+room['timeout_chating'] #print 'checking %s %s' % (now,timeout) if(now>timeout): sql_update = ''' update chat_chatroom set is_charging_text=0 where id = %s ''' % room['id'] bd.update(sql_update) #print 'TIMOUT 00000000' else: data.append({'action': 'text_chat', 'app_name': room['app_name'], 'user_id': man, 'opponent_id': woman, 'room_id': room['id'], 'price': str(room['price_text_chat']) }) #print data if(room['is_charging_video']==1): data.append({'action': 'video', 'app_name': room['app_name'], 'user_id': man, 'opponent_id': woman, 'room_id': room['id'], 'price': str(room['price_video']) }) if(room['is_charging_audio']==1): data.append({'action': 'audio', 'app_name': room['app_name'], 'user_id': man, 'opponent_id': woman, 'room_id': room['id'], 'price': str(room['price_audio']) }) if url: print "Charge request to %s " % url print "DATA %s" % data print requests.post(url,json=data).content
def clean_online(clients): sql = "select chat_chatuser.user_id, chat_tpa.name from chat_chatuser, chat_tpa where is_online = 1 and chat_chatuser.tpa_id = chat_tpa.id" online = bd.select(sql) for o in online.record: print "checking - %s" % o["user_id"] if not o["user_id"] in clients: bd.update("update chat_chatuser set is_online=0 where user_id=%s" % o["user_id"]) bd.update("update users set online=0 where login=%s" % o["user_id"]) ssql = ( """select chat_chatroom.id from chat_chatroom, chat_chatuser2room, chat_chatuser where chat_chatroom.id = chat_chatuser2room.room_id and chat_chatuser2room.user_id=chat_chatuser.id and chat_chatroom.is_closed = 0 and chat_chatuser.user_id = %s""" % o["user_id"] ) rooms = bd.select(ssql) for r in rooms.record: print "CLOSE ROOM %s for user %s" % (r["id"], o["user_id"]) bd.update( "update chat_chatroom set is_charging_text = 0, is_charging_video = 0, is_charging_audio = 0, is_closed=1 where chat_chatroom.id = %s" % r["id"] ) url = get_url_by_name( "set_disconnected", {"user_id": o["user_id"], "app_name": o["name"], "source": "tpa"} ) print url try: requests.get(url) except: print "Error: Can not do request to %s" % url
def clean_online(): #print 'CLEANING ONLINE!!!' #print 'clients %s' % clients #select all online sql = 'select chat_chatuser.user_id, chat_tpa.name from chat_chatuser, chat_tpa where is_online = 1 and chat_chatuser.tpa_id = chat_tpa.id' online = bd.select(sql) for o in online.record: #print 'checking - %s' % o['user_id'] if not o['user_id'] in clients: bd.update('update chat_chatuser set is_online=0 where user_id=%s' % o['user_id']) bd.update('update users set online=0 where login=%s' % o['user_id']) ssql = '''select chat_chatroom.id from chat_chatroom, chat_chatuser2room, chat_chatuser where chat_chatroom.id = chat_chatuser2room.room_id and chat_chatuser2room.user_id=chat_chatuser.id and chat_chatroom.is_closed = 0 and chat_chatuser.user_id = %s''' % o['user_id'] rooms = bd.select(ssql) for r in rooms.record: #print 'CLOSE ROOM %s for user %s' % (r['id'],o['user_id']) bd.update('update chat_chatroom set is_charging_text = 0, is_charging_video = 0, is_charging_audio = 0, is_closed=1 where chat_chatroom.id = %s' % r['id']) url = get_url_by_name('set_disconnected',{'user_id':o['user_id'], 'app_name': o['name'], 'source': 'tpa'}) #print url try: requests.get(url) except: print 'Error: Can not do request to %s' % url
def set_online(message): url = get_url_by_name( "set_connected", {"user_id": message["user_id"], "app_name": message["tpa"], "source": message["source"]} ) try: requests.get(url) print "REQUEST %s" % url except: print "!!ERROR!! can not make a request to %s" % url
def update_user(request,user_id,app_name): ''' Function update or create user. Example: http://chat.locahost/api/tpa1com/150032/update_user ''' url = get_url_by_name('get_profile_from_tpa',{'user_id':user_id,'app_name':app_name,'signal_server': TPA_SERVER}) responce = requests.get(url) return {'status': 0, 'message': 'ok'}
def on_close(self): ''' Method whith fires when connection is closed. ''' print 'connection closed' url = get_url_by_name('set_disconnected',{'user_id':self.current_user_id, 'app_name': self.tpa_name}) requests.get(url) #self.set_user_offline() #mes = {'action': 'update_users_online'} #self.broadcast(mes) #mes = {'action': 'set_me_offline', 'uid': self.current_user_id} #self.broadcast(mes) self.participants.remove(self)
def clean_online_by_activity(): print "clean online by activity" now = time.time() now = now - 180 user = ChatUser.objects.filter(activity__lt=now, is_online=True) for u in user: print "offline - %s" % u.name url = get_url_by_name("set_disconnected", {"user_id": u.user_id, "app_name": "tpa1com", "source": "tpa"}) print url try: requests.get(url) except: print "Error: Can not do request to %s" % url
def delete_from_online(self,app_name,user=1): yield gen.Task(IOLoop.instance().add_timeout, time.time() + 10) u = int(user) if not u in clients: tmnow = int(time.time()) chanel = '%s_%s' % (app_name,user) try: dift = tmnow - timers[chanel] if dift > 10: #print 'Deleting from online %s %s %s %s ' % (chanel, tmnow, timers[chanel], dift) url = get_url_by_name('set_disconnected',{'user_id':user, 'app_name': app_name, 'source': 'tpa'}) #print url requests.get(url) except: pass
def on_message(self, message): 'Accepting message from javasctipt client' #print 'message received: %s' % message message = json.loads(message) if message['action'] == 'ping': self.write_message('pong'); if message['action'] == 'connect': timers['%s_%s' % (message["tpa"],message["user_id"])] = int(time.time()) #self.replace_timer(message["tpa"],message["user_id"], int(time.time())) #print 'set time %s' % time.time() url = get_url_by_name('set_connected',{'user_id':message["user_id"], 'app_name': message["tpa"], 'source': message['source']}) try: requests.get(url) except: print '!!ERROR!! can not make a request to %s' % url chanel = '%s_%s' % (message["tpa"], message["user_id"]) clients.append(int(message["user_id"])) self._listen(chanel) self.current_user_id = message["user_id"] self.tpa_name = message["tpa"] self.source = message['source'] self.write_message(json.dumps({'action': 'connected', 'status': 0, 'user_id': self.current_user_id, 'message': 'you have been connected to %s' % chanel })) #self.set_user_online() #mes = {'action': 'update_users_online'} #self.broadcast(mes) #mes = {'action': 'set_me_online', 'uid': self.current_user_id} #self.broadcast(mes) #print 'set me online!!!!!!!!!!!!' #except Exception, e: # print e # self.write_message(json.dumps({'status': 1, 'message': str(e)})) handle(message,self)
def get_profile(request,user_id,app_name): from djapp.settings import TPA_SERVER try: tpa = Tpa.objects.get(name=app_name) u_name = ChatUser.objects.get(user_id=user_id,tpa=tpa) out = { 'status': 0, 'user_profile': serialize_user(u_name) } return HttpResponse(json.dumps(out), content_type='application/json') except: url = get_url_by_name('get_profile_from_tpa',{'user_id':user_id,'app_name':app_name,'signal_server': TPA_SERVER}) print 'REQUEST TO %s' % url responce = requests.get(url) outdata = json.loads(responce.content) #print outdata out = { 'status': 0, 'message': 'ok', 'outdata': outdata } return HttpResponse(json.dumps(out), content_type='application/json')
def get_online(request,app_name,user_id): ''' Function return list of users with opposite gender who are on line [server]/api/[app_name]/[user_id]/get_online Example: http://chat.localhost/api/tpa1com/150031/get_online ''' userlst_profile = [] tpa = Tpa.objects.get(name=app_name) if user_id == 'undefined': return { 'status': 0, 'message': 'ok', 'user_list': {} } else: try: owner = ChatUser.objects.get(tpa=tpa,user_id=user_id) except: url = get_url_by_name('get_profile_from_tpa',{'user_id':user_id,'app_name':app_name,'signal_server': TPA_SERVER}) responce = requests.get(url) owner = ChatUser.objects.get(tpa=tpa,user_id=user_id) users_online = ChatUser.objects.filter(tpa=tpa,is_online=1).exclude(gender=owner.gender) for u in users_online: userlst_profile.append(serialize_user(u)) return { 'status': 0, 'message': 'ok', 'user_list': userlst_profile }
def on_message(self, message): 'Accepting message from javasctipt client' #print 'message received: %s' % message message = json.loads(message) if message['action'] == 'connect': try: url = get_url_by_name('set_connected',{'user_id':message["user_id"], 'app_name': message["tpa"]}) requests.get(url) chanel = '%s_%s' % (message["tpa"], message["user_id"]) self.subscribe(chanel) self.current_user_id = message["user_id"] self.tpa_name = message["tpa"] self.write_message(json.dumps({'action': 'connected', 'status': 0, 'user_id': self.current_user_id, 'message': 'you have been connected to %s' % chanel })) #self.set_user_online() #mes = {'action': 'update_users_online'} #self.broadcast(mes) #mes = {'action': 'set_me_online', 'uid': self.current_user_id} #self.broadcast(mes) #print 'set me online!!!!!!!!!!!!' except Exception, e: print e self.write_message(json.dumps({'status': 1, 'message': str(e)}))
def charge_money(): sql = """select chat_chatroom.id, chat_chatroom.activity, chat_chatroom.is_charging_text, chat_chatroom.is_charging_video, chat_chatroom.is_charging_audio, chat_tpa.price_text_chat, chat_tpa.price_video, chat_tpa.price_audio, chat_tpa.name as app_name, chat_tpa.timeout_chating from chat_chatroom, chat_tpa where chat_chatroom.tpa_id = chat_tpa.id and chat_chatroom.is_closed = 0 and (is_charging_text="%s" or is_charging_video="%s" or is_charging_audio="%s")""" % ( 1, 1, 1, ) rooms = bd.select(sql) data = [] url = False print "Charging!!!!" for room in rooms.record: # url = room['charge_url'] url = get_url_by_name("charge_request", {"app_name": room["app_name"]}) # select users from room sql = ( """ select chat_chatuser.user_id, chat_chatuser.gender from chat_chatuser, chat_chatuser2room where chat_chatuser2room.user_id = chat_chatuser.id and chat_chatuser2room.room_id = %s """ % room["id"] ) users = bd.select(sql) for u in users.record: # print 'room %s user %s' % (room['id'],u['gender']) if u["gender"] == "m": man = u["user_id"] else: woman = u["user_id"] if room["is_charging_text"] == 1: now = int(time.time()) timeout = room["activity"] + room["timeout_chating"] # print 'checking %s %s' % (now,timeout) if now > timeout: sql_update = """ update chat_chatroom set is_charging_text=0 where id = %s """ % room["id"] bd.update(sql_update) # print 'TIMOUT 00000000' # send command to remove user from contact list mess_ac = {"action": "delete_me_from_contact", "opponent_id": u["user_id"]} bclient.publish("%s_%s" % (room["app_name"], man), json.dumps(mess_ac)) mess_ac = {"action": "delete_me_from_contact", "opponent_id": man} bclient.publish("%s_%s" % (room["app_name"], u["user_id"]), json.dumps(mess_ac)) else: data.append( { "action": "text_chat", "app_name": room["app_name"], "user_id": man, "opponent_id": woman, "room_id": room["id"], "price": str(room["price_text_chat"]), } ) # print data if room["is_charging_video"] == 1: data.append( { "action": "video", "app_name": room["app_name"], "user_id": man, "opponent_id": woman, "room_id": room["id"], "price": str(room["price_video"]), } ) if room["is_charging_audio"] == 1: data.append( { "action": "audio", "app_name": room["app_name"], "user_id": man, "opponent_id": woman, "room_id": room["id"], "price": str(room["price_audio"]), } ) if url: print "Charge request to %s " % url print "DATA %s" % data print requests.post(url, json=data).content
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 }