def new_message(self, data): '''收到nsq服务器的新消息, data必须具有`topic`和`message`两个字段, 分别用来保存消息的topic和具体消息内容, 你需要在相关消费者的handler里边封装之. data结构如下所示. { 'topic': xxx, 'message': xxx } ''' if self.request.connection.stream.closed(): return assert isinstance(data, dict) assert 'topic' in data assert 'message' in data MessageDocument.set_read_sync(self.current_user['_id'], data['topic']) if data['topic'] == MessageTopic.CHAT_MESSAGE_NEW: # 将该消息标记为已读 ChatMessageDocument.get_collection(pymongo=True).update( {'_id': ObjectId(data['message']['_id'])}, {'$set': {'read': True}} ) messages = [{ '_id': data['message']['sender'], 'messages': [data['message']] }] response_data = self._new_chat_message_handler(messages) else: response_data = self._new_message_handler(data) self.finish(response_data)
def new_message(self, data): '''收到nsq服务器的新消息, data必须具有`topic`和`message`两个字段, 分别用来保存消息的topic和具体消息内容, 你需要在相关消费者的handler里边封装之. data结构如下所示. { 'topic': xxx, 'message': xxx } ''' if self.request.connection.stream.closed(): return assert isinstance(data, dict) assert 'topic' in data assert 'message' in data MessageDocument.set_read_sync(self.current_user['_id'], data['topic']) if data['topic'] == MessageTopic.CHAT_MESSAGE_NEW: # 将该消息标记为已读 ChatMessageDocument.get_collection(pymongo=True).update( {'_id': ObjectId(data['message']['_id'])}, {'$set': {'read': True}} ) messages = [{ '_id': data['message']['sender'], 'messages': [data['message']] }] response_data = self._new_chat_message_handler(messages) else: response_data = self._new_message_handler(data) self.write_json(response_data) self.finish()
def get(self): form = MessageForm(self.request.arguments) if not form.validate(): raise HTTPError(404) category = form.category.data kwargs = yield self.get_sidebar_arguments() if category == MessageTopic.CHAT_MESSAGE_NEW: message_list = yield ChatMessageDocument.get_chat_message_list( self.current_user['_id'], limit=HOME_SETTINGS['message_number_per_page'] ) else: message_list = yield MessageDocument.get_message_list( self.current_user['_id'], message_topic=category, limit=HOME_SETTINGS['message_number_per_page'] ) yield MessageDocument.set_read(self.current_user['_id'], category) kwargs.update({ 'message_list': message_list, 'category': category }) self.render('home/template/message/message.html', **kwargs)
def post(self): form = MessageUpdaterForm(self.request.arguments) if not form.validate(): raise HTTPError(404) n = form.n.data XMPPClientManager.get_xmppclient( self.current_user['_id'], self.current_user['password'] ) has_unreceived = MessageDocument.has_unreceived( self.current_user['_id'] ) has_unread_chat_message = ChatMessageDocument.has_unread_chat_message( self.current_user['_id'] ) if n == 1 or has_unreceived: unread_message_numbers = MessageDocument.get_unread_message_numbers( self.current_user['_id'] ) MessageDocument.set_received(self.current_user['_id']) kwargs = { 'unread_message_numbers': unread_message_numbers, 'MessageTopic': MessageTopic } html = self.render_string( 'message/template/message-header.html', **kwargs ) self.write_json({ 'topic': 'unread_message_numbers', 'html': html }) self.finish() elif has_unread_chat_message: messages = ChatMessageDocument.get_unread_messages( self.current_user['_id'] ) response_data = self._new_chat_message_handler(messages) ChatMessageDocument.set_read(self.current_user['_id']) self.write_json(response_data) self.finish() else: BrowserCallbackManager.add( self.current_user['_id'], self.new_message )
def post(self): form = MessageUpdaterForm(self.request.arguments) if not form.validate(): raise HTTPError(404) n = form.n.data XMPPClientManager.get_xmppclient( self.current_user['_id'], self.current_user['password'] ) has_unreceived = MessageDocument.has_unreceived( self.current_user['_id'] ) has_unread_chat_message = ChatMessageDocument.has_unread_chat_message( self.current_user['_id'] ) if n == 1 or has_unreceived: unread_message_numbers = MessageDocument.get_unread_message_numbers( self.current_user['_id'] ) MessageDocument.set_received(self.current_user['_id']) kwargs = { 'unread_message_numbers': unread_message_numbers, 'MessageTopic': MessageTopic } html = self.render_string( 'message/template/message-header.html', **kwargs ) self.finish(json.dumps({ 'topic': 'unread_message_numbers', 'html': html })) elif has_unread_chat_message: messages = ChatMessageDocument.get_unread_messages( self.current_user['_id'] ) response_data = self._new_chat_message_handler(messages) ChatMessageDocument.set_read(self.current_user['_id']) self.finish(response_data) else: BrowserCallbackManager.add( self.current_user['_id'], self.new_message )
def post(self): response_data = {} form = FriendRequestForm(self.request.arguments) if not form.validate(): raise HTTPError(404) user_id = form.user_id.data user = yield UserDocument.find_one({'_id': ObjectId(user_id)}) if not user or user['_id'] == self.current_user['_id']: raise HTTPError(404) is_friend = yield FriendDocument.is_friend( user_id, self.current_user['_id'] ) if is_friend: raise HTTPError(404) document = { 'sender': DBRef( UserDocument.meta['collection'], ObjectId(self.current_user['_id']) ), 'recipient': DBRef( UserDocument.meta['collection'], ObjectId(user_id) ), 'message_type': MessageTopic.FRIEND_REQUEST_NEW, } message = yield MessageDocument.find_one(document) if message: response_data = {'error': '你已经发送了好友请求!'} else: user_setting = yield UserSettingDocument.get_user_setting(user_id) if not user_setting['require_verify_when_add_friend']: yield FriendDocument.add_friend( user_id, self.current_user['_id'] ) response_data.update({'ok': 1}) document.update({'time': datetime.now()}) message_id = yield MessageDocument.insert(document) WriterManager.pub(MessageTopic.FRIEND_REQUEST_NEW, message_id) self.write_json(response_data)
def get_recommend_friends(user_id, size=5): '''得到推荐的朋友 :Parameters: - `user_id`: 为谁推荐? - `size`: 推荐数量 ''' from app.message.document import MessageDocument user = yield UserDocument.find_one({'_id': ObjectId(user_id)}) if not user: raise gen.Return([]) friend_list = yield FriendDocument.get_friend_list(user['_id']) friend_objectid_list = [user['_id']] + [ friend['_id'] for friend in friend_list ] cursor = MessageDocument.find({ 'sender': DBRef( UserDocument.meta['collection'], ObjectId(user_id) ), 'message_type': MessageTopic.FRIEND_REQUEST_NEW }) message_list = yield MessageDocument.to_list(cursor) for message in message_list: friend_objectid_list.append( ObjectId(message['recipient'].id) ) query = { '_id': {'$nin': friend_objectid_list}, 'activated': True, 'avatar_updated': True } cursor = UserDocument.find(query) count = yield UserDocument.find(query).count() if count > size: cursor = cursor.skip(random.randint(0, count - size)) cursor = cursor.limit(size) user_list = yield UserDocument.to_list(cursor) raise gen.Return(user_list)
def post(self): form = FriendRequestForm(self.request.arguments) if not form.validate(): raise HTTPError(404) user_id = form.user_id.data user = yield UserDocument.find_one({'_id': ObjectId(user_id)}) if not user or user['_id'] == self.current_user['_id']: raise HTTPError(404) is_friend = yield FriendDocument.is_friend( user_id, self.current_user['_id'] ) if not is_friend: yield FriendDocument.add_friend( user_id, self.current_user['_id'] ) yield MessageDocument.remove({ 'sender': DBRef( UserDocument.meta['collection'], ObjectId(user_id) ), 'recipient': DBRef( UserDocument.meta['collection'], ObjectId(self.current_user['_id']) ), 'message_type': MessageTopic.FRIEND_REQUEST_NEW })
def send_has_unread_message_email_handler(message): '''如果用户不在线就发送邮件''' from young.handler import BaseHandler from app.user.document import UserDocument from app.message.document import MessageDocument message = MessageDocument.get_collection(pymongo=True).find_one( {'_id': ObjectId(message.body)}) if not message: return True recipient_id = message['recipient'].id topic = MessageTopic.message_type2topic(message['message_type']) recipient = UserDocument.get_user_sync(recipient_id) if recipient and recipient['activated']: message = BaseHandler.translate_dbref_in_document(message) if 'data' in message: message['data'] = BaseHandler.translate_dbref_in_document( message['data'], depth=2) kwargs = { 'message_topic': topic, 'message': message, 'MessageTopic': MessageTopic, 'handler': BaseHandler } root = os.path.dirname( os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) path = os.path.join(root, 'app/message/template') loader = template.Loader(path) html = loader.load("message.html").generate(**kwargs) soup = BeautifulSoup(html, "html.parser") link_list = soup.find_all('a') for link in link_list: new_link = link if link['href'].startswith('/'): new_link['href'] = EMAIL_SETTINGS['url'] + link['href'] link.replace_with(new_link) img_list = soup.find_all('img') for img in img_list: new_img = img if img['src'].startswith('/'): new_img['src'] = EMAIL_SETTINGS['url'] + img['src'] img.replace_with(new_img) body = ('{} <a href="{}/setting/notification">' '关闭邮件提醒</a>').format(soup.prettify(), EMAIL_SETTINGS["url"]) msg = MIMEText(body, "html", 'utf-8') msg["subject"] = "你有未读消息【Young社区】" send_email(recipient['email'], msg) return True
def get(self, user_id=None): user_id = user_id or self.current_user["_id"] kwargs = yield self.get_header_arguments(user_id) if not kwargs['can_seen']: self.render('profile/template/profile-visitor.html', **kwargs) else: messages_func = LeaveMessageDocument.get_leave_message_list leave_message_list = yield messages_func( user_id, self.current_user['_id'], limit=PROFILE_SETTINGS['leave_message_number_per_page'] ) kwargs.update({ 'leave_message_list': leave_message_list }) if ObjectId(user_id) == ObjectId(self.current_user['_id']): yield MessageDocument.set_read( user_id, MessageTopic.LEAVE_MESSAGE_NEW ) self.render( 'profile/template/leavemessage/leavemessage.html', **kwargs )
def post(self): form = FriendRequestForm(self.request.arguments) if not form.validate(): raise HTTPError(404) user_id = form.user_id.data user = yield UserDocument.find_one({'_id': ObjectId(user_id)}) if not user or user['_id'] == self.current_user['_id']: raise HTTPError(404) is_friend = yield FriendDocument.is_friend(user_id, self.current_user['_id']) if not is_friend: yield FriendDocument.add_friend(user_id, self.current_user['_id']) yield MessageDocument.remove({ 'sender': DBRef(UserDocument.meta['collection'], ObjectId(user_id)), 'recipient': DBRef(UserDocument.meta['collection'], ObjectId(self.current_user['_id'])), 'message_type': MessageTopic.FRIEND_REQUEST_NEW }) self.finish()
def get_recommend_friends(user_id, size=5): '''得到推荐的朋友 :Parameters: - `user_id`: 为谁推荐? - `size`: 推荐数量 ''' from app.message.document import MessageDocument user = yield UserDocument.find_one({'_id': ObjectId(user_id)}) if not user: raise gen.Return([]) friend_list = yield FriendDocument.get_friend_list(user['_id']) friend_objectid_list = [user['_id'] ] + [friend['_id'] for friend in friend_list] cursor = MessageDocument.find({ 'sender': DBRef(UserDocument.meta['collection'], ObjectId(user_id)), 'message_type': MessageTopic.FRIEND_REQUEST_NEW }) message_list = yield MessageDocument.to_list(cursor) for message in message_list: friend_objectid_list.append(ObjectId(message['recipient'].id)) query = { '_id': { '$nin': friend_objectid_list }, 'activated': True, 'avatar_updated': True } cursor = UserDocument.find(query) count = yield UserDocument.find(query).count() if count > size: cursor = cursor.skip(random.randint(0, count - size)) cursor = cursor.limit(size) user_list = yield UserDocument.to_list(cursor) raise gen.Return(user_list)
def delete_one(topic_id): topic = DBRef(TopicDocument.meta['collection'], ObjectId(topic_id)) yield TopicDocument.remove({'_id': ObjectId(topic_id)}) yield TopicStatisticsDocument.remove({'data': topic}) yield TopicLikeDocument.delete(topic_id) yield TopicCommentDocument.delete(topic_id) yield MessageDocument.remove({'data': topic}) raise gen.Return()
def post(self): response_data = {} form = FriendRequestForm(self.request.arguments) if not form.validate(): raise HTTPError(404) user_id = form.user_id.data user = yield UserDocument.find_one({'_id': ObjectId(user_id)}) if not user or user['_id'] == self.current_user['_id']: raise HTTPError(404) is_friend = yield FriendDocument.is_friend(user_id, self.current_user['_id']) if is_friend: raise HTTPError(404) document = { 'sender': DBRef(UserDocument.meta['collection'], ObjectId(self.current_user['_id'])), 'recipient': DBRef(UserDocument.meta['collection'], ObjectId(user_id)), 'message_type': MessageTopic.FRIEND_REQUEST_NEW, } message = yield MessageDocument.find_one(document) if message: response_data = {'error': '你已经发送了好友请求!'} else: user_setting = yield UserSettingDocument.get_user_setting(user_id) if not user_setting['require_verify_when_add_friend']: yield FriendDocument.add_friend(user_id, self.current_user['_id']) response_data.update({'ok': 1}) document.update({'time': datetime.now()}) message_id = yield MessageDocument.insert(document) WriterManager.pub(MessageTopic.FRIEND_REQUEST_NEW, message_id) self.finish(json.dumps(response_data))
def post(self): '''点赞''' form = StatusLikeForm(self.request.arguments) if not form.validate(): raise HTTPError(404) status_id = form.status_id.data status = yield StatusDocument.find_one({'_id': ObjectId(status_id)}) if not status: raise HTTPError(404) status_dbref = DBRef(StatusDocument.meta['collection'], ObjectId(status_id)) liker_dbref = DBRef(UserDocument.meta['collection'], ObjectId(self.current_user['_id'])) document = {'status': status_dbref, 'liker': liker_dbref} liked = yield StatusLikeDocument.is_liked(status_id, self.current_user['_id']) if not liked: now = datetime.now() document.update({'like_time': now}) like_id = yield StatusLikeDocument.insert_one(document) if str(self.current_user['_id']) != str(status['author'].id): document = { 'sender': DBRef(UserDocument.meta['collection'], ObjectId(self.current_user['_id'])), 'recipient': DBRef(UserDocument.meta['collection'], ObjectId(status['author'].id)), 'message_type': 'like:status', 'time': now, 'read': False, 'data': DBRef(StatusLikeDocument.meta['collection'], ObjectId(like_id)) } message_id = yield MessageDocument.insert(document) WriterManager.pub(MessageTopic.LIKE, message_id) like_times = yield StatusLikeDocument.get_like_times(status_id) like_list = yield StatusLikeDocument.get_like_list( status['_id'], self.current_user['_id']) likers = '、'.join([like['liker']['name'] for like in like_list]) self.write_json({'like_times': like_times, 'likers': likers})
def delete_one(topic_id): topic = DBRef( TopicDocument.meta['collection'], ObjectId(topic_id) ) yield TopicDocument.remove({'_id': ObjectId(topic_id)}) yield TopicStatisticsDocument.remove({'data': topic}) yield TopicLikeDocument.delete(topic_id) yield TopicCommentDocument.delete(topic_id) yield MessageDocument.remove({'data': topic}) raise gen.Return()
def post(self): '''加载更多消息''' form = MessageMoreForm(self.request.arguments) if not form.validate(): raise HTTPError(404) page = form.page.data category = form.category.data skip = HOME_SETTINGS['message_number_per_page'] * page limit = HOME_SETTINGS['message_number_per_page'] if category == MessageTopic.CHAT_MESSAGE_NEW: message_list = yield ChatMessageDocument.get_chat_message_list( self.current_user['_id'], skip=skip, limit=limit ) else: message_list = yield MessageDocument.get_message_list( self.current_user['_id'], message_topic=category, skip=skip, limit=limit ) if category == MessageTopic._FRIENDS_DYNAMIC: path = 'message-friends-dynamic-list-item.html' elif category == MessageTopic._COMMENT_AND_REPLY: path = 'message-comment-and-reply-list-item.html' elif category == MessageTopic.AT: path = 'message-at-list-item.html' elif category == MessageTopic.CHAT_MESSAGE_NEW: path = 'message-chat-message-list-item.html' elif category == MessageTopic.FRIEND_REQUEST_NEW: path = 'message-friend-request-list-item.html' elif category == MessageTopic.LIKE: path = 'message-like-list-item.html' path = os.path.join("home/template/message", path) html = ''.join( self.render_string( path, message=message, MessageTopic=MessageTopic ) for message in message_list ) response_data = json.dumps({'html': html, 'page': page + 1}) self.finish(response_data)
def post(self): '''加载更多消息''' form = MessageMoreForm(self.request.arguments) if not form.validate(): raise HTTPError(404) page = form.page.data category = form.category.data skip = HOME_SETTINGS['message_number_per_page'] * page limit = HOME_SETTINGS['message_number_per_page'] if category == MessageTopic.CHAT_MESSAGE_NEW: message_list = yield ChatMessageDocument.get_chat_message_list( self.current_user['_id'], skip=skip, limit=limit ) else: message_list = yield MessageDocument.get_message_list( self.current_user['_id'], message_topic=category, skip=skip, limit=limit ) if category == MessageTopic._FRIENDS_DYNAMIC: path = 'message-friends-dynamic-list-item.html' elif category == MessageTopic._COMMENT_AND_REPLY: path = 'message-comment-and-reply-list-item.html' elif category == MessageTopic.AT: path = 'message-at-list-item.html' elif category == MessageTopic.CHAT_MESSAGE_NEW: path = 'message-chat-message-list-item.html' elif category == MessageTopic.FRIEND_REQUEST_NEW: path = 'message-friend-request-list-item.html' elif category == MessageTopic.LIKE: path = 'message-like-list-item.html' path = os.path.join("home/template/message", path) html = ''.join( self.render_string( path, message=message, MessageTopic=MessageTopic ) for message in message_list ) self.write_json({'html': html, 'page': page + 1})
def message_handler(message): '''向用户发送消息''' from app.message.document import MessageDocument message = MessageDocument.get_collection(pymongo=True).find_one( {'_id': ObjectId(message.body)}) if not message: return True recipient_id = message['recipient'].id topic = MessageTopic.message_type2topic(message['message_type']) _reponse_browser_callback(recipient_id, topic, message) return True
def post(self): form = FriendRequestForm(self.request.arguments) if not form.validate(): raise HTTPError(404) user_id = form.user_id.data yield MessageDocument.remove({ 'sender': DBRef(UserDocument.meta['collection'], ObjectId(user_id)), 'recipient': DBRef(UserDocument.meta['collection'], ObjectId(self.current_user['_id'])), 'message_type': MessageTopic.FRIEND_REQUEST_NEW })
def post(self): form = FriendRequestForm(self.request.arguments) if not form.validate(): raise HTTPError(404) user_id = form.user_id.data yield MessageDocument.remove({ 'sender': DBRef( UserDocument.meta['collection'], ObjectId(user_id) ), 'recipient': DBRef( UserDocument.meta['collection'], ObjectId(self.current_user['_id']) ), 'message_type': MessageTopic.FRIEND_REQUEST_NEW})
def message_handler(message): '''向用户发送消息''' from app.message.document import MessageDocument message = MessageDocument.get_collection(pymongo=True).find_one( {'_id': ObjectId(message.body)} ) if not message: return True recipient_id = message['recipient'].id topic = MessageTopic.message_type2topic(message['message_type']) _reponse_browser_callback(recipient_id, topic, message) return True
def remove_one(query): like = yield TopicLikeDocument.find_one(query) if like: yield TopicLikeDocument.remove(query) like_times = yield TopicLikeDocument.get_like_times( like['topic'].id ) yield TopicDocument.update( {'_id': ObjectId(like['topic'].id)}, {'$set': {'like_times': like_times}}) yield MessageDocument.remove({ 'data': DBRef(TopicLikeDocument.meta['collection'], ObjectId(like['_id'])) }) raise gen.Return()
def remove_one(query): like = yield ShareLikeDocument.find_one(query) if like: yield ShareLikeDocument.remove(query) like_times = yield ShareLikeDocument.get_like_times( like['share'].id) yield ShareDocument.update({'_id': ObjectId(like['share'].id)}, {'$set': { 'like_times': like_times }}) yield MessageDocument.remove({ 'data': DBRef(ShareLikeDocument.meta['collection'], ObjectId(like['_id'])) }) raise gen.Return()
def get(self, user_id=None): user_id = user_id or self.current_user["_id"] kwargs = yield self.get_header_arguments(user_id) if not kwargs['can_seen']: self.render('profile/template/profile-visitor.html', **kwargs) else: messages_func = LeaveMessageDocument.get_leave_message_list leave_message_list = yield messages_func( user_id, self.current_user['_id'], limit=PROFILE_SETTINGS['leave_message_number_per_page']) kwargs.update({'leave_message_list': leave_message_list}) if ObjectId(user_id) == ObjectId(self.current_user['_id']): yield MessageDocument.set_read(user_id, MessageTopic.LEAVE_MESSAGE_NEW) self.render('profile/template/leavemessage/leavemessage.html', **kwargs)
def delete_one(comment_id): comment = yield ShareCommentDocument.find_one( {'_id': ObjectId(comment_id)}) if comment: yield ShareCommentDocument.remove({'_id': ObjectId(comment_id)}) comment_times = yield ShareCommentDocument.get_comment_times( comment['share'].id) yield ShareDocument.update( {'_id': ObjectId(comment['share'].id)}, {'$set': { 'comment_times': comment_times }}) yield MessageDocument.remove({ 'data': DBRef(ShareCommentDocument.meta['collection'], ObjectId(comment_id)) }) raise gen.Return()
def delete_one(comment_id): comment = yield TopicCommentDocument.find_one({ '_id': ObjectId(comment_id) }) if comment: yield TopicCommentDocument.remove({'_id': ObjectId(comment_id)}) comment_times = yield TopicCommentDocument.get_comment_times( comment['topic'].id ) yield TopicDocument.update( {'_id': ObjectId(comment['topic'].id)}, {'$set': {'comment_times': comment_times}} ) yield MessageDocument.remove({ 'data': DBRef(TopicCommentDocument.meta['collection'], ObjectId(comment_id)) }) raise gen.Return()
def post(self): '''评论状态''' response_data ={} form = StatusCommentNewForm(self.request.arguments) if form.validate(): status_id = form.status_id.data content = form.content.data replyeder_id = form.replyeder_id.data status = yield StatusDocument.find_one({ '_id': ObjectId(status_id) }) if not status: raise HTTPError(404) can_see = yield StatusDocument.can_see( status, self.current_user['_id'] ) if not can_see: raise HTTPError(404) replyeder = None if replyeder_id: replyeder = yield UserDocument.find_one({ '_id': ObjectId(replyeder_id) }) if not replyeder: raise HTTPError(404) is_friend = yield FriendDocument.is_friend( self.current_user['_id'], replyeder_id ) if not is_friend: raise HTTPError(404) now = datetime.now() document = { 'status': DBRef( StatusDocument.meta['collection'], ObjectId(status['_id']) ), 'author': DBRef( UserDocument.meta['collection'], ObjectId(self.current_user['_id']) ), 'comment_time': now, 'content': content } if replyeder: document.update({ 'replyeder': DBRef( UserDocument.meta['collection'], ObjectId(replyeder_id) ) }) comment_id = yield StatusCommentDocument.insert_one(document) if replyeder: recipient_id = replyeder_id message_type = 'reply:status' message_topic = MessageTopic.REPLY else: recipient_id = status['author'].id message_type = 'comment:status' message_topic = MessageTopic.COMMENT if ObjectId(self.current_user['_id']) != ObjectId(recipient_id): message = { 'sender': DBRef( UserDocument.meta['collection'], ObjectId(self.current_user['_id']) ), 'recipient': DBRef( UserDocument.meta['collection'], ObjectId(recipient_id) ), 'message_type': message_type, 'time': now, 'read': False, 'data': DBRef( StatusCommentDocument.meta['collection'], ObjectId(comment_id) ) } message_id = yield MessageDocument.insert(message) WriterManager.pub(message_topic, message_id) comment = yield StatusCommentDocument.get_comment(comment_id) html = self.render_string( 'home/template/status/status-comment-list-item.html', status=status, status_comment=comment ) response_data.update({'html': html}) else: for field in form.errors: response_data.update({'error': form.errors[field][0]}) break self.write_json(response_data)
def post(self): response_data = {} form = TopicLikeForm(self.request.arguments) if not form.validate(): raise HTTPError(404) topic_id = form.topic_id.data topic = yield TopicDocument.find_one({'_id': ObjectId(topic_id)}) if not topic: raise HTTPError(404) can_afford = yield UserDocument.can_afford( self.current_user['_id'], WEALTH_SETTINGS['like'] ) if not can_afford and str( self.current_user['_id']) != str(topic['author'].id): response_data.update({'error': '金币不足!'}) topic_dbref = DBRef( TopicDocument.meta['collection'], ObjectId(topic_id) ) liker_dbref = DBRef( UserDocument.meta['collection'], ObjectId(self.current_user['_id']) ) document = {'topic': topic_dbref, 'liker': liker_dbref} liked = yield TopicLikeDocument.is_liked( topic_id, self.current_user['_id'] ) if not liked and not response_data: now = datetime.now() document.update({'like_time': now}) like_id = yield TopicLikeDocument.insert_one(document) if str(self.current_user['_id']) != str(topic['author'].id): document = { 'user': DBRef( UserDocument.meta['collection'], ObjectId(self.current_user['_id']) ), 'activity_type': UserActivityDocument.LIKE, 'time': now, 'data': DBRef( TopicLikeDocument.meta['collection'], ObjectId(like_id) ) } activity_id = yield UserActivityDocument.insert(document) # 赞者 document = { 'user': DBRef( UserDocument.meta['collection'], ObjectId(self.current_user['_id']) ), 'in_out_type': WealthRecordDocument.OUT, 'activity': DBRef( UserActivityDocument.meta['collection'], ObjectId(activity_id) ), 'quantity': WEALTH_SETTINGS['like'], 'time': now } yield WealthRecordDocument.insert(document) yield UserDocument.update_wealth( self.current_user['_id'], -WEALTH_SETTINGS['like'] ) # 被赞者 document = { 'user': DBRef( UserDocument.meta['collection'], ObjectId(topic['author'].id) ), 'in_out_type': WealthRecordDocument.IN, 'activity': DBRef( UserActivityDocument.meta['collection'], ObjectId(activity_id) ), 'quantity': WEALTH_SETTINGS['like'], 'time': now } yield WealthRecordDocument.insert(document) yield UserDocument.update_wealth( topic['author'].id, WEALTH_SETTINGS['like'] ) document = { 'sender': DBRef( UserDocument.meta['collection'], ObjectId(self.current_user['_id']) ), 'recipient': DBRef( UserDocument.meta['collection'], ObjectId(topic['author'].id) ), 'message_type': 'like:topic', 'time': now, 'read': False, 'data': DBRef( TopicLikeDocument.meta['collection'], ObjectId(like_id) ) } message_id = yield MessageDocument.insert(document) WriterManager.pub(MessageTopic.LIKE, message_id) like_times = yield TopicLikeDocument.get_like_times(topic_id) response_data.update({'like_times': like_times}) self.write_json(response_data)
def post(self): form = ShareLikeForm(self.request.arguments) if not form.validate(): raise HTTPError(404) response_data = {} share_id = form.share_id.data share = yield ShareDocument.find_one({'_id': ObjectId(share_id)}) if not share: raise HTTPError(404) can_afford = yield UserDocument.can_afford(self.current_user['_id'], WEALTH_SETTINGS['like']) if (not can_afford and str(self.current_user['_id']) != str(share['uploader'].id)): response_data.update({'error': '金币不足!'}) share_dbref = DBRef(ShareDocument.meta['collection'], ObjectId(share_id)) liker_dbref = DBRef(UserDocument.meta['collection'], ObjectId(self.current_user['_id'])) document = {'share': share_dbref, 'liker': liker_dbref} liked = yield ShareLikeDocument.is_liked(share_id, self.current_user['_id']) if not liked and not response_data: now = datetime.now() document.update({'like_time': now}) like_id = yield ShareLikeDocument.insert_one(document) if str(self.current_user['_id']) != str(share['uploader'].id): activity = { 'user': DBRef(UserDocument.meta['collection'], ObjectId(self.current_user['_id'])), 'activity_type': UserActivityDocument.LIKE, 'time': now, 'data': DBRef(ShareLikeDocument.meta['collection'], ObjectId(like_id)) } activity_id = yield UserActivityDocument.insert(activity) # 赞者 wealth = { 'user': DBRef(UserDocument.meta['collection'], ObjectId(self.current_user['_id'])), 'in_out_type': WealthRecordDocument.OUT, 'activity': DBRef(UserActivityDocument.meta['collection'], ObjectId(activity_id)), 'quantity': WEALTH_SETTINGS['like'], 'time': now } yield WealthRecordDocument.insert(wealth) yield UserDocument.update_wealth(self.current_user['_id'], -WEALTH_SETTINGS['like']) # 被赞者 wealth = { 'user': DBRef(UserDocument.meta['collection'], ObjectId(share['uploader'].id)), 'in_out_type': WealthRecordDocument.IN, 'activity': DBRef(UserActivityDocument.meta['collection'], ObjectId(activity_id)), 'quantity': WEALTH_SETTINGS['like'], 'time': now } yield WealthRecordDocument.insert(wealth) yield UserDocument.update_wealth(share['uploader'].id, WEALTH_SETTINGS['like']) message = { 'sender': DBRef(UserDocument.meta['collection'], ObjectId(self.current_user['_id'])), 'recipient': DBRef(UserDocument.meta['collection'], ObjectId(share['uploader'].id)), 'message_type': 'like:share', 'time': now, 'read': False, 'data': DBRef(ShareLikeDocument.meta['collection'], ObjectId(like_id)) } message_id = yield MessageDocument.insert(message) WriterManager.pub(MessageTopic.LIKE, str(message_id)) like_times = yield ShareLikeDocument.get_like_times(share_id) response_data.update({'like_times': like_times}) self.finish(json.dumps(response_data))
def post(self): form = ShareCommentNewForm(self.request.arguments) if not form.validate(): raise HTTPError(404) response_data = {} content = form.content.data share_id = form.share_id.data anonymous = form.anonymous.data replyeder_id = form.replyeder_id.data replyeder = None if replyeder_id: replyeder = yield UserDocument.find_one( {'_id': ObjectId(replyeder_id)}) if (not replyeder or anonymous or self.current_user['_id'] == replyeder['_id']): raise HTTPError(404) share = yield ShareDocument.find_one({'_id': ObjectId(share_id)}) if not share: raise HTTPError(404) if not response_data: now = datetime.now() document = { 'author': DBRef(UserDocument.meta['collection'], ObjectId(self.current_user['_id'])), 'share': DBRef(ShareDocument.meta['collection'], ObjectId(share['_id'])), 'comment_time': now, 'content': content, 'anonymous': anonymous } if replyeder: document.update({ 'replyeder': DBRef(UserDocument.meta['collection'], ObjectId(replyeder_id)) }) comment_id = yield ShareCommentDocument.insert_one(document) activity = { 'user': DBRef(UserDocument.meta['collection'], ObjectId(self.current_user['_id'])), 'activity_type': UserActivityDocument.COMMENT, 'time': now, 'data': DBRef(ShareCommentDocument.meta['collection'], ObjectId(comment_id)) } yield UserActivityDocument.insert(activity) if replyeder: recipient_id = replyeder_id message_type = 'reply:share' message_share = MessageTopic.REPLY else: recipient_id = share['uploader'].id message_type = 'comment:share' message_share = MessageTopic.COMMENT if (str(self.current_user['_id']) != str(recipient_id) and not anonymous): message = { 'sender': DBRef(UserDocument.meta['collection'], ObjectId(self.current_user['_id'])), 'recipient': DBRef(UserDocument.meta['collection'], ObjectId(recipient_id)), 'message_type': message_type, 'time': now, 'read': False, 'data': DBRef(ShareCommentDocument.meta['collection'], ObjectId(comment_id)) } message_id = yield MessageDocument.insert(message) WriterManager.pub(message_share, message_id) comment_times = yield ShareCommentDocument.get_comment_times( share_id) document.update({ '_id': ObjectId(comment_id), 'author': self.current_user, 'floor': comment_times }) if replyeder: document.update({'replyeder': replyeder}) item = self.render_string( 'share/template/share-comment-list-item.html', comment=document) response_data.update({'item': item}) self.finish(json.dumps(response_data))
def post(self): form = LeaveMessageNewForm(self.request.arguments) if not form.validate(): raise HTTPError(404) user_id = form.user_id.data private = form.private.data content = form.content.data replyeder_id = form.replyeder_id.data user_setting = yield UserSettingDocument.get_user_setting(user_id) if not user_setting['enable_leaving_message']: raise HTTPError(404) replyeder = None if replyeder_id: replyeder = yield UserDocument.find_one( {'_id': ObjectId(replyeder_id)}) if (not replyeder or ObjectId(user_id) != ObjectId(self.current_user['_id'])): raise HTTPError(404) user = yield UserDocument.find_one({'_id': ObjectId(user_id)}) if not user: raise HTTPError(404) now = datetime.now() document = { 'user': DBRef(UserDocument.meta['collection'], ObjectId(user_id)), 'author': DBRef(UserDocument.meta['collection'], ObjectId(self.current_user['_id'])), 'private': private, 'content': content, 'leave_time': now } if replyeder: document.update({ 'replyeder': DBRef(UserDocument.meta['collection'], ObjectId(replyeder_id)) }) leave_message_id = yield LeaveMessageDocument.insert(document) if replyeder: recipient_id = replyeder_id message_type = 'reply:leavemessage' message_topic = MessageTopic.REPLY else: recipient_id = user_id message_type = MessageTopic.LEAVE_MESSAGE_NEW message_topic = MessageTopic.LEAVE_MESSAGE_NEW if ObjectId(self.current_user['_id']) != ObjectId(recipient_id): message = { 'sender': DBRef(UserDocument.meta['collection'], ObjectId(self.current_user['_id'])), 'recipient': DBRef(UserDocument.meta['collection'], ObjectId(recipient_id)), 'message_type': message_type, 'time': now, 'data': DBRef(LeaveMessageDocument.meta['collection'], ObjectId(leave_message_id)) } message_id = yield MessageDocument.insert(message) WriterManager.pub(message_topic, message_id) number_func = LeaveMessageDocument.get_leave_message_number leave_message_number = yield number_func(user_id, self.current_user['_id']) document.update({ '_id': ObjectId(leave_message_id), 'floor': leave_message_number }) if replyeder: document.update({'replyeder': replyeder}) leave_message = yield LeaveMessageDocument.translate_dbref_in_document( document) html = self.render_string( 'profile/template/leavemessage/leavemessage-list-item.html', leave_message=leave_message, user=user) self.finish(json.dumps({'html': html}))
def post(self): form = LeaveMessageNewForm(self.request.arguments) if not form.validate(): raise HTTPError(404) user_id = form.user_id.data private = form.private.data content = form.content.data replyeder_id = form.replyeder_id.data user_setting = yield UserSettingDocument.get_user_setting(user_id) if not user_setting['enable_leaving_message']: raise HTTPError(404) replyeder = None if replyeder_id: replyeder = yield UserDocument.find_one({ '_id': ObjectId(replyeder_id) }) if (not replyeder or ObjectId(user_id) != ObjectId(self.current_user['_id'])): raise HTTPError(404) user = yield UserDocument.find_one({'_id': ObjectId(user_id)}) if not user: raise HTTPError(404) now = datetime.now() document = { 'user': DBRef( UserDocument.meta['collection'], ObjectId(user_id) ), 'author': DBRef( UserDocument.meta['collection'], ObjectId(self.current_user['_id']) ), 'private': private, 'content': content, 'leave_time': now } if replyeder: document.update({ 'replyeder': DBRef( UserDocument.meta['collection'], ObjectId(replyeder_id) ) }) leave_message_id = yield LeaveMessageDocument.insert(document) if replyeder: recipient_id = replyeder_id message_type = 'reply:leavemessage' message_topic = MessageTopic.REPLY else: recipient_id = user_id message_type = MessageTopic.LEAVE_MESSAGE_NEW message_topic = MessageTopic.LEAVE_MESSAGE_NEW if ObjectId(self.current_user['_id']) != ObjectId(recipient_id): message = { 'sender': DBRef( UserDocument.meta['collection'], ObjectId(self.current_user['_id']) ), 'recipient': DBRef( UserDocument.meta['collection'], ObjectId(recipient_id) ), 'message_type': message_type, 'time': now, 'data': DBRef( LeaveMessageDocument.meta['collection'], ObjectId(leave_message_id) ) } message_id = yield MessageDocument.insert(message) WriterManager.pub(message_topic, message_id) number_func = LeaveMessageDocument.get_leave_message_number leave_message_number = yield number_func( user_id, self.current_user['_id'] ) document.update({ '_id': ObjectId(leave_message_id), 'floor': leave_message_number }) if replyeder: document.update({ 'replyeder': replyeder }) leave_message = yield LeaveMessageDocument.translate_dbref_in_document( document ) html = self.render_string( 'profile/template/leavemessage/leavemessage-list-item.html', leave_message=leave_message, user=user ) self.write_json({'html': html})
def post(self): response_data = {} form = StatusNewForm(self.request.arguments) if form.validate(): content = form.content.data n = len(content) if n > HOME_SETTINGS['status_max_length']: response_data.update({ 'error': ( '状态内容不能超过%s字' % HOME_SETTINGS['status_max_length'] ) }) elif n <= 0 and not ( self.request.files and 'picture' in self.request.files): response_data.update({'error': '请输入文字内容或者照片'}) else: picture = None if self.request.files and 'picture' in self.request.files: picture = self.request.files['picture'][0] image_types = [ 'image/jpg', 'image/png', 'image/jpeg', 'image/gif' ] if picture['content_type'].lower() not in image_types: response_data.update({ 'error': '请上传jpg/png/gif格式的图片' }) if 'error' not in response_data: now = datetime.now() document = { 'author': DBRef( UserDocument.meta['collection'], self.current_user['_id'] ), 'publish_time': now, 'content': content } status_id = yield StatusDocument.insert(document) friends = yield FriendDocument.get_reached_friends( self.current_user['_id'] ) message_list = [] for friend in friends: document = { 'sender': DBRef( UserDocument.meta['collection'], ObjectId(self.current_user['_id']) ), 'recipient': DBRef( UserDocument.meta['collection'], ObjectId(friend['_id']) ), 'message_type': MessageTopic.STATUS_NEW, 'time': now, 'read': False, 'data': DBRef( StatusDocument.meta['collection'], ObjectId(status_id) ) } message_id = yield MessageDocument.insert(document) message_list.append(str(message_id)) if message_list: WriterManager.mpub( MessageTopic.STATUS_NEW, message_list ) if picture is not None: try: image = Image.open(StringIO(picture['body'])) except: raise HTTPError(404) try: content_type = picture[ 'content_type' ].split('/')[-1].upper() except: content_type = 'JPEG' document = { 'status': DBRef( StatusDocument.meta['collection'], ObjectId(status_id) ), 'name': picture['filename'], 'content_type': content_type, 'upload_time': datetime.now() } width = 1024 if image.size[0] > width: height = width * 1.0 * image.size[1] / image.size[0] image = image.resize( map(int, (width, height)), Image.ANTIALIAS ) output = StringIO() image.save(output, content_type, quality=100) document.update({'body': Binary(output.getvalue())}) output.close() thumbnail_width = 200 thumbnail_height = ( thumbnail_width * 1.0 * image.size[1] / image.size[0] ) output = StringIO() image = image.resize( map(int, (thumbnail_width, thumbnail_height)), Image.ANTIALIAS ) image.save(output, content_type, quality=100) document.update({ 'thumbnail': Binary(output.getvalue()) }) output.close() yield StatusPhotoDocument.insert(document) status = yield StatusDocument.get_status( status_id, self.current_user['_id'] ) html = self.render_string( 'home/template/status/status-list-item.html', status=status ) response_data.update({'html': html}) else: for field in form.errors: response_data.update({'error': form.errors[field][0]}) break self.write_json(response_data)
def post(self): form = TopicCommentNewForm(self.request.arguments) if not form.validate(): raise HTTPError(404) response_data = {} content = form.content.data topic_id = form.topic_id.data anonymous = form.anonymous.data replyeder_id = form.replyeder_id.data replyeder = None if replyeder_id: replyeder = yield UserDocument.find_one({ '_id': ObjectId(replyeder_id) }) if not replyeder: raise HTTPError(404) if anonymous or self.current_user['_id'] == replyeder['_id']: raise HTTPError(404) topic = yield TopicDocument.find_one({'_id': ObjectId(topic_id)}) if not topic: raise HTTPError(404) now = datetime.now() document = { 'author': DBRef( UserDocument.meta['collection'], ObjectId(self.current_user['_id']) ), 'topic': DBRef( TopicDocument.meta['collection'], ObjectId(topic['_id']) ), 'content': content, 'anonymous': anonymous } existed = yield TopicCommentDocument.find_one(document) if existed and (now - existed['comment_time'] < timedelta(minutes=1)): response_data.update({'error': '请不要重复评论!'}) else: document.update({'comment_time': now}) if not response_data: if replyeder: document.update({ 'replyeder': DBRef( UserDocument.meta['collection'], ObjectId(replyeder_id) ) }) comment_id = yield TopicCommentDocument.insert_one(document) activity = { 'user': DBRef( UserDocument.meta['collection'], ObjectId(self.current_user['_id']) ), 'activity_type': UserActivityDocument.COMMENT, 'time': now, 'data': DBRef( TopicCommentDocument.meta['collection'], ObjectId(comment_id) ) } yield UserActivityDocument.insert(activity) if replyeder: recipient_id = replyeder_id message_type = 'reply:topic' message_topic = MessageTopic.REPLY else: recipient_id = topic['author'].id message_type = 'comment:topic' message_topic = MessageTopic.COMMENT if (str(self.current_user['_id']) != str(recipient_id) and not anonymous and not (message_topic == MessageTopic.COMMENT and topic['anonymous'])): message = { 'sender': DBRef( UserDocument.meta['collection'], ObjectId(self.current_user['_id']) ), 'recipient': DBRef( UserDocument.meta['collection'], ObjectId(recipient_id) ), 'message_type': message_type, 'time': now, 'read': False, 'data': DBRef( TopicCommentDocument.meta['collection'], ObjectId(comment_id) ) } message_id = yield MessageDocument.insert(message) WriterManager.pub(message_topic, message_id) comment_times = yield TopicCommentDocument.get_comment_times( topic_id ) document.update({ '_id': ObjectId(comment_id), 'author': self.current_user, 'floor': comment_times }) if replyeder: document.update({'replyeder': replyeder}) item = self.render_string( 'community/template/topic-comment-list-item.html', comment=document ) response_data.update({'item': item}) self.write_json(response_data)
def post(self): '''点赞''' form = StatusLikeForm(self.request.arguments) if not form.validate(): raise HTTPError(404) status_id = form.status_id.data status = yield StatusDocument.find_one({'_id': ObjectId(status_id)}) if not status: raise HTTPError(404) status_dbref = DBRef( StatusDocument.meta['collection'], ObjectId(status_id) ) liker_dbref = DBRef( UserDocument.meta['collection'], ObjectId(self.current_user['_id']) ) document = { 'status': status_dbref, 'liker': liker_dbref } liked = yield StatusLikeDocument.is_liked( status_id, self.current_user['_id'] ) if not liked: now = datetime.now() document.update({'like_time': now}) like_id = yield StatusLikeDocument.insert_one(document) if str(self.current_user['_id']) != str(status['author'].id): document = { 'sender': DBRef( UserDocument.meta['collection'], ObjectId(self.current_user['_id']) ), 'recipient': DBRef( UserDocument.meta['collection'], ObjectId(status['author'].id) ), 'message_type': 'like:status', 'time': now, 'read': False, 'data': DBRef( StatusLikeDocument.meta['collection'], ObjectId(like_id) ) } message_id = yield MessageDocument.insert(document) WriterManager.pub(MessageTopic.LIKE, message_id) like_times = yield StatusLikeDocument.get_like_times(status_id) like_list = yield StatusLikeDocument.get_like_list( status['_id'], self.current_user['_id'] ) likers = '、'.join([like['liker']['name'] for like in like_list]) self.write_json({ 'like_times': like_times, 'likers': likers })
def post(self): form = ShareLikeForm(self.request.arguments) if not form.validate(): raise HTTPError(404) response_data = {} share_id = form.share_id.data share = yield ShareDocument.find_one({ '_id': ObjectId(share_id) }) if not share: raise HTTPError(404) can_afford = yield UserDocument.can_afford( self.current_user['_id'], WEALTH_SETTINGS['like'] ) if (not can_afford and str(self.current_user['_id']) != str(share['uploader'].id)): response_data.update({'error': '金币不足!'}) share_dbref = DBRef( ShareDocument.meta['collection'], ObjectId(share_id) ) liker_dbref = DBRef( UserDocument.meta['collection'], ObjectId(self.current_user['_id']) ) document = { 'share': share_dbref, 'liker': liker_dbref } liked = yield ShareLikeDocument.is_liked( share_id, self.current_user['_id'] ) if not liked and not response_data: now = datetime.now() document.update({ 'like_time': now }) like_id = yield ShareLikeDocument.insert_one(document) if str(self.current_user['_id']) != str(share['uploader'].id): activity = { 'user': DBRef( UserDocument.meta['collection'], ObjectId(self.current_user['_id']) ), 'activity_type': UserActivityDocument.LIKE, 'time': now, 'data': DBRef( ShareLikeDocument.meta['collection'], ObjectId(like_id) ) } activity_id = yield UserActivityDocument.insert(activity) # 赞者 wealth = { 'user': DBRef( UserDocument.meta['collection'], ObjectId(self.current_user['_id']) ), 'in_out_type': WealthRecordDocument.OUT, 'activity': DBRef( UserActivityDocument.meta['collection'], ObjectId(activity_id) ), 'quantity': WEALTH_SETTINGS['like'], 'time': now } yield WealthRecordDocument.insert(wealth) yield UserDocument.update_wealth( self.current_user['_id'], -WEALTH_SETTINGS['like'] ) # 被赞者 wealth = { 'user': DBRef( UserDocument.meta['collection'], ObjectId(share['uploader'].id) ), 'in_out_type': WealthRecordDocument.IN, 'activity': DBRef( UserActivityDocument.meta['collection'], ObjectId(activity_id) ), 'quantity': WEALTH_SETTINGS['like'], 'time': now } yield WealthRecordDocument.insert(wealth) yield UserDocument.update_wealth( share['uploader'].id, WEALTH_SETTINGS['like'] ) message = { 'sender': DBRef( UserDocument.meta['collection'], ObjectId(self.current_user['_id']) ), 'recipient': DBRef( UserDocument.meta['collection'], ObjectId(share['uploader'].id) ), 'message_type': 'like:share', 'time': now, 'read': False, 'data': DBRef( ShareLikeDocument.meta['collection'], ObjectId(like_id) ) } message_id = yield MessageDocument.insert(message) WriterManager.pub(MessageTopic.LIKE, str(message_id)) like_times = yield ShareLikeDocument.get_like_times(share_id) response_data.update({'like_times': like_times}) self.write_json(response_data)
def post(self): form = ShareCommentNewForm(self.request.arguments) if not form.validate(): raise HTTPError(404) response_data = {} content = form.content.data share_id = form.share_id.data anonymous = form.anonymous.data replyeder_id = form.replyeder_id.data replyeder = None if replyeder_id: replyeder = yield UserDocument.find_one({ '_id': ObjectId(replyeder_id) }) if (not replyeder or anonymous or self.current_user['_id'] == replyeder['_id']): raise HTTPError(404) share = yield ShareDocument.find_one({'_id': ObjectId(share_id)}) if not share: raise HTTPError(404) if not response_data: now = datetime.now() document = { 'author': DBRef( UserDocument.meta['collection'], ObjectId(self.current_user['_id']) ), 'share': DBRef( ShareDocument.meta['collection'], ObjectId(share['_id']) ), 'comment_time': now, 'content': content, 'anonymous': anonymous } if replyeder: document.update({ 'replyeder': DBRef( UserDocument.meta['collection'], ObjectId(replyeder_id) ) }) comment_id = yield ShareCommentDocument.insert_one(document) activity = { 'user': DBRef( UserDocument.meta['collection'], ObjectId(self.current_user['_id']) ), 'activity_type': UserActivityDocument.COMMENT, 'time': now, 'data': DBRef( ShareCommentDocument.meta['collection'], ObjectId(comment_id) ) } yield UserActivityDocument.insert(activity) if replyeder: recipient_id = replyeder_id message_type = 'reply:share' message_share = MessageTopic.REPLY else: recipient_id = share['uploader'].id message_type = 'comment:share' message_share = MessageTopic.COMMENT if (str(self.current_user['_id']) != str(recipient_id) and not anonymous): message = { 'sender': DBRef( UserDocument.meta['collection'], ObjectId(self.current_user['_id']) ), 'recipient': DBRef( UserDocument.meta['collection'], ObjectId(recipient_id) ), 'message_type': message_type, 'time': now, 'read': False, 'data': DBRef( ShareCommentDocument.meta['collection'], ObjectId(comment_id) ) } message_id = yield MessageDocument.insert(message) WriterManager.pub(message_share, message_id) comment_times = yield ShareCommentDocument.get_comment_times( share_id ) document.update({ '_id': ObjectId(comment_id), 'author': self.current_user, 'floor': comment_times }) if replyeder: document.update({'replyeder': replyeder}) item = self.render_string( 'share/template/share-comment-list-item.html', comment=document ) response_data.update({'item': item}) self.write_json(response_data)
def post(self): response_data = {} form = StatusNewForm(self.request.arguments) if form.validate(): content = form.content.data n = len(content) if n > HOME_SETTINGS['status_max_length']: response_data.update({ 'error': ( '状态内容不能超过%s字' % HOME_SETTINGS['status_max_length'] ) }) elif n <= 0 and not ( self.request.files and 'picture' in self.request.files): response_data.update({'error': '请输入文字内容或者照片'}) else: picture = None if self.request.files and 'picture' in self.request.files: picture = self.request.files['picture'][0] image_types = [ 'image/jpg', 'image/png', 'image/jpeg', 'image/gif' ] if picture['content_type'].lower() not in image_types: response_data.update({ 'error': '请上传jpg/png/gif格式的图片' }) if 'error' not in response_data: now = datetime.now() document = { 'author': DBRef( UserDocument.meta['collection'], self.current_user['_id'] ), 'publish_time': now, 'content': content } status_id = yield StatusDocument.insert(document) friends = yield FriendDocument.get_reached_friends( self.current_user['_id'] ) message_list = [] for friend in friends: document = { 'sender': DBRef( UserDocument.meta['collection'], ObjectId(self.current_user['_id']) ), 'recipient': DBRef( UserDocument.meta['collection'], ObjectId(friend['_id']) ), 'message_type': MessageTopic.STATUS_NEW, 'time': now, 'read': False, 'data': DBRef( StatusDocument.meta['collection'], ObjectId(status_id) ) } message_id = yield MessageDocument.insert(document) message_list.append(str(message_id)) if message_list: WriterManager.mpub( MessageTopic.STATUS_NEW, message_list ) if picture is not None: try: image = Image.open(StringIO(picture['body'])) except: raise HTTPError(404) try: content_type = picture[ 'content_type' ].split('/')[-1].upper() except: content_type = 'JPEG' document = { 'status': DBRef( StatusDocument.meta['collection'], ObjectId(status_id) ), 'name': picture['filename'], 'content_type': content_type, 'upload_time': datetime.now() } width = 1024 if image.size[0] > width: height = width * 1.0 * image.size[1] / image.size[0] image = image.resize( map(int, (width, height)), Image.ANTIALIAS ) output = StringIO() image.save(output, content_type, quality=100) document.update({'body': Binary(output.getvalue())}) output.close() thumbnail_width = 200 thumbnail_height = ( thumbnail_width * 1.0 * image.size[1] / image.size[0] ) output = StringIO() image = image.resize( map(int, (thumbnail_width, thumbnail_height)), Image.ANTIALIAS ) image.save(output, content_type, quality=100) document.update({ 'thumbnail': Binary(output.getvalue()) }) output.close() yield StatusPhotoDocument.insert(document) status = yield StatusDocument.get_status( status_id, self.current_user['_id'] ) html = self.render_string( 'home/template/status/status-list-item.html', status=status ) response_data.update({'html': html}) else: for field in form.errors: response_data.update({'error': form.errors[field][0]}) break self.finish(json.dumps(response_data))
def post(self): '''评论状态''' response_data ={} form = StatusCommentNewForm(self.request.arguments) if form.validate(): status_id = form.status_id.data content = form.content.data replyeder_id = form.replyeder_id.data status = yield StatusDocument.find_one({ '_id': ObjectId(status_id) }) if not status: raise HTTPError(404) can_see = yield StatusDocument.can_see( status, self.current_user['_id'] ) if not can_see: raise HTTPError(404) replyeder = None if replyeder_id: replyeder = yield UserDocument.find_one({ '_id': ObjectId(replyeder_id) }) if not replyeder: raise HTTPError(404) is_friend = yield FriendDocument.is_friend( self.current_user['_id'], replyeder_id ) if not is_friend: raise HTTPError(404) now = datetime.now() document = { 'status': DBRef( StatusDocument.meta['collection'], ObjectId(status['_id']) ), 'author': DBRef( UserDocument.meta['collection'], ObjectId(self.current_user['_id']) ), 'comment_time': now, 'content': content } if replyeder: document.update({ 'replyeder': DBRef( UserDocument.meta['collection'], ObjectId(replyeder_id) ) }) comment_id = yield StatusCommentDocument.insert_one(document) if replyeder: recipient_id = replyeder_id message_type = 'reply:status' message_topic = MessageTopic.REPLY else: recipient_id = status['author'].id message_type = 'comment:status' message_topic = MessageTopic.COMMENT if ObjectId(self.current_user['_id']) != ObjectId(recipient_id): message = { 'sender': DBRef( UserDocument.meta['collection'], ObjectId(self.current_user['_id']) ), 'recipient': DBRef( UserDocument.meta['collection'], ObjectId(recipient_id) ), 'message_type': message_type, 'time': now, 'read': False, 'data': DBRef( StatusCommentDocument.meta['collection'], ObjectId(comment_id) ) } message_id = yield MessageDocument.insert(message) WriterManager.pub(message_topic, message_id) comment = yield StatusCommentDocument.get_comment(comment_id) html = self.render_string( 'home/template/status/status-comment-list-item.html', status=status, status_comment=comment ) response_data.update({'html': html}) else: for field in form.errors: response_data.update({'error': form.errors[field][0]}) break self.finish(json.dumps(response_data))
def send_has_unread_message_email_handler(message): '''如果用户不在线就发送邮件''' from young.handler import BaseHandler from app.user.document import UserDocument from app.message.document import MessageDocument message = MessageDocument.get_collection(pymongo=True).find_one( {'_id': ObjectId(message.body)} ) if not message: return True recipient_id = message['recipient'].id topic = MessageTopic.message_type2topic(message['message_type']) recipient = UserDocument.get_user_sync(recipient_id) if recipient and recipient['activated']: message = BaseHandler.translate_dbref_in_document(message) if 'data' in message: message['data'] = BaseHandler.translate_dbref_in_document( message['data'], depth=2 ) kwargs = { 'message_topic': topic, 'message': message, 'MessageTopic': MessageTopic, 'handler': BaseHandler } root = os.path.dirname(os.path.dirname( os.path.dirname(os.path.abspath(__file__)) )) path = os.path.join(root, 'app/message/template') loader = template.Loader(path) html = loader.load("message.html").generate(**kwargs) soup = BeautifulSoup(html, "html.parser") link_list = soup.find_all('a') for link in link_list: new_link = link if link['href'].startswith('/'): new_link['href'] = EMAIL_SETTINGS['url'] + link['href'] link.replace_with(new_link) img_list = soup.find_all('img') for img in img_list: new_img = img if img['src'].startswith('/'): new_img['src'] = EMAIL_SETTINGS['url'] + img['src'] img.replace_with(new_img) body = ( '{} <a href="{}/setting/notification">' '关闭邮件提醒</a>' ).format(soup.prettify(), EMAIL_SETTINGS["url"]) msg = MIMEText(body, "html", 'utf-8') msg["subject"] = "你有未读消息【Young社区】" send_email(recipient['email'], msg) return True
def post(self): form = TopicNewForm(self.request.arguments) if not form.validate(): raise HTTPError(404) response_data = {} title = form.title.data content = form.content.data nodes = form.nodes.data.split(',') anonymous = form.anonymous.data nodes = list(set(nodes)) if len(nodes) > 3: response_data = {'error': '节点请不要超过3个!'} can_afford = yield UserDocument.can_afford( self.current_user['_id'], WEALTH_SETTINGS['topic_new']) if not can_afford: response_data = {'error': '金币不足!'} new_nodes = [] for node in nodes: existed = yield NodeDocument.find_one({'name': node}) if existed: node_id = existed['_id'] else: node_id = yield NodeDocument.insert({'name': node}) new_nodes.append( DBRef(NodeDocument.meta['collection'], ObjectId(node_id))) now = datetime.now() document = { 'author': DBRef(UserDocument.meta['collection'], ObjectId(self.current_user['_id'])), 'title': title, 'anonymous': anonymous, 'nodes': new_nodes, } existed = yield TopicDocument.find_one(document) if existed and (now - existed['publish_time'] < timedelta(minutes=1)): response_data.update({'error': '你已经发布了一个相同的帖子!'}) else: document.update({'publish_time': now, 'last_update_time': now}) if not response_data: if content: document.update({'content': content}) images = yield self.get_images(content) if images: document.update({'images': images}) topic_id = yield TopicDocument.insert_one(document) document = { 'user': DBRef(UserDocument.meta['collection'], ObjectId(self.current_user['_id'])), 'activity_type': UserActivityDocument.TOPIC_NEW, 'time': now, 'data': DBRef(TopicDocument.meta['collection'], ObjectId(topic_id)) } activity_id = yield UserActivityDocument.insert(document) document = { 'user': DBRef(UserDocument.meta['collection'], ObjectId(self.current_user['_id'])), 'in_out_type': WealthRecordDocument.OUT, 'activity': DBRef(UserActivityDocument.meta['collection'], ObjectId(activity_id)), 'quantity': WEALTH_SETTINGS['topic_new'], 'time': now } yield WealthRecordDocument.insert(document) yield UserDocument.update_wealth(self.current_user['_id'], -WEALTH_SETTINGS['topic_new']) if not anonymous: friends = yield FriendDocument.get_reached_friends( self.current_user['_id']) message_list = [] for friend in friends: document = { 'sender': DBRef(UserDocument.meta['collection'], ObjectId(self.current_user['_id'])), 'recipient': DBRef(UserDocument.meta['collection'], ObjectId(friend['_id'])), 'message_type': MessageTopic.TOPIC_NEW, 'time': now, 'read': False, 'data': DBRef(TopicDocument.meta['collection'], ObjectId(topic_id)) } message_id = yield MessageDocument.insert(document) message_list.append(str(message_id)) if message_list: try: WriterManager.mpub(MessageTopic.TOPIC_NEW, message_list) except: pass self.write_json(response_data)
def post(self): form = TopicCommentNewForm(self.request.arguments) if not form.validate(): raise HTTPError(404) response_data = {} content = form.content.data topic_id = form.topic_id.data anonymous = form.anonymous.data replyeder_id = form.replyeder_id.data replyeder = None if replyeder_id: replyeder = yield UserDocument.find_one( {'_id': ObjectId(replyeder_id)}) if not replyeder: raise HTTPError(404) if anonymous or self.current_user['_id'] == replyeder['_id']: raise HTTPError(404) topic = yield TopicDocument.find_one({'_id': ObjectId(topic_id)}) if not topic: raise HTTPError(404) now = datetime.now() document = { 'author': DBRef(UserDocument.meta['collection'], ObjectId(self.current_user['_id'])), 'topic': DBRef(TopicDocument.meta['collection'], ObjectId(topic['_id'])), 'content': content, 'anonymous': anonymous } existed = yield TopicCommentDocument.find_one(document) if existed and (now - existed['comment_time'] < timedelta(minutes=1)): response_data.update({'error': '请不要重复评论!'}) else: document.update({'comment_time': now}) if not response_data: if replyeder: document.update({ 'replyeder': DBRef(UserDocument.meta['collection'], ObjectId(replyeder_id)) }) comment_id = yield TopicCommentDocument.insert_one(document) activity = { 'user': DBRef(UserDocument.meta['collection'], ObjectId(self.current_user['_id'])), 'activity_type': UserActivityDocument.COMMENT, 'time': now, 'data': DBRef(TopicCommentDocument.meta['collection'], ObjectId(comment_id)) } yield UserActivityDocument.insert(activity) if replyeder: recipient_id = replyeder_id message_type = 'reply:topic' message_topic = MessageTopic.REPLY else: recipient_id = topic['author'].id message_type = 'comment:topic' message_topic = MessageTopic.COMMENT if (str(self.current_user['_id']) != str(recipient_id) and not anonymous and not (message_topic == MessageTopic.COMMENT and topic['anonymous'])): message = { 'sender': DBRef(UserDocument.meta['collection'], ObjectId(self.current_user['_id'])), 'recipient': DBRef(UserDocument.meta['collection'], ObjectId(recipient_id)), 'message_type': message_type, 'time': now, 'read': False, 'data': DBRef(TopicCommentDocument.meta['collection'], ObjectId(comment_id)) } message_id = yield MessageDocument.insert(message) WriterManager.pub(message_topic, message_id) comment_times = yield TopicCommentDocument.get_comment_times( topic_id) document.update({ '_id': ObjectId(comment_id), 'author': self.current_user, 'floor': comment_times }) if replyeder: document.update({'replyeder': replyeder}) item = self.render_string( 'community/template/topic-comment-list-item.html', comment=document) response_data.update({'item': item}) self.write_json(response_data)
def post(self): response_data = {} form = TopicLikeForm(self.request.arguments) if not form.validate(): raise HTTPError(404) topic_id = form.topic_id.data topic = yield TopicDocument.find_one({'_id': ObjectId(topic_id)}) if not topic: raise HTTPError(404) can_afford = yield UserDocument.can_afford(self.current_user['_id'], WEALTH_SETTINGS['like']) if not can_afford and str(self.current_user['_id']) != str( topic['author'].id): response_data.update({'error': '金币不足!'}) topic_dbref = DBRef(TopicDocument.meta['collection'], ObjectId(topic_id)) liker_dbref = DBRef(UserDocument.meta['collection'], ObjectId(self.current_user['_id'])) document = {'topic': topic_dbref, 'liker': liker_dbref} liked = yield TopicLikeDocument.is_liked(topic_id, self.current_user['_id']) if not liked and not response_data: now = datetime.now() document.update({'like_time': now}) like_id = yield TopicLikeDocument.insert_one(document) if str(self.current_user['_id']) != str(topic['author'].id): document = { 'user': DBRef(UserDocument.meta['collection'], ObjectId(self.current_user['_id'])), 'activity_type': UserActivityDocument.LIKE, 'time': now, 'data': DBRef(TopicLikeDocument.meta['collection'], ObjectId(like_id)) } activity_id = yield UserActivityDocument.insert(document) # 赞者 document = { 'user': DBRef(UserDocument.meta['collection'], ObjectId(self.current_user['_id'])), 'in_out_type': WealthRecordDocument.OUT, 'activity': DBRef(UserActivityDocument.meta['collection'], ObjectId(activity_id)), 'quantity': WEALTH_SETTINGS['like'], 'time': now } yield WealthRecordDocument.insert(document) yield UserDocument.update_wealth(self.current_user['_id'], -WEALTH_SETTINGS['like']) # 被赞者 document = { 'user': DBRef(UserDocument.meta['collection'], ObjectId(topic['author'].id)), 'in_out_type': WealthRecordDocument.IN, 'activity': DBRef(UserActivityDocument.meta['collection'], ObjectId(activity_id)), 'quantity': WEALTH_SETTINGS['like'], 'time': now } yield WealthRecordDocument.insert(document) yield UserDocument.update_wealth(topic['author'].id, WEALTH_SETTINGS['like']) document = { 'sender': DBRef(UserDocument.meta['collection'], ObjectId(self.current_user['_id'])), 'recipient': DBRef(UserDocument.meta['collection'], ObjectId(topic['author'].id)), 'message_type': 'like:topic', 'time': now, 'read': False, 'data': DBRef(TopicLikeDocument.meta['collection'], ObjectId(like_id)) } message_id = yield MessageDocument.insert(document) WriterManager.pub(MessageTopic.LIKE, message_id) like_times = yield TopicLikeDocument.get_like_times(topic_id) response_data.update({'like_times': like_times}) self.write_json(response_data)
def post(self): form = TopicNewForm(self.request.arguments) if not form.validate(): raise HTTPError(404) response_data = {} title = form.title.data content = form.content.data nodes = form.nodes.data.split(',') anonymous = form.anonymous.data nodes = list(set(nodes)) if len(nodes) > 3: response_data = {'error': '节点请不要超过3个!'} can_afford = yield UserDocument.can_afford( self.current_user['_id'], WEALTH_SETTINGS['topic_new'] ) if not can_afford: response_data = {'error': '金币不足!'} new_nodes = [] for node in nodes: existed = yield NodeDocument.find_one({'name': node}) if existed: node_id = existed['_id'] else: node_id = yield NodeDocument.insert({'name': node}) new_nodes.append( DBRef(NodeDocument.meta['collection'], ObjectId(node_id)) ) now = datetime.now() document = { 'author': DBRef( UserDocument.meta['collection'], ObjectId(self.current_user['_id']) ), 'title': title, 'anonymous': anonymous, 'nodes': new_nodes, } existed = yield TopicDocument.find_one(document) if existed and (now - existed['publish_time'] < timedelta(minutes=1)): response_data.update({'error': '你已经发布了一个相同的帖子!'}) else: document.update({'publish_time': now, 'last_update_time': now}) if not response_data: if content: document.update({'content': content}) images = yield self.get_images(content) if images: document.update({'images': images}) topic_id = yield TopicDocument.insert_one(document) document = { 'user': DBRef( UserDocument.meta['collection'], ObjectId(self.current_user['_id']) ), 'activity_type': UserActivityDocument.TOPIC_NEW, 'time': now, 'data': DBRef( TopicDocument.meta['collection'], ObjectId(topic_id) ) } activity_id = yield UserActivityDocument.insert(document) document = { 'user': DBRef( UserDocument.meta['collection'], ObjectId(self.current_user['_id']) ), 'in_out_type': WealthRecordDocument.OUT, 'activity': DBRef( UserActivityDocument.meta['collection'], ObjectId(activity_id) ), 'quantity': WEALTH_SETTINGS['topic_new'], 'time': now } yield WealthRecordDocument.insert(document) yield UserDocument.update_wealth( self.current_user['_id'], -WEALTH_SETTINGS['topic_new'] ) if not anonymous: friends = yield FriendDocument.get_reached_friends( self.current_user['_id'] ) message_list = [] for friend in friends: document = { 'sender': DBRef( UserDocument.meta['collection'], ObjectId(self.current_user['_id']) ), 'recipient': DBRef( UserDocument.meta['collection'], ObjectId(friend['_id']) ), 'message_type': MessageTopic.TOPIC_NEW, 'time': now, 'read': False, 'data': DBRef( TopicDocument.meta['collection'], ObjectId(topic_id) ) } message_id = yield MessageDocument.insert(document) message_list.append(str(message_id)) if message_list: try: WriterManager.mpub(MessageTopic.TOPIC_NEW, message_list) except: pass self.write_json(response_data)