Ejemplo n.º 1
0
    def get_header_arguments(self, user_id=None):
        user_id = user_id or self.current_user["_id"]

        user = yield UserDocument.find_one({
            '_id': ObjectId(user_id)
        })
        if not user:
            raise HTTPError(404)

        status_number = yield StatusDocument.get_status_number(user_id)
        topic_number = yield TopicDocument.get_topic_number_by_someone(
            user_id, visitor_id=self.current_user['_id']
        )

        user = yield UserDocument.translate_dbref_in_document(user)

        can_seen = yield UserDocument.can_seen(
            user_id, self.current_user['_id']
        )
        is_friend = yield FriendDocument.is_friend(
            user_id, self.current_user['_id']
        )
        user_setting = yield UserSettingDocument.get_user_setting(
            user_id
        )
        profile_cover = yield UserSettingDocument.get_profile_cover(
            user_id
        )

        kwargs = {
            'user': user,
            'can_seen': can_seen,
            'is_friend': is_friend,
            'user_setting': user_setting,
            'status_number': status_number,
            'topic_number': topic_number,
            'profile_cover': profile_cover,
            'PROFILE_SETTINGS': PROFILE_SETTINGS
        }

        if not can_seen:
            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
            })

        raise gen.Return(kwargs)
Ejemplo n.º 2
0
    def can_see(status, user_id):
        '''判断某人能否看到某状态.

        :Parameters:
          - `status`: 状态, 是id或者document
          - `user_id`: 相关用户
        '''

        can = False

        if isinstance(status, (str, ObjectId)):
            status = yield StatusDocument.find_one({'_id': ObjectId(status)})

        if status:
            if isinstance(status['author'], DBRef):
                author = status['author'].id
            elif isinstance(status['author'], dict):
                author = status['author']['_id']
            else:
                raise gen.Return(can)

            is_friend = yield FriendDocument.is_friend(user_id, author)
            user_setting = yield UserSettingDocument.get_user_setting(author)

            if (str(author) == str(user_id) or is_friend
                    or user_setting['allow_stranger_visiting_profile']):
                can = True

        raise gen.Return(can)
Ejemplo n.º 3
0
    def get_sidebar_arguments(self):
        '''得到两侧栏的render变量'''

        user_id = self.current_user['_id']
        status_number = yield StatusDocument.get_status_number(user_id)
        topic_number = yield TopicDocument.get_topic_number_by_someone(user_id)

        user_setting = yield UserSettingDocument.find_one({
            'user': DBRef(UserDocument.meta['collection'], ObjectId(user_id))
        })

        random_user_list = yield UserDocument.get_random_user_list(
            self.current_user['_id']
        )

        kwargs = {
            'status_number': status_number,
            'topic_number': topic_number,
            'MessageTopic': MessageTopic,
            'user_setting': user_setting,
            'random_user_list': random_user_list,
            'HOME_SETTINGS': HOME_SETTINGS
        }

        raise gen.Return(kwargs)
Ejemplo n.º 4
0
    def can_see(status, user_id):
        '''判断某人能否看到某状态.

        :Parameters:
          - `status`: 状态, 是id或者document
          - `user_id`: 相关用户
        '''

        can = False

        if isinstance(status, (str, ObjectId)):
            status = yield StatusDocument.find_one({'_id': ObjectId(status)})

        if status:
            if isinstance(status['author'], DBRef):
                author = status['author'].id
            elif isinstance(status['author'], dict):
                author = status['author']['_id']
            else:
                raise gen.Return(can)

            is_friend = yield FriendDocument.is_friend(user_id, author)
            user_setting = yield UserSettingDocument.get_user_setting(author)

            if (str(author) == str(user_id) or is_friend or
                    user_setting['allow_stranger_visiting_profile']):
                can = True

        raise gen.Return(can)
Ejemplo n.º 5
0
    def get_sidebar_arguments(self):
        '''得到两侧栏的render变量'''

        user_id = self.current_user['_id']

        status_number = yield StatusDocument.get_status_number(user_id)
        topic_number = yield TopicDocument.get_topic_number_by_someone(
            user_id, visitor_id=user_id
        )

        user_setting = yield UserSettingDocument.find_one({
            'user': DBRef(UserDocument.meta['collection'], ObjectId(user_id))
        })
        login_reward_fetched_today = yield UserActivityDocument.login_reward_fetched(
            user_id
        )
        continuous_login_days = yield UserDocument.get_continuous_login_days(
            user_id
        )

        kwargs = {
            'status_number': status_number,
            'topic_number': topic_number,
            'MessageTopic': MessageTopic,
            'user_setting': user_setting,
            'login_reward_fetched_today': login_reward_fetched_today,
            'continuous_login_days': continuous_login_days,
            'HOME_SETTINGS': HOME_SETTINGS
        }

        raise gen.Return(kwargs)
Ejemplo n.º 6
0
    def post(self):
        if 'cover' not in self.request.files:
            raise HTTPError(404)

        upload_file = self.request.files['cover'][0]

        try:
            Image.open(StringIO(upload_file['body']))
        except:
            raise HTTPError(404)

        uploader = DBRef(
            UserDocument.meta['collection'],
            ObjectId(self.current_user['_id'])
        )
        image_id = yield ImageDocument.insert_one(
            upload_file,
            thumbnail_width=960,
            uploader=uploader,
            upload_time=datetime.now()
        )

        cover = DBRef(ImageDocument.meta['collection'], ObjectId(image_id))
        yield UserSettingDocument.set_profile_cover(
            self.current_user['_id'], cover
        )

        self.finish()
Ejemplo n.º 7
0
def _reponse_browser_callback(recipient_id, topic, message):
    from app.user.document import UserSettingDocument

    callback = BrowserCallbackManager.get(recipient_id)

    if callback:
        message = {
            'topic': topic,
            'message': message
        }

        try:
            callback(message)
        except:
            pass

        return True

    user_setting = UserSettingDocument.get_user_setting_sync(
        recipient_id
    )
    if user_setting['email_notify_when_offline']:
        WriterManager.pub(
            MessageTopic.SEND_HAS_UNREAD_MESSAGE_EMAIL,
            message['_id']
        )

    return True
Ejemplo n.º 8
0
    def get_sidebar_arguments(self):
        '''得到两侧栏的render变量'''

        user_id = self.current_user['_id']
        status_number = yield StatusDocument.get_status_number(user_id)
        topic_number = yield TopicDocument.get_topic_number_by_someone(user_id)

        user_setting = yield UserSettingDocument.find_one({
            'user': DBRef(UserDocument.meta['collection'], ObjectId(user_id))
        })

        random_user_list = yield UserDocument.get_random_user_list(
            self.current_user['_id']
        )

        kwargs = {
            'status_number': status_number,
            'topic_number': topic_number,
            'MessageTopic': MessageTopic,
            'user_setting': user_setting,
            'random_user_list': random_user_list,
            'HOME_SETTINGS': HOME_SETTINGS
        }

        raise gen.Return(kwargs)
Ejemplo n.º 9
0
    def get_sidebar_arguments(self):
        '''得到两侧栏的render变量'''

        user_id = self.current_user['_id']

        status_number = yield StatusDocument.get_status_number(user_id)
        topic_number = yield TopicDocument.get_topic_number_by_someone(
            user_id, visitor_id=user_id)

        user_setting = yield UserSettingDocument.find_one({
            'user':
            DBRef(UserDocument.meta['collection'], ObjectId(user_id))
        })
        login_reward_fetched_today = yield UserActivityDocument.login_reward_fetched(
            user_id)
        continuous_login_days = yield UserDocument.get_continuous_login_days(
            user_id)

        kwargs = {
            'status_number': status_number,
            'topic_number': topic_number,
            'MessageTopic': MessageTopic,
            'user_setting': user_setting,
            'login_reward_fetched_today': login_reward_fetched_today,
            'continuous_login_days': continuous_login_days,
            'HOME_SETTINGS': HOME_SETTINGS
        }

        raise gen.Return(kwargs)
Ejemplo n.º 10
0
    def get_header_arguments(self, user_id=None):
        user_id = user_id or self.current_user["_id"]

        user = yield UserDocument.find_one({'_id': ObjectId(user_id)})
        if not user:
            raise HTTPError(404)

        status_number = yield StatusDocument.get_status_number(user_id)
        topic_number = yield TopicDocument.get_topic_number_by_someone(
            user_id, visitor_id=self.current_user['_id'])

        user = yield UserDocument.translate_dbref_in_document(user)

        can_seen = yield UserDocument.can_seen(user_id,
                                               self.current_user['_id'])
        is_friend = yield FriendDocument.is_friend(user_id,
                                                   self.current_user['_id'])
        user_setting = yield UserSettingDocument.get_user_setting(user_id)
        profile_cover = yield UserSettingDocument.get_profile_cover(user_id)

        kwargs = {
            'user': user,
            'can_seen': can_seen,
            'is_friend': is_friend,
            'user_setting': user_setting,
            'status_number': status_number,
            'topic_number': topic_number,
            'profile_cover': profile_cover,
            'PROFILE_SETTINGS': PROFILE_SETTINGS
        }

        if not can_seen:
            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})

        raise gen.Return(kwargs)
Ejemplo n.º 11
0
    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)
Ejemplo n.º 12
0
    def post(self):
        form = ThemeSetForm(self.request.arguments)
        if not form.validate():
            raise HTTPError(404)

        theme = form.theme.data

        yield UserSettingDocument.update(
            {'user': DBRef(
                UserDocument.meta['collection'],
                ObjectId(self.current_user['_id'])
            )},
            {'$set': {'theme': theme}}
        )

        self.finish()
Ejemplo n.º 13
0
    def post(self):
        form = NotificationSetForm(self.request.arguments)
        if not form.validate():
            raise HTTPError(404)

        email_notify_when_offline = form.email_notify_when_offline.data

        yield UserSettingDocument.update(
            {'user': DBRef(
                UserDocument.meta['collection'],
                ObjectId(self.current_user['_id'])
            )},
            {'$set': {'email_notify_when_offline': email_notify_when_offline}}
        )

        self.finish()
Ejemplo n.º 14
0
    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))
Ejemplo n.º 15
0
    def get(self, cover_type, id_, content_type=None):
        if cover_type == 'user':
            user_setting = yield UserSettingDocument.find_one({
                'user':
                DBRef(UserDocument.meta['collection'], ObjectId(id_))
            })

            profile_cover = yield OfficialProfileCoverDocument.find_one(
                {'_id': ObjectId(user_setting['profile_cover'].id)})
        else:
            profile_cover = yield OfficialProfileCoverDocument.find_one(
                {'_id': ObjectId(id_)})

        content = str(profile_cover['content'])
        if content_type is not None:
            content = str(
                profile_cover['profile_content'] if content_type ==
                'profile-content' else profile_cover['setting_content'])

        self.finish(content)
Ejemplo n.º 16
0
def _reponse_browser_callback(recipient_id, topic, message):
    from app.user.document import UserSettingDocument

    callback = BrowserCallbackManager.get(recipient_id)

    if callback:
        message = {'topic': topic, 'message': message}

        try:
            callback(message)
        except:
            pass

        return True

    user_setting = UserSettingDocument.get_user_setting_sync(recipient_id)
    if user_setting['email_notify_when_offline']:
        WriterManager.pub(MessageTopic.SEND_HAS_UNREAD_MESSAGE_EMAIL,
                          message['_id'])

    return True
Ejemplo n.º 17
0
    def post(self):
        form = ProfileCoverSetForm(self.request.arguments)
        if not form.validate():
            raise HTTPError(404)

        profile_cover_id = form.profile_cover_id.data
        profile_cover = yield OfficialProfileCoverDocument.find_one({
            '_id': ObjectId(profile_cover_id)
        })

        if not profile_cover:
            raise HTTPError(404)

        cover = DBRef(
            OfficialProfileCoverDocument.meta['collection'],
            ObjectId(profile_cover['_id'])
        )
        yield UserSettingDocument.set_profile_cover(
            self.current_user['_id'], cover
        )

        raise gen.Return()
Ejemplo n.º 18
0
    def get(self, cover_type, id_, content_type=None):
        if cover_type == 'user':
            user_setting = yield UserSettingDocument.find_one({
                'user': DBRef(UserDocument.meta['collection'], ObjectId(id_))
            })

            profile_cover = yield OfficialProfileCoverDocument.find_one({
                '_id': ObjectId(user_setting['profile_cover'].id)
            })
        else:
            profile_cover = yield OfficialProfileCoverDocument.find_one({
                '_id': ObjectId(id_)
            })

        content = str(profile_cover['content'])
        if content_type is not None:
            content = str(
                profile_cover['profile_content']
                if content_type == 'profile-content' else
                profile_cover['setting_content']
            )

        self.finish(content)
Ejemplo n.º 19
0
    def post(self):
        form = PrivateSetForm(self.request.arguments)
        if not form.validate():
            raise HTTPError(404)

        require_verify_when_add_friend = form.require_verify_when_add_friend.data
        allow_stranger_visiting_profile = form.allow_stranger_visiting_profile.data
        allow_stranger_chat_with_me = form.allow_stranger_chat_with_me.data
        enable_leaving_message = form.enable_leaving_message.data

        yield UserSettingDocument.update(
            {'user': DBRef(
                UserDocument.meta['collection'],
                ObjectId(self.current_user['_id'])
            )},
            {'$set': {
                'require_verify_when_add_friend': require_verify_when_add_friend,
                'allow_stranger_visiting_profile': allow_stranger_visiting_profile,
                'allow_stranger_chat_with_me': allow_stranger_chat_with_me,
                'enable_leaving_message': enable_leaving_message
            }}
        )

        self.finish()
Ejemplo n.º 20
0
    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}))
Ejemplo n.º 21
0
    def post(self):
        response_data = {}

        form = RegisterForm(self.request.arguments)
        if form.validate():
            name = form.name.data
            email = form.email.data
            password = form.password.data

            if (yield UserDocument.find_one({'name': name})):
                response_data["error"] = "用户名已被占用"

            if (yield UserDocument.find_one({"email": email})):
                response_data["error"] = "邮箱已被注册"

            if not response_data:
                password = yield UserDocument.encrypt_password(password)

                document = {
                    'email': email,
                    'name': name,
                    'password': password,
                    'user_type': "person",
                    'register_date': datetime.now()
                }

                try:
                    user_id = yield UserDocument.insert(document)
                except:
                    raise HTTPError(500)

                # 头像初始化
                avatar = open(
                    os.path.join(APPLICATION_SETTINGS['static_path'],
                                 'img/default.jpg'))
                content = avatar.read()
                avatar.close()

                document = {
                    'name':
                    'default.jpg',
                    'upload_time':
                    datetime.now(),
                    'content_type':
                    'jpeg',
                    'owner':
                    DBRef(UserDocument.meta['collection'], ObjectId(user_id)),
                    'content':
                    Binary(content),
                    'thumbnail50x50':
                    Binary(content),
                    'thumbnail180x180':
                    Binary(content)
                }
                yield AvatarDocument.insert(document)

                # 用户设置初始化
                _ = yield OfficialProfileCoverDocument.get_profile_cover_list()
                profile_cover = random.sample(_, 1)[0]

                document = {
                    'user':
                    DBRef(UserDocument.meta['collection'], ObjectId(user_id)),
                    'profile_cover':
                    DBRef(OfficialProfileCoverDocument.meta['collection'],
                          ObjectId(profile_cover['_id']))
                }
                yield UserSettingDocument.insert(document)

                # Ejabberd注册
                try:
                    Ejabberd.register(user_id, password)
                except:
                    pass

                # 给用户发送验证邮件
                document = {
                    'uid':
                    user_id,
                    'code':
                    CodeDocument.generate_code(),
                    'expired_time':
                    datetime.now() +
                    timedelta(days=USER_SETTINGS['code_expired_after'])
                }
                code_id = yield CodeDocument.insert(document)
                WriterManager.pub(MessageTopic.SEND_ACTIVATION_EMAIL, code_id)

                response_data.update(
                    {'success': '注册成功! 系统已经向你的注册邮箱发送了一封激活'
                     '邮件, 请验证后登录!'})

        else:
            for field in form.errors:
                response_data.update({'error': form.errors[field][0]})
                break

        self.finish(json.dumps(response_data))
Ejemplo n.º 22
0
    def post(self):
        response_data = {}

        form = RegisterForm(self.request.arguments)
        if form.validate():
            name = form.name.data
            email = form.email.data
            password = form.password.data

            if (yield UserDocument.find_one({'name': name})):
                response_data["error"] = "用户名已被占用"

            if (yield UserDocument.find_one({"email": email})):
                response_data["error"] = "邮箱已被注册"

            if not response_data:
                password = yield UserDocument.encrypt_password(password)

                document = {
                    'email': email,
                    'name': name,
                    'password': password,
                    'user_type': "person",
                    'register_date': datetime.now()
                }

                try:
                    user_id = yield UserDocument.insert(document)
                except:
                    raise HTTPError(500)

                # 头像初始化
                avatar = open(os.path.join(
                    APPLICATION_SETTINGS['static_path'], 'img/default.jpg')
                )
                content = avatar.read()
                avatar.close()

                document = {
                    'name': 'default.jpg',
                    'upload_time': datetime.now(),
                    'content_type': 'jpeg',
                    'owner': DBRef(
                        UserDocument.meta['collection'], ObjectId(user_id)
                    ),
                    'content': Binary(content),
                    'thumbnail50x50': Binary(content),
                    'thumbnail180x180': Binary(content)
                }
                yield AvatarDocument.insert(document)

                # 用户设置初始化
                _ = yield OfficialProfileCoverDocument.get_profile_cover_list()
                profile_cover = random.sample(_, 1)[0]

                document = {
                    'user': DBRef(
                        UserDocument.meta['collection'], ObjectId(user_id)
                    ),
                    'profile_cover': DBRef(
                        OfficialProfileCoverDocument.meta['collection'],
                        ObjectId(profile_cover['_id'])
                    )
                }
                yield UserSettingDocument.insert(document)

                # Ejabberd注册
                try:
                    Ejabberd.register(user_id, password)
                except:
                    pass

                # 给用户发送验证邮件
                document = {
                    'uid': user_id,
                    'code': CodeDocument.generate_code(),
                    'expired_time': datetime.now() + timedelta(
                        days=USER_SETTINGS['code_expired_after']
                    )
                }
                code_id = yield CodeDocument.insert(document)
                WriterManager.pub(MessageTopic.SEND_ACTIVATION_EMAIL, code_id)

                response_data.update({
                    'success': '注册成功! 系统已经向你的注册邮箱发送了一封激活'
                               '邮件, 请验证后登录!'
                })

        else:
            for field in form.errors:
                response_data.update({'error': form.errors[field][0]})
                break

        self.write_json(response_data)
Ejemplo n.º 23
0
    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})
Ejemplo n.º 24
0
    def get(self, option):
        if option == 'avatar':
            avatar = yield AvatarDocument.find_one({
                'owner': DBRef(
                    UserDocument.meta['collection'],
                    ObjectId(self.current_user['_id'])
                )
            })

            self.render(
                'setting/template/setting-avatar.html',
                avatar=avatar,
                preview=self.get_avatar(self.current_user['_id'])
            )

        elif option == 'profile':
            user_setting = yield UserSettingDocument.find_one({
                'user': DBRef(
                    UserDocument.meta['collection'],
                    ObjectId(self.current_user['_id'])
                )
            })

            self.render(
                'setting/template/setting-profile.html',
                user_setting=user_setting
            )

        elif option == 'password':
            self.render('setting/template/setting-password.html')

        elif option == 'profile/cover':
            cover_list_f = OfficialProfileCoverDocument.get_profile_cover_list
            profile_cover_list = yield cover_list_f()

            user_setting = yield UserSettingDocument.find_one({
                'user': DBRef(
                    UserDocument.meta['collection'],
                    ObjectId(self.current_user['_id'])
                )
            })

            self.render(
                'setting/template/setting-profile-cover.html',
                profile_cover_list=profile_cover_list,
                user_setting=user_setting
            )

        elif option == 'private':
            user_setting = yield UserSettingDocument.find_one({
                'user': DBRef(
                    UserDocument.meta['collection'],
                    ObjectId(self.current_user['_id'])
                )
            })

            self.render(
                'setting/template/setting-private.html',
                user_setting=user_setting
            )
        elif option == 'notification':
            user_setting = yield UserSettingDocument.find_one({
                'user': DBRef(
                    UserDocument.meta['collection'],
                    ObjectId(self.current_user['_id'])
                )
            })
            self.render(
                'setting/template/setting-notification.html',
                user_setting=user_setting
            )
        elif option == 'theme':
            user_setting = yield UserSettingDocument.find_one({
                'user': DBRef(
                    UserDocument.meta['collection'],
                    ObjectId(self.current_user['_id'])
                )
            })

            self.render(
                'setting/template/setting-theme.html',
                user_setting=user_setting
            )
        else:
            raise HTTPError(404)