Esempio n. 1
0
    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
        })
Esempio n. 2
0
    def post(self):
        form = PasswordResetSendmailForm(self.request.arguments)
        if not form.validate():
            raise HTTPError(404)

        response_data = {}
        email = form.email.data

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

        if not user['activated']:
            response_data.update({'error': '该账号尚未激活, 请先激活账号!'})
        else:
            document = {
                'uid': user["_id"],
                'code': CodeDocument.generate_code(),
                'expired_time': datetime.now() + timedelta(
                    days=USER_SETTINGS['code_expired_after']
                )
            }

            yield CodeDocument.remove({"uid": user["_id"]}, multi=True)

            code_id = yield CodeDocument.insert(document)
            WriterManager.pub(MessageTopic.SEND_RESET_PASSWORD_EMAIL, code_id)

        self.write_json(response_data)
Esempio n. 3
0
    def get(self):
        form = AccountActiveForm(self.request.arguments)
        if not form:
            raise HTTPError(404)

        response_data = {}

        uid = form.uid.data
        code = form.code.data

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

        code = yield CodeDocument.find_one({'uid': user["_id"], 'code': code})
        if not code:
            raise HTTPError(404)

        if user['activated']:
            response_data.update({'error': '该账号已经激活!'})
        elif code['expired_time'] < datetime.now():
            response_data.update({'error': '激活码已失效! 请返回到登录界面重新发送激活码!'})
        else:
            yield UserDocument.update({'_id': user['_id']},
                                      {'$set': {
                                          'activated': True
                                      }})
            response_data.update({'error': '激活成功!'})

        yield CodeDocument.remove({'_id': code['_id']})

        self.render('user/template/feedback.html', response_data=response_data)
Esempio n. 4
0
    def post(self):
        form = PasswordResetSendmailForm(self.request.arguments)
        if not form.validate():
            raise HTTPError(404)

        response_data = {}
        email = form.email.data

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

        if not user['activated']:
            response_data.update({'error': '该账号尚未激活, 请先激活账号!'})
        else:
            document = {
                'uid':
                user["_id"],
                'code':
                CodeDocument.generate_code(),
                'expired_time':
                datetime.now() +
                timedelta(days=USER_SETTINGS['code_expired_after'])
            }

            yield CodeDocument.remove({"uid": user["_id"]}, multi=True)

            code_id = yield CodeDocument.insert(document)
            WriterManager.pub(MessageTopic.SEND_RESET_PASSWORD_EMAIL, code_id)

        self.finish(json.dumps(response_data))
Esempio n. 5
0
    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()
Esempio n. 6
0
    def get(self):
        form = AccountActiveForm(self.request.arguments)
        if not form:
            raise HTTPError(404)

        response_data = {}

        uid = form.uid.data
        code = form.code.data

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

        code = yield CodeDocument.find_one({'uid': user["_id"], 'code': code})
        if not code:
            raise HTTPError(404)

        if user['activated']:
            response_data.update({'error': '该账号已经激活!'})
        elif code['expired_time'] < datetime.now():
            response_data.update({
                'error': '激活码已失效! 请返回到登录界面重新发送激活码!'
            })
        else:
            yield UserDocument.update(
                {'_id': user['_id']},
                {'$set': {'activated': True}}
            )
            response_data.update({'error': '激活成功!'})

        yield CodeDocument.remove({'_id': code['_id']})

        self.render('user/template/feedback.html', response_data=response_data)
Esempio n. 7
0
    def post(self):
        form = AccountActiveSendmailForm(self.request.arguments)
        if not form.validate():
            raise HTTPError(404)

        response_data = {}
        email = form.email.data

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

        if user['activated']:
            response_data.update({'error': '该账号已经激活!'})
        else:
            document = {
                'uid':
                user["_id"],
                'code':
                CodeDocument.generate_code(),
                'expired_time':
                datetime.now() +
                timedelta(days=USER_SETTINGS['code_expired_after'])
            }

            yield CodeDocument.remove({"uid": user["_id"]}, multi=True)

            code_id = yield CodeDocument.insert(document)
            WriterManager.pub(MessageTopic.SEND_ACTIVATION_EMAIL, code_id)

        self.write_json(response_data)
Esempio n. 8
0
    def post(self):
        response_data = {
            "next": self.get_argument("next", "/")
        }

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

            encrypt_password = yield UserDocument.encrypt_password(password)

            user = yield UserDocument.find_one({
                'email': email,
                'password': encrypt_password
            })

            if user:
                if not user['activated']:
                    response_data.update({
                        'error': '该账号尚未被激活! 请登录该邮箱以激活该账号! '
                                 '或者 <a href="#resend-activation-email-modal" '
                                 'class="red-color" id="resend-activation-email-link">'
                                 '重新发送激活邮件</a>'
                    })
                elif user['forbidden_login']:
                    response_data.update({
                        'error': '你的账号已于%s被冻结, 冻结时间为一周. 冻结原因: %s. 请你一周后再登录!' % (
                            user['forbidden_login_info'][-1]['time'].strftime('%m 月 %d 日 %H:%M'),
                            user['forbidden_login_info'][-1]['reason']
                        )
                    })
                else:
                    if not Ejabberd.registered(user['_id']):
                        Ejabberd.register(user['_id'], user['password'])

                    session = self.session_manager.new_session()
                    session.set('user_id', user['_id'])
                    session.set(
                        "ip", self.request.headers.get("X-Real-IP", None)
                    )
                    session.set(
                        'user_agent',
                        self.request.headers.get("User-Agent", None)
                    )

                    # 添加httponly,防止javascript获得session_id
                    self.set_secure_cookie(
                        'session_id', session.id, httponly=True
                    )
            else:
                response_data.update({'error': '邮箱或者密码错误!'})
        else:
            for field in form.errors:
                response_data.update({'error': form.errors[field][0]})
                break

        self.write_json(response_data)
Esempio n. 9
0
    def post(self):
        response_data = {"next": self.get_argument("next", "/")}

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

            encrypt_password = yield UserDocument.encrypt_password(password)

            user = yield UserDocument.find_one({
                'email': email,
                'password': encrypt_password
            })

            if user:
                if not user['activated']:
                    response_data.update({
                        'error':
                        '该账号尚未被激活! 请登录该邮箱以激活该账号! '
                        '或者 <a href="#resend-activation-email-modal" '
                        'class="red-color" id="resend-activation-email-link">'
                        '重新发送激活邮件</a>'
                    })
                elif user['forbidden_login']:
                    response_data.update({
                        'error':
                        '你的账号已于%s被冻结, 冻结时间为一周. 冻结原因: %s. 请你一周后再登录!' %
                        (user['forbidden_login_info'][-1]['time'].strftime(
                            '%m 月 %d 日 %H:%M'),
                         user['forbidden_login_info'][-1]['reason'])
                    })
                else:
                    if not Ejabberd.registered(user['_id']):
                        Ejabberd.register(user['_id'], user['password'])

                    session = self.session_manager.new_session()
                    session.set('user_id', user['_id'])
                    session.set("ip",
                                self.request.headers.get("X-Real-IP", None))
                    session.set('user_agent',
                                self.request.headers.get("User-Agent", None))

                    # 添加httponly,防止javascript获得session_id
                    self.set_secure_cookie('session_id',
                                           session.id,
                                           httponly=True)
            else:
                response_data.update({'error': '邮箱或者密码错误!'})
        else:
            for field in form.errors:
                response_data.update({'error': form.errors[field][0]})
                break

        self.finish(json.dumps(response_data))
Esempio 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)
Esempio n. 11
0
    def get(self):
        # 刷新失效
        session_id = self.get_secure_cookie('sid')
        if session_id:
            session = self.session_manager.load_session(session_id)

            yield CodeDocument.remove({
                'uid': ObjectId(session["uid"]),
                'code': session["code"]
            })

            session.clear()
            self.clear_cookie("sid")

        form = PasswordResetGetForm(self.request.arguments)
        if not form:
            raise HTTPError(404)

        response_data = {}

        uid = form.uid.data
        code = form.code.data

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

        code = yield CodeDocument.find_one({
            'uid': user["_id"],
            'code': code
        })
        if not code or datetime.now() > code['expired_time']:
            response_data.update({
                'error': '验证码已失效! 请返回到登录界面重新发送验证邮件!'
            })

        if response_data:
            self.clear_cookie('sid')
            self.render(
                'user/template/feedback.html',
                response_data=response_data
            )
        else:
            session = self.session_manager.new_session()
            session["uid"] = uid
            session["code"] = code["code"]

            self.set_secure_cookie('sid', session.id, httponly=True)
            self.render('user/template/password-reset.html')
Esempio n. 12
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)
Esempio n. 13
0
    def post(self):
        form = PasswordResetPostForm(self.request.arguments)
        if not form:
            raise HTTPError(404)

        password = form.password.data

        session_id = self.get_secure_cookie('sid')
        if not session_id:
            raise HTTPError(404)

        self.session = self.session_manager.load_session(session_id)

        uid = self.session.get('uid')
        code = self.session.get('code')

        if not uid or not code:
            raise HTTPError(404)

        code = yield CodeDocument.find_one({
            'uid': ObjectId(uid),
            'code': code
        })
        if not code:
            raise HTTPError(404)

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

        password = yield UserDocument.encrypt_password(password)
        yield UserDocument.update({'_id': user["_id"]},
                                  {'$set': {
                                      'password': password
                                  }})
        yield CodeDocument.remove({'_id': ObjectId(code['_id'])})

        try:
            Ejabberd.unregister(user['_id'])
            Ejabberd.register(user['_id'], password)
        except:
            pass

        self.session.clear()
        self.clear_cookie('sid')

        self.finish()
Esempio n. 14
0
    def post(self):
        form = PasswordResetPostForm(self.request.arguments)
        if not form:
            raise HTTPError(404)

        password = form.password.data

        session_id = self.get_secure_cookie('sid')
        if not session_id:
            raise HTTPError(404)

        self.session = self.session_manager.load_session(session_id)

        uid = self.session.get('uid')
        code = self.session.get('code')

        if not uid or not code:
            raise HTTPError(404)

        code = yield CodeDocument.find_one({
            'uid': ObjectId(uid),
            'code': code
        })
        if not code:
            raise HTTPError(404)

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

        password = yield UserDocument.encrypt_password(password)
        yield UserDocument.update(
            {'_id': user["_id"]},
            {'$set': {'password': password}}
        )
        yield CodeDocument.remove({'_id': ObjectId(code['_id'])})

        try:
            Ejabberd.unregister(user['_id'])
            Ejabberd.register(user['_id'], password)
        except:
            pass

        self.session.clear()
        self.clear_cookie('sid')

        self.finish()
Esempio n. 15
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))
Esempio n. 16
0
    def get(self):
        # 刷新失效
        session_id = self.get_secure_cookie('sid')
        if session_id:
            session = self.session_manager.load_session(session_id)

            yield CodeDocument.remove({
                'uid': ObjectId(session["uid"]),
                'code': session["code"]
            })

            session.clear()
            self.clear_cookie("sid")

        form = PasswordResetGetForm(self.request.arguments)
        if not form:
            raise HTTPError(404)

        response_data = {}

        uid = form.uid.data
        code = form.code.data

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

        code = yield CodeDocument.find_one({'uid': user["_id"], 'code': code})
        if not code or datetime.now() > code['expired_time']:
            response_data.update({'error': '验证码已失效! 请返回到登录界面重新发送验证邮件!'})

        if response_data:
            self.clear_cookie('sid')
            self.render('user/template/feedback.html',
                        response_data=response_data)
        else:
            session = self.session_manager.new_session()
            session["uid"] = uid
            session["code"] = code["code"]

            self.set_secure_cookie('sid', session.id, httponly=True)
            self.render('user/template/password-reset.html')
Esempio n. 17
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)
Esempio n. 18
0
    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)
Esempio n. 19
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})
Esempio n. 20
0
    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))
Esempio 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))
Esempio n. 22
0
    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)
Esempio n. 23
0
    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)
Esempio n. 24
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}))
Esempio n. 25
0
    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))
Esempio n. 26
0
    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)
Esempio n. 27
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)