async def connect(self): room_channel_no = self.scope['url_route']['kwargs']['room_name'] request_user = self.scope["user"] # 游客拒绝 if request_user.is_anonymous: # Reject the connection await self.close() # 必须是我加入的频道 elif room_channel_no in request_user.profile.get_my_chat_room(): self.room_name = room_channel_no self.room_group_name = 'chat_%s' % self.room_name # 加入成员保存字典 redis缓存中 ChatCache().append(self.room_group_name, request_user.profile.unicode_id) print('UID:%s加入房间(%s),剩余:%s' % (self.scope["user"].profile.unicode_id, self.room_group_name, ChatCache().get_cache(self.room_group_name))) # Join room group await self.channel_layer.group_add(self.room_group_name, self.channel_name) await self.accept() # 机器人回复频道 elif room_channel_no == 'GP_robot': self.room_name = room_channel_no self.room_group_name = 'chat_%s' % self.room_name # Join room group await self.channel_layer.group_add(self.room_group_name, self.channel_name) await self.accept() else: await self.close()
async def disconnect(self, close_code): # Leave room group 缓存中清理 ChatCache(self.room_group_name).set_remove(self.profile_uid) print('UID:%s离开房间(%s),剩余:%s' % (self.request_user.profile.unicode_id, self.room_group_name, ChatCache(self.room_group_name).set_members())) await self.channel_layer.group_discard(self.room_group_name, self.channel_name)
async def disconnect(self, close_code): # Leave room group 缓存中清理 ChatCache().remove(self.room_group_name, self.scope["user"].profile.unicode_id) print('UID:%s离开房间(%s),剩余:%s' % (self.scope["user"].profile.unicode_id, self.room_group_name, ChatCache().get_cache(self.room_group_name))) await self.channel_layer.group_discard(self.room_group_name, self.channel_name)
def __init__(self): self.nes = NetEaseServer() self.engine = QQMUsicServer() self.aplayer_data = { 'name': '', 'artist': '', 'url': '', 'cover': '', # 唱片图片 'lrc': '', 'theme': '#ebd0c2', 'song_process': '0', # 歌曲播放进度 } self.name = 'musiclist' self.ap_cache = ChatCache(self.name)
async def connect(self): # 游客拒绝 if self.request_user.is_anonymous: await self.close() # 初始化信息 self.profile_uid = self.request_user.profile.unicode_id # url参数上的channel_no self.room_channel_no = self.scope['url_route']['kwargs']['room_name'] self.chat_room_model = ChatRoom.objects.filter( channel_no=self.room_channel_no).first() self.room_type = self.chat_room_model.chat_type # 拼接websocket组的名字 self.room_group_name = self.room_type + '_' + self.room_channel_no # 初始化信息结束 # 必须是我加入的频道 if self.room_channel_no in self.request_user.profile.get_my_chat_room( ): # 加入成员保存字典 redis缓存中 ChatCache(self.room_group_name).set_add(self.profile_uid) # 打印信息 print('UID:%s加入房间(%s),剩余:%s' % (self.profile_uid, self.room_group_name, ChatCache(self.room_group_name).set_members())) # Join room group await self.channel_layer.group_add(self.room_group_name, self.channel_name) await self.accept() # 机器人回复频道 elif self.room_type == 'ROBOT': # Join room group await self.channel_layer.group_add(self.room_group_name, self.channel_name) await self.accept() else: await self.close()
async def connect(self): uid = self.scope['url_route']['kwargs']['uid'] ChatCache('__online').set_add(uid) if self.scope["user"].is_anonymous: # Reject the connection await self.close() else: self.uid = uid self.uid_group = 'notification_%s' % self.uid # Join room group await self.channel_layer.group_add(self.uid_group, self.channel_name) await self.accept()
def list(self, request, *args, **kwargs): total_user = User.objects.count() total_room = ChatRoom.objects.count() total_online = ChatCache('__online').set_len() or 0 total_history = History.objects.aggregate(total=Sum('count'))['total'] user_register_table = self.get_user_register_table() daily_user_register_table = self.get_daily_user_register_table() chatroom_table = self.get_chatroom_table() donut = [ {'label': "访问人次", 'value': total_history}, ] return JsonResponse( {'area': user_register_table, 'bar': chatroom_table, 'donut': donut, 'line': daily_user_register_table, 'total_user': total_user, 'total_room': total_room, 'total_online': total_online, 'total_history': total_history}, status=200)
async def receive(self, text_data=None, bytes_data=None): # 接收参数 text_data_json = json.loads(text_data) or {} message = text_data_json.get('message', '') if message == '': return msg_type = text_data_json.get('msg_type') action = text_data_json.get('action', '') song_index = text_data_json.get('song_index', None) now_song_id = text_data_json.get('now_song_id', None) send_user_nick_name = text_data_json.get('send_user_nick_name', '') send_time = datetime.now() # 房间类型 # 机器人 if self.room_type == 'ROBOT' and msg_type == 'chat_message': robot_msg, msg_type = talk_with_me(message) robot_user, _ = User.objects.get_or_create(username='******') robot_send_time = datetime.now() await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': robot_msg, 'user_id': 'robot', 'send_time': robot_send_time.strftime('%p %H:%M'), 'msg_type': msg_type, 'username': self.request_user.username }) if message: # 与机器人聊天记录 ChatLog.objects.create(chat_datetime=robot_send_time, content=message, msg_type=msg_type, who_said=self.request_user, said_to_id=self.request_user.id, said_to_room=self.chat_room_model) ChatLog.objects.create(chat_datetime=robot_send_time, content=robot_msg, msg_type=msg_type, who_said=robot_user, said_to_id=self.request_user.id, said_to_room=self.chat_room_model) # 普通的对话 elif msg_type == 'chat_message': # Send message to room group 如果他人不在房间就单对单发通知 if self.chat_room_model: # 房间成员 menbers_list = self.chat_room_model.get_members_unicode_id() menbers_list = [str(i) for i in menbers_list] # 在线成员 online_list = ChatCache(self.room_group_name).set_members() # 离线成员 outline_list = set(menbers_list) - online_list print('成员人数:%s\n在线人数:%s\n离线人数:%s' % (menbers_list, online_list, outline_list)) # 离线发通知 for ntf in outline_list: await self.channel_layer.group_send( 'notification_%s' % (ntf), { 'type': 'push_message', 'msg_type': 'push_message', 'message': message, 'send_time': send_time.strftime('%p %H:%M'), 'channel_no': self.room_channel_no, 'user_id': str(self.request_user.id), 'send_user_nick_name': send_user_nick_name, }) if message: queryset = [] for on in online_list: queryset.append( ChatLog(chat_datetime=send_time, content=message, msg_type=msg_type, who_said=self.request_user, said_to=User.objects.filter( profile__unicode_id=on).first(), said_to_room=self.chat_room_model, status='read')) for out in outline_list: queryset.append( ChatLog(chat_datetime=send_time, content=message, msg_type=msg_type, who_said=self.request_user, said_to=User.objects.filter( profile__unicode_id=out).first(), said_to_room=self.chat_room_model, status='unread')) ChatLog.objects.bulk_create(queryset) await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message, 'user_id': str(self.request_user.id), 'send_time': send_time.strftime('%p %H:%M'), 'msg_type': msg_type, }) elif msg_type == 'chat_info': await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message, 'user_id': str(self.request_user.id), 'send_time': send_time.strftime('%p %H:%M'), 'msg_type': msg_type, }) elif msg_type == 'chat_music': aplayer_data = [] if 'init_data' in message: aplayer_data = MusicRobot().get_now_song_data_list() action = 'init_data' # 询问其他人进度 elif '点歌' in message: message = message.replace('点歌', '', 1).strip() song_info = MusicRobot().pick_a_song(message) # 找不到歌曲,或歌曲已存在 if not song_info: action = 'tips' else: aplayer_data = [song_info] action = 'add_song' elif "切歌" in message: MusicRobot().switch_next_song(now_song_id) action = 'switch_next_song' elif action == 'reload_song_url': music_robot = MusicRobot() music_robot.del_song_data(now_song_id) new_song_url = music_robot.get_song_url(now_song_id) if not new_song_url: action = 'tips' else: message['url'] = new_song_url music_robot.upload_song_data(now_song_id, message) aplayer_data = [message] elif action == 'remove_song': MusicRobot().del_song_data(now_song_id) return elif action == 'ack_song_process': print('询问其他人播放进度') elif action == 'syn_song_process': print('回答自己歌曲播放进度', self.request_user.profile.nick_name, message) # todo 改为自己的 return if float(message) < 1: return aplayer_data = message elif action == 'quit_listen_song': print(message) elif action == 'update_song': MusicRobot().update_song_data_song_process( now_song_id, 'song_process', message) return else: msg_type = 'chat_message' aplayer_data = message print('>>>当前歌单\n', aplayer_data) await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': aplayer_data, 'msg_type': msg_type, 'user_id': str(self.request_user.id), 'send_time': '', 'action': action, 'song_index': song_index, })
async def receive(self, text_data=None, bytes_data=None): text_data_json = json.loads(text_data) message = text_data_json['message'] msg_type = text_data_json['msg_type'] send_user_nick_name = text_data_json.get('send_user_nick_name', '') or '' chat_user = self.scope.get('user') send_time = datetime.now() # 机器人 加思知回复 if self.room_name == 'GP_robot' and msg_type == 'chat_message': self.chat_room_model = ChatRoom.objects.filter( channel_no=self.room_name).first() robot_msg, chat_type = talk_with_me(message) robot_user, _ = User.objects.get_or_create(username='******') robot_send_time = datetime.now() await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': robot_msg, 'user_id': 'robot', 'send_time': robot_send_time.strftime('%p %H:%M'), 'msg_type': chat_type, 'username': self.scope.get('user').username }) if message and chat_type == 'chat_message': ChatLog.objects.create(chat_datetime=robot_send_time, content=message, msg_type=msg_type, who_said=chat_user, said_to_id=chat_user.id, said_to_room=self.chat_room_model) ChatLog.objects.create(chat_datetime=robot_send_time, content=robot_msg, msg_type=msg_type, who_said=robot_user, said_to_id=chat_user.id, said_to_room=self.chat_room_model) elif msg_type == 'chat_message': self.chat_room_model = ChatRoom.objects.filter( channel_no=self.room_name).first() # Send message to room group 如果他人不在房间就单对单发通知 if self.chat_room_model: menbers_list = self.chat_room_model.get_members_unicode_id() online_list = ChatCache().get_cache(self.room_group_name) outline_list = set(menbers_list) - online_list print('成员人数:%s\n在线人数:%s\n离线人数:%s' % (menbers_list, online_list, outline_list)) for ntf in outline_list: await self.channel_layer.group_send( 'notification_%s' % (ntf), { 'type': 'push_message', 'message': message, 'user_id': str(chat_user.id), 'send_time': send_time.strftime('%p %H:%M'), 'msg_type': msg_type, 'channel_no': self.room_name, 'send_user_nick_name': send_user_nick_name, }) if message: queryset = [] for on in online_list: queryset.append( ChatLog(chat_datetime=send_time, content=message, msg_type=msg_type, who_said=chat_user, said_to=User.objects.filter( profile__unicode_id=on).first(), said_to_room=self.chat_room_model, status='read')) for out in outline_list: queryset.append( ChatLog(chat_datetime=send_time, content=message, msg_type=msg_type, who_said=chat_user, said_to=User.objects.filter( profile__unicode_id=out).first(), said_to_room=self.chat_room_model, status='unread')) ChatLog.objects.bulk_create(queryset) await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message, 'user_id': str(chat_user.id), 'send_time': send_time.strftime('%p %H:%M'), 'msg_type': msg_type, }) elif msg_type == 'chat_info': await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message, 'user_id': str(chat_user.id), 'send_time': send_time.strftime('%p %H:%M'), 'msg_type': msg_type, })
def setUpClass(cls): cls.cache = ChatCache("test") # cls.cache.clear() print("Start test cache")
class MusicRobot(object): def __init__(self): self.nes = NetEaseServer() self.engine = QQMUsicServer() self.aplayer_data = { 'name': '', 'artist': '', 'url': '', 'cover': '', # 唱片图片 'lrc': '', 'theme': '#ebd0c2', 'song_process': '0', # 歌曲播放进度 } self.name = 'musiclist' self.ap_cache = ChatCache(self.name) def _get_song_id(self, keyword): return self.nes.get_song_id(keyword=keyword) def _get_song_id_list(self, keyword, limit=3): return self.nes.get_song_id_list(keyword=keyword, limit=limit) def get_song_url(self, song_id): return self.nes.get_song_url(song_id=song_id) def _get_song_lyric(self, song_id): return self.nes.get_song_lyric(song_id=song_id) def _get_song_detail(self, song_id): return self.nes.get_song_details(song_id=song_id) def pick_a_song(self, keyword): """ Step1 歌曲已经在歌单 Step2 渠道请求歌单 Step3 更新歌单 :param keyword: :return: """ # 默认选择3条查找有版权那首 song_id_list = self._get_song_id_list(keyword=keyword) song_id_list_not_null = list(filter(lambda x: x, song_id_list)) aplayer_data = None while song_id_list_not_null: song_id = song_id_list_not_null.pop(0) is_exist = self.ap_cache.hash_exists(song_id) if is_exist: # 歌曲已经在歌单 return None else: aplayer_data = self.get_song_info_and_upload(song_id) if aplayer_data: break return aplayer_data def pick_a_song_qq_music(self, keyword): song_id = self.engine.get_song_id_list(keyword) is_exist = self.ap_cache.hash_exists(song_id) if is_exist: # 歌曲已经在歌单 return None else: self.engine.get_song_url(song_id) aplayer_data = self.engine.song_details aplayer_data['add_time'] = time.time() self.upload_song_data(song_id, aplayer_data) return aplayer_data def switch_next_song(self, now_song_id): self.ap_cache.hash_del(now_song_id) def get_song_info_and_upload(self, song_id): song_lyric = self._get_song_lyric(song_id=song_id) song_detail = self._get_song_detail(song_id=song_id) song_url = self.get_song_url(song_id=song_id) if not song_url: return None # 歌曲url 为none self.aplayer_data['id'] = song_id self.aplayer_data['name'] = song_detail['name'] self.aplayer_data['artist'] = song_detail['artist'] self.aplayer_data['url'] = song_url self.aplayer_data['cover'] = song_detail['picture_url'] self.aplayer_data['lrc'] = song_lyric self.aplayer_data['add_time'] = time.time() self.upload_song_data(song_id, self.aplayer_data) return self.aplayer_data def upload_song_data(self, song_id, data): """上传到redis""" self.ap_cache.hash_set(song_id, json.dumps(data)) def get_now_song_data_list(self): serializer_data = [json.loads(data) for data in self.ap_cache.hash_values()] serializer_data.sort(key=lambda x: x.get('add_time')) return serializer_data def del_song_data(self, song_id): self.ap_cache.hash_del(song_id) def update_song_data_song_process(self, song_id, sub_key, sub_value): song_dict = json.loads(self.ap_cache.hash_hget(song_id)) song_dict[sub_key] = sub_value self.ap_cache.hash_set(song_id, json.dumps(song_dict))