Example #1
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)
Example #2
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)
Example #3
0
    def post(self):
        response_data = {}

        login_reward_fetched = yield UserActivityDocument.login_reward_fetched(
            self.current_user['_id']
        )

        if login_reward_fetched:
            response_data.update({'error': '你已经领取了今日的登录奖励!'})
        else:
            now = datetime.now()

            document = {
                'user': DBRef(
                    UserDocument.meta['collection'],
                    ObjectId(self.current_user['_id'])
                ),
                'activity_type': UserActivityDocument.FETCH_LOGIN_REWARD,
                'time': now
            }
            activity_id = yield UserActivityDocument.insert(document)

            continuous_login_days = yield UserDocument.get_continuous_login_days(
                self.current_user['_id']
            )
            quantity = (1 + continuous_login_days / 7) * 5

            document = {
                'user': DBRef(
                    UserDocument.meta['collection'],
                    ObjectId(self.current_user['_id'])
                ),
                'activity': DBRef(
                    UserActivityDocument.meta['collection'],
                    ObjectId(activity_id)
                ),
                'in_out_type': WealthRecordDocument.IN,
                'quantity': quantity,
                'time': now
            }
            yield WealthRecordDocument.insert(document)

            yield UserDocument.update_wealth(
                self.current_user['_id'], quantity
            )
            yield UserDocument.update(
                {'_id': ObjectId(self.current_user['_id'])},
                {'$inc': {'continuous_login_days': 1}}
            )

            continuous_login_days = yield UserDocument.get_continuous_login_days(
                self.current_user['_id']
            )

            response_data.update({
                'wealth': self.current_user['wealth'] + quantity,
                'continuous_login_days': continuous_login_days
            })

        self.write_json(response_data)
Example #4
0
    def post(self):
        response_data = {}

        login_reward_fetched = yield UserActivityDocument.login_reward_fetched(
            self.current_user['_id'])

        if login_reward_fetched:
            response_data.update({'error': '你已经领取了今日的登录奖励!'})
        else:
            now = datetime.now()

            document = {
                'user':
                DBRef(UserDocument.meta['collection'],
                      ObjectId(self.current_user['_id'])),
                'activity_type':
                UserActivityDocument.FETCH_LOGIN_REWARD,
                'time':
                now
            }
            activity_id = yield UserActivityDocument.insert(document)

            continuous_login_days = yield UserDocument.get_continuous_login_days(
                self.current_user['_id'])
            quantity = (1 + continuous_login_days / 7) * 5

            document = {
                'user':
                DBRef(UserDocument.meta['collection'],
                      ObjectId(self.current_user['_id'])),
                'activity':
                DBRef(UserActivityDocument.meta['collection'],
                      ObjectId(activity_id)),
                'in_out_type':
                WealthRecordDocument.IN,
                'quantity':
                quantity,
                'time':
                now
            }
            yield WealthRecordDocument.insert(document)

            yield UserDocument.update_wealth(self.current_user['_id'],
                                             quantity)
            yield UserDocument.update(
                {'_id': ObjectId(self.current_user['_id'])},
                {'$inc': {
                    'continuous_login_days': 1
                }})

            continuous_login_days = yield UserDocument.get_continuous_login_days(
                self.current_user['_id'])

            response_data.update({
                'wealth': self.current_user['wealth'] + quantity,
                'continuous_login_days': continuous_login_days
            })

        self.finish(json.dumps(response_data))
Example #5
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)
Example #6
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))
Example #7
0
    def get_message_list(recipient_id, message_topic=None, read=None,
                         skip=0, limit=None):
        '''得到消息列表'''

        query = MessageDocument.get_query(recipient_id, message_topic)

        if read is not None:
            assert isinstance(read, bool)
            query.update({'read': read})

        cursor = MessageDocument.find(query).sort(
            [('time', pymongo.DESCENDING)]
        ).skip(skip)

        if limit is not None:
            cursor = cursor.limit(limit)

        message_list = yield MessageDocument.to_list(cursor)
        for message in message_list:
            if 'sender' in message:
                message['sender'] = yield UserDocument.translate_dbref(
                    message['sender']
                )

            message['recipient'] = yield UserDocument.translate_dbref(
                message['recipient']
            )

            if 'data' not in message:
                continue

            if str(message['data'].collection) == str(
                    StatusDocument.meta['collection']):
                message['data'] = yield StatusDocument.get_status(
                    message['data'].id
                )
                continue

            message['data'] = yield Document.translate_dbref(
                message['data']
            )

            if message['data']:
                message['data'] = yield Document.translate_dbref_in_document(
                    message['data'], depth=2
                )

                if 'status' in message['data']:
                    message['data']['status'] = yield StatusDocument.get_status(
                        message['data']['status']['_id']
                    )

        raise gen.Return(message_list)
Example #8
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)
Example #9
0
    def get_message_list(recipient_id,
                         message_topic=None,
                         read=None,
                         skip=0,
                         limit=None):
        '''得到消息列表'''

        query = MessageDocument.get_query(recipient_id, message_topic)

        if read is not None:
            assert isinstance(read, bool)
            query.update({'read': read})

        cursor = MessageDocument.find(query).sort([('time', pymongo.DESCENDING)
                                                   ]).skip(skip)

        if limit is not None:
            cursor = cursor.limit(limit)

        message_list = yield MessageDocument.to_list(cursor)
        for message in message_list:
            if 'sender' in message:
                message['sender'] = yield UserDocument.translate_dbref(
                    message['sender'])

            message['recipient'] = yield UserDocument.translate_dbref(
                message['recipient'])

            if 'data' not in message:
                continue

            if str(message['data'].collection) == str(
                    StatusDocument.meta['collection']):
                message['data'] = yield StatusDocument.get_status(
                    message['data'].id)
                continue

            message['data'] = yield Document.translate_dbref(message['data'])

            if message['data']:
                message['data'] = yield Document.translate_dbref_in_document(
                    message['data'], depth=2)

                if 'status' in message['data']:
                    message['data'][
                        'status'] = yield StatusDocument.get_status(
                            message['data']['status']['_id'])

        raise gen.Return(message_list)
Example #10
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)
Example #11
0
    def get_topic_list_by_someone(author_id, skip=0, limit=None):
        '''得到某人的话题'''

        cursor = TopicDocument.find({
            'author': DBRef(
                UserDocument.meta['collection'], ObjectId(author_id)
            )
        }).sort([('publish_time', pymongo.DESCENDING)]).skip(skip)

        if limit is not None:
            cursor = cursor.limit(limit)

        topic_list = yield TopicDocument.to_list(cursor)
        for topic in topic_list:
            topic['author'] = yield UserDocument.translate_dbref(
                topic['author']
            )
            topic['last_comment'] = yield TopicCommentDocument.get_last_comment(
                topic['_id']
            )

            for i, node in enumerate(topic['nodes']):
                topic['nodes'][i] = yield NodeDocument.translate_dbref(node)

        raise gen.Return(topic_list)
Example #12
0
    def get_top_topic_list(user_id=None, skip=0, limit=None):
        '''得到置顶的帖子'''

        query = {'top': True}

        cursor = TopicDocument.find(query).sort(
            [('publish_time', pymongo.DESCENDING)]
        ).skip(skip)

        if limit is not None:
            cursor = cursor.limit(limit)

        topic_list = yield TopicDocument.to_list(cursor)
        for topic in topic_list:
            topic['author'] = yield UserDocument.translate_dbref(
                topic['author']
            )
            topic['last_comment'] = yield TopicCommentDocument.get_last_comment(
                topic['_id']
            )

            if 'images' in topic and topic['images']:
                topic['images'] = yield TopicDocument._extend_images(topic)

            if user_id is not None:
                topic['liked'] = yield TopicLikeDocument.is_liked(
                    topic['_id'], user_id
                )

            for i, node in enumerate(topic['nodes']):
                topic['nodes'][i] = yield NodeDocument.translate_dbref(node)

        raise gen.Return(topic_list)
Example #13
0
    def get_topic(topic_id, user_id):
        '''
        :Parameters:
          - `topic_id`: 话题id
          - `user_id`: 判断该user是否赞了该话题
        '''

        topic = yield TopicDocument.find_one({'_id': ObjectId(topic_id)})
        if topic:
            topic['author'] = yield UserDocument.translate_dbref(
                topic['author']
            )

            liked = yield TopicLikeDocument.is_liked(topic_id, user_id)
            last_comment = yield TopicCommentDocument.get_last_comment(
                topic['_id']
            )

            topic.update({
                'liked': liked,
                'last_comment': last_comment
            })

            if 'images' in topic and topic['images']:
                topic['images'] = yield TopicDocument._extend_images(topic)

            for i, node in enumerate(topic['nodes']):
                topic['nodes'][i] = yield NodeDocument.translate_dbref(node)

        raise gen.Return(topic)
Example #14
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)
Example #15
0
def send_has_unread_message_email_handler(message):
    '''如果用户不在线就发送邮件'''

    from young.handler import BaseHandler
    from app.user.document import UserDocument
    from app.message.document import MessageDocument

    message = MessageDocument.get_collection(pymongo=True).find_one(
        {'_id': ObjectId(message.body)})

    if not message:
        return True

    recipient_id = message['recipient'].id
    topic = MessageTopic.message_type2topic(message['message_type'])

    recipient = UserDocument.get_user_sync(recipient_id)
    if recipient and recipient['activated']:
        message = BaseHandler.translate_dbref_in_document(message)
        if 'data' in message:
            message['data'] = BaseHandler.translate_dbref_in_document(
                message['data'], depth=2)

        kwargs = {
            'message_topic': topic,
            'message': message,
            'MessageTopic': MessageTopic,
            'handler': BaseHandler
        }

        root = os.path.dirname(
            os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
        path = os.path.join(root, 'app/message/template')

        loader = template.Loader(path)
        html = loader.load("message.html").generate(**kwargs)

        soup = BeautifulSoup(html, "html.parser")
        link_list = soup.find_all('a')
        for link in link_list:
            new_link = link
            if link['href'].startswith('/'):
                new_link['href'] = EMAIL_SETTINGS['url'] + link['href']
                link.replace_with(new_link)

        img_list = soup.find_all('img')
        for img in img_list:
            new_img = img
            if img['src'].startswith('/'):
                new_img['src'] = EMAIL_SETTINGS['url'] + img['src']
                img.replace_with(new_img)

        body = ('{} &nbsp;&nbsp; <a href="{}/setting/notification">'
                '关闭邮件提醒</a>').format(soup.prettify(), EMAIL_SETTINGS["url"])

        msg = MIMEText(body, "html", 'utf-8')
        msg["subject"] = "你有未读消息【Young社区】"
        send_email(recipient['email'], msg)

    return True
Example #16
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
        })
Example #17
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)
Example #18
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)
Example #19
0
    def get(self, user_id=None):
        user_id = user_id or self.current_user['_id']

        kwargs = yield self.get_header_arguments(user_id)
        if not kwargs['can_seen']:
            self.render('profile/template/profile-visitor.html', **kwargs)
        else:
            status_list = yield StatusDocument.get_status_list(
                user_id,
                self.current_user['_id'],
                limit=PROFILE_SETTINGS['status_number_per_page'])

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

            if kwargs['user']['user_type'] == 'league':
                member_list = yield LeagueMemberDocument.get_member(user_id)
                kwargs.update({'member_list': member_list})

            kwargs.update({
                'status_list': status_list,
                'recommend_friend_list': recommend_friend_list,
                'PROFILE_SETTINGS': PROFILE_SETTINGS
            })

            self.render('profile/template/status/status.html', **kwargs)
Example #20
0
    def get_top_topic_list(user_id=None, skip=0, limit=None):
        '''得到置顶的帖子'''

        query = {'top': True}

        cursor = TopicDocument.find(query).sort([
            ('publish_time', pymongo.DESCENDING)
        ]).skip(skip)

        if limit is not None:
            cursor = cursor.limit(limit)

        topic_list = yield TopicDocument.to_list(cursor)
        for topic in topic_list:
            topic['author'] = yield UserDocument.translate_dbref(
                topic['author'])
            topic[
                'last_comment'] = yield TopicCommentDocument.get_last_comment(
                    topic['_id'])

            if 'images' in topic and topic['images']:
                topic['images'] = yield TopicDocument._extend_images(topic)

            if user_id is not None:
                topic['liked'] = yield TopicLikeDocument.is_liked(
                    topic['_id'], user_id)

            for i, node in enumerate(topic['nodes']):
                topic['nodes'][i] = yield NodeDocument.translate_dbref(node)

        raise gen.Return(topic_list)
Example #21
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)
Example #22
0
    def get_topic(topic_id, user_id):
        '''
        :Parameters:
          - `topic_id`: 话题id
          - `user_id`: 判断该user是否赞了该话题
        '''

        topic = yield TopicDocument.find_one({'_id': ObjectId(topic_id)})
        if topic:
            topic['author'] = yield UserDocument.translate_dbref(
                topic['author'])

            liked = yield TopicLikeDocument.is_liked(topic_id, user_id)
            last_comment = yield TopicCommentDocument.get_last_comment(
                topic['_id'])

            topic.update({'liked': liked, 'last_comment': last_comment})

            if 'images' in topic and topic['images']:
                topic['images'] = yield TopicDocument._extend_images(topic)

            for i, node in enumerate(topic['nodes']):
                topic['nodes'][i] = yield NodeDocument.translate_dbref(node)

        raise gen.Return(topic)
Example #23
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))
Example #24
0
    def get(self, user_id=None):
        user_id = user_id or self.current_user['_id']

        kwargs = yield self.get_header_arguments(user_id)
        if not kwargs['can_seen']:
            self.render('profile/template/profile-visitor.html', **kwargs)
        else:
            status_list = yield StatusDocument.get_status_list(
                user_id,
                self.current_user['_id'],
                limit=PROFILE_SETTINGS['status_number_per_page']
            )

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

            if kwargs['user']['user_type'] == 'league':
                member_list = yield LeagueMemberDocument.get_member(user_id)
                kwargs.update({'member_list': member_list})

            kwargs.update({
                'status_list': status_list,
                'recommend_friend_list': recommend_friend_list,
                'PROFILE_SETTINGS': PROFILE_SETTINGS
            })

            self.render('profile/template/status/status.html', **kwargs)
Example #25
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()
Example #26
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)
Example #27
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()
Example #28
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()
Example #29
0
    def post(self):
        form = ProfileSetForm(self.request.arguments)
        if not form.validate():
            raise HTTPError(404)

        response_data = {}

        sex = form.sex.data
        birthday = form.birthday.data
        relationship_status = form.relationship_status.data
        province = form.province.data
        city = form.city.data
        phone = form.phone.data
        qq = form.qq.data
        signature = form.signature.data

        document = {}

        if birthday:
            year, month, day = map(int, birthday.split('-'))
            birthday = datetime(year, month, day)
            document.update({'birthday': birthday})

        if sex:
            document.update({'sex': sex})

        if relationship_status not in ['', 'single', 'in_love']:
            raise HTTPError(404)

        document.update({'relationship_status': relationship_status})

        if province and city:
            home = '%s-%s' % (province, city)
            if len(home) < 100:
                document.update({'home': home})
            else:
                raise HTTPError(404)

        regex = re.compile('^\d{11}$')
        document.update({'phone': phone})
        if phone and not regex.match(phone):
            response_data.update({'error': '手机号码错误!'})

        regex = re.compile('^\d{1,20}$')
        document.update({'qq': qq})
        if qq and not regex.match(qq):
            response_data.update({'error': 'qq号码错误!'})

        document.update({'signature': signature})
        if signature and len(signature) > 100:
            response_data.update({'error': '自我介绍不能超过100字!'})

        if not response_data:
            yield UserDocument.update(
                {'_id': ObjectId(self.current_user['_id'])},
                {'$set': document}
            )

        self.write_json(response_data)
Example #30
0
    def post(self):
        recommend_friend_list = yield UserDocument.get_random_user_list(
            self.current_user['_id'])

        html = self.render_string(
            'profile/template/status/friend-recommend.html',
            recommend_friend_list=recommend_friend_list)
        self.finish(json.dumps({'html': html}))
Example #31
0
    def get_active_author_list(node_id=None, period=None, skip=0, limit=None):
        '''得到某一节点下的活跃用户排名

        :Parameters:
          - `node_id`: 如果不为None, 则表示某一节点下的活跃用户
          - `period`: 如果不为None, 则为timedelta类型, 表示从现在往前算多长时间内的活跃用户
          - `skip`: 默认0
          - `limit`: 默认None
        '''

        query = {
            'anonymous': False,
        }
        if node_id is not None:
            query.update({
                'nodes':
                DBRef(NodeDocument.meta['collection'], ObjectId(node_id))
            })

        if period is not None:
            begin = datetime.now() - period
            query.update({'publish_time': {'$gt': begin}})

        aggregate_pipeline = [{
            '$match': query
        }, {
            '$group': {
                '_id': {
                    'author': '$author'
                },
                'times': {
                    '$sum': 1
                }
            }
        }, {
            '$sort': {
                'times': -1
            }
        }, {
            '$skip': skip
        }, {
            '$limit': limit
        }]

        cursor = TopicStatisticsDocument.aggregate(aggregate_pipeline)

        author_list = []
        while (yield cursor.fetch_next):
            item = cursor.next_object()
            author_list.append({
                'author': item['_id']['author'],
                'times': item['times']
            })

        author_list = yield UserDocument.translate_dbref_in_document_list(
            author_list)

        raise gen.Return(author_list)
Example #32
0
    def post(self):
        '''换一批推荐'''

        random_user_list = yield UserDocument.get_random_user_list(
            self.current_user['_id'])
        html = self.render_string('home/template/friend-recommend.html',
                                  random_user_list=random_user_list)

        self.write_json({'html': html})
Example #33
0
    def post(self):
        recommend_friend_list = yield UserDocument.get_random_user_list(
            self.current_user['_id']
        )

        html = self.render_string(
            'profile/template/status/friend-recommend.html',
            recommend_friend_list=recommend_friend_list
        )
        self.write_json({'html': html})
Example #34
0
    def get_comment_list(share_id, skip=0, limit=None):
        cursor = ShareCommentDocument.find({
            'share':
            DBRef(ShareDocument.meta['collection'], ObjectId(share_id))
        }).sort([('comment_time', pymongo.ASCENDING)]).skip(skip)

        if limit is not None:
            cursor = cursor.limit(limit)

        comment_list = yield ShareCommentDocument.to_list(cursor)

        for i, comment in enumerate(comment_list):
            comment['floor'] = skip + 1 + i
            comment['author'] = yield UserDocument.translate_dbref(
                comment['author'])
            if 'replyeder' in comment:
                comment['replyeder'] = yield UserDocument.translate_dbref(
                    comment['replyeder'])

        raise gen.Return(comment_list)
Example #35
0
    def post(self):
        form = LeagueBulletinSaveForm(self.request.arguments)
        if not form.validate() or self.current_user['user_type'] != 'league':
            raise HTTPError(404)

        league_bulletin = form.league_bulletin.data

        yield UserDocument.update(
            {'_id': ObjectId(self.current_user['_id'])},
            {'$set': {'league_bulletin': league_bulletin}}
        )
Example #36
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)
Example #37
0
    def post(self):
        '''换一批推荐'''

        random_user_list = yield UserDocument.get_random_user_list(
            self.current_user['_id']
        )
        html = self.render_string(
            'home/template/friend-recommend.html',
            random_user_list=random_user_list
        )

        self.write_json({'html': html})
Example #38
0
    def get_comment_list(topic_id, skip=0, limit=None):
        cursor = TopicCommentDocument.find({
            'topic': DBRef(TopicDocument.meta['collection'], ObjectId(topic_id))
        }).sort([('comment_time', pymongo.ASCENDING)]).skip(skip)

        if limit is not None:
            cursor = cursor.limit(limit)

        comment_list = yield TopicCommentDocument.to_list(cursor)
        for i, comment in enumerate(comment_list):
            comment['floor'] = skip + 1 + i
            comment['author'] = yield UserDocument.translate_dbref(
                comment['author']
            )

            if 'replyeder' in comment:
                comment['replyeder'] = yield UserDocument.translate_dbref(
                    comment['replyeder']
                )

        raise gen.Return(comment_list)
Example #39
0
    def get_like_list(topic_id, skip=0, limit=None):
        cursor = TopicLikeDocument.find({
            'topic': DBRef(TopicDocument.meta['collection'], ObjectId(topic_id))
        }).sort([('like_time', pymongo.DESCENDING)]).skip(skip)

        if limit is not None:
            cursor = cursor.limit(limit)

        like_list = yield TopicLikeDocument.to_list(cursor)
        for like in like_list:
            like['liker'] = yield UserDocument.translate_dbref(like['liker'])

        raise gen.Return(like_list)
Example #40
0
    def post(self):
        response_data = {}

        form = PasswordSetForm(self.request.arguments)
        if form.validate():
            current_password = form.current_password.data
            new_password = form.new_password.data
            repeat_password = form.repeat_password.data

            encrypt_password = yield UserDocument.encrypt_password(
                current_password
            )

            if self.current_user['password'] != encrypt_password:
                response_data.update({'error': '密码错误!'})
            elif new_password != repeat_password:
                response_data.update({'error': '新密码与重复密码不一致!'})
            else:
                new_password = yield UserDocument.encrypt_password(
                    new_password
                )

                yield UserDocument.update(
                    {'_id': ObjectId(self.current_user['_id'])},
                    {'$set': {'password': new_password}}
                )

                try:
                    Ejabberd.unregister(self.current_user['_id'])
                    Ejabberd.register(self.current_user['_id'], new_password)
                except:
                    pass
        else:
            for field in form.errors:
                response_data.update({'error': form.errors[field][0]})
                break

        self.write_json(response_data)
Example #41
0
    def get_like_list(share_id, skip=0, limit=None):
        cursor = ShareLikeDocument.find({
            'share':
            DBRef(ShareDocument.meta['collection'], ObjectId(share_id))
        }).sort([('like_time', pymongo.DESCENDING)]).skip(skip)

        if limit is not None:
            cursor = cursor.limit(limit)

        like_list = yield ShareLikeDocument.to_list(cursor)
        for like in like_list:
            like['liker'] = yield UserDocument.translate_dbref(like['liker'])

        raise gen.Return(like_list)
Example #42
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')
Example #43
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)
Example #44
0
    def get_active_author_list(node_id=None, period=None, skip=0, limit=None):
        '''得到某一节点下的活跃用户排名

        :Parameters:
          - `node_id`: 如果不为None, 则表示某一节点下的活跃用户
          - `period`: 如果不为None, 则为timedelta类型, 表示从现在往前算多长时间内的活跃用户
          - `skip`: 默认0
          - `limit`: 默认None
        '''

        query = {
            'anonymous': False,
        }
        if node_id is not None:
            query.update({
                'nodes': DBRef(NodeDocument.meta['collection'],
                               ObjectId(node_id))
            })

        if period is not None:
            begin = datetime.now() - period
            query.update({'publish_time': {'$gt': begin}})

        aggregate_pipeline = [
            {'$match': query},
            {'$group': {'_id': {'author': '$author'}, 'times': {'$sum': 1}}},
            {'$sort': {'times': -1}},
            {'$skip': skip},
            {'$limit': limit}
        ]

        cursor = TopicStatisticsDocument.aggregate(aggregate_pipeline)

        author_list = []
        while (yield cursor.fetch_next):
            item = cursor.next_object()
            author_list.append({
                'author': item['_id']['author'],
                'times': item['times']
            })

        author_list = yield UserDocument.translate_dbref_in_document_list(
            author_list
        )

        raise gen.Return(author_list)
Example #45
0
    def get_last_comment(topic_id):
        '''得到某一话题的最后一个回复'''

        cursor = TopicCommentDocument.find({
            'topic': DBRef(TopicDocument.meta['collection'], ObjectId(topic_id))
        }).sort([('comment_time', pymongo.DESCENDING)]).limit(1)

        comment_list = yield TopicCommentDocument.to_list(cursor)

        last_comment = None
        if comment_list:
            last_comment = comment_list[0]
            last_comment['author'] = yield UserDocument.translate_dbref(
                last_comment['author']
            )

        raise gen.Return(last_comment)
Example #46
0
    def get_last_comment(topic_id):
        '''得到某一话题的最后一个回复'''

        cursor = TopicCommentDocument.find({
            'topic':
            DBRef(TopicDocument.meta['collection'], ObjectId(topic_id))
        }).sort([('comment_time', pymongo.DESCENDING)]).limit(1)

        comment_list = yield TopicCommentDocument.to_list(cursor)

        last_comment = None
        if comment_list:
            last_comment = comment_list[0]
            last_comment['author'] = yield UserDocument.translate_dbref(
                last_comment['author'])

        raise gen.Return(last_comment)
Example #47
0
def _send_email_handler(message, type_="activate"):
    from app.user.document import CodeDocument, UserDocument

    code_id = message.body

    code = CodeDocument.get_collection(True).find_one({
        '_id': ObjectId(code_id)
    })
    if not code:
        return True

    user = UserDocument.get_collection(True).find_one({
        "_id": ObjectId(code["uid"])
    })
    if not user:
        return True

    if type_ == "activate":
        subject = "账号激活【Young社区】"
        tpl = ''.join([
            '请点击链接激活你的Young社区帐号!',
            '<a href="{0}/account/active?uid={1}&code={2}">',
            '{0}/account/active?uid={1}&code={2}</a>'
        ])
    else:
        subject = "密码重置【Young社区】"
        tpl = ''.join([
            '请点击链接重置你的Young社区账号密码!',
            '<a href="{0}/password/reset?uid={1}&code={2}">',
            '{0}/password/reset?uid={1}&code={2}</a>'
        ])

    body = tpl.format(EMAIL_SETTINGS['url'], code['uid'], code['code'])

    msg = MIMEText(body, "html", 'utf-8')
    msg["subject"] = subject

    try:
        send_email(user['email'], msg)
    except Exception as e:
        logging.error('%s' % e)

    return True
Example #48
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))
Example #49
0
    def get_recommend_topic_list(topic_id, size=10):
        '''根据某一话题推荐话题'''

        topic_list = []

        topic = yield TopicDocument.find_one({'_id': ObjectId(topic_id)})
        if topic:
            query = {
                '$and': [{
                    '_id': {
                        '$ne': ObjectId(topic_id)
                    }
                }, {
                    '$or': [{
                        'nodes': node
                    } for node in topic['nodes']]
                }]
            }
            count = yield TopicDocument.find(query).count()
            if count > size:
                skip = random.randint(0, count - size)
                cursor = TopicDocument.find(query).skip(skip).limit(size)
            else:
                cursor = TopicDocument.find(query)

            topic_list = yield TopicDocument.to_list(cursor)
            if not topic_list or len(topic_list) < size:
                query = {'$and': [{'_id': {'$ne': ObjectId(topic_id)}}]}
                count = yield TopicDocument.find(query).count()
                if count > size:
                    skip = random.randint(0, count - size)
                    cursor = TopicDocument.find(query).skip(skip).limit(size)
                else:
                    cursor = TopicDocument.find(query)

                topic_list = yield TopicDocument.to_list(cursor)

            for topic in topic_list:
                topic['author'] = yield UserDocument.translate_dbref(
                    topic['author'])

        raise gen.Return(topic_list)
Example #50
0
    def get_recommend_topic_list(topic_id, size=10):
        '''根据某一话题推荐话题'''

        topic_list = []

        topic = yield TopicDocument.find_one({'_id': ObjectId(topic_id)})
        if topic:
            query = {
                '$and': [
                    {'_id': {'$ne': ObjectId(topic_id)}},
                    {'$or': [{'nodes': node} for node in topic['nodes']]}
                ]
            }
            count = yield TopicDocument.find(query).count()
            if count > size:
                skip = random.randint(0, count - size)
                cursor = TopicDocument.find(query).skip(skip).limit(size)
            else:
                cursor = TopicDocument.find(query)

            topic_list = yield TopicDocument.to_list(cursor)
            if not topic_list or len(topic_list) < size:
                query = {
                    '$and': [
                        {'_id': {'$ne': ObjectId(topic_id)}}
                    ]
                }
                count = yield TopicDocument.find(query).count()
                if count > size:
                    skip = random.randint(0, count - size)
                    cursor = TopicDocument.find(query).skip(skip).limit(size)
                else:
                    cursor = TopicDocument.find(query)

                topic_list = yield TopicDocument.to_list(cursor)

            for topic in topic_list:
                topic['author'] = yield UserDocument.translate_dbref(
                    topic['author']
                )

        raise gen.Return(topic_list)
Example #51
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')
Example #52
0
def _send_email_handler(message, type_="activate"):
    from app.user.document import CodeDocument, UserDocument

    code_id = message.body

    code = CodeDocument.get_collection(True).find_one(
        {'_id': ObjectId(code_id)})
    if not code:
        return True

    user = UserDocument.get_collection(True).find_one(
        {"_id": ObjectId(code["uid"])})
    if not user:
        return True

    if type_ == "activate":
        subject = "账号激活【Young社区】"
        tpl = ''.join([
            '请点击链接激活你的Young社区帐号!',
            '<a href="{0}/account/active?uid={1}&code={2}">',
            '{0}/account/active?uid={1}&code={2}</a>'
        ])
    else:
        subject = "密码重置【Young社区】"
        tpl = ''.join([
            '请点击链接重置你的Young社区账号密码!',
            '<a href="{0}/password/reset?uid={1}&code={2}">',
            '{0}/password/reset?uid={1}&code={2}</a>'
        ])

    body = tpl.format(EMAIL_SETTINGS['url'], code['uid'], code['code'])

    msg = MIMEText(body, "html", 'utf-8')
    msg["subject"] = subject

    try:
        send_email(user['email'], msg)
    except Exception as e:
        logging.error('%s' % e)

    return True
Example #53
0
    def get_topic_list_by_someone(author_id, skip=0, limit=None):
        '''得到某人的话题'''

        cursor = TopicDocument.find({
            'author':
            DBRef(UserDocument.meta['collection'], ObjectId(author_id))
        }).sort([('publish_time', pymongo.DESCENDING)]).skip(skip)

        if limit is not None:
            cursor = cursor.limit(limit)

        topic_list = yield TopicDocument.to_list(cursor)
        for topic in topic_list:
            topic['author'] = yield UserDocument.translate_dbref(
                topic['author'])
            topic[
                'last_comment'] = yield TopicCommentDocument.get_last_comment(
                    topic['_id'])

            for i, node in enumerate(topic['nodes']):
                topic['nodes'][i] = yield NodeDocument.translate_dbref(node)

        raise gen.Return(topic_list)
Example #54
0
    def post(self):
        response_data = {}

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

        topic_id = form.topic_id.data

        topic = yield TopicDocument.find_one({'_id': ObjectId(topic_id)})
        if not topic:
            raise HTTPError(404)

        can_afford = yield UserDocument.can_afford(self.current_user['_id'],
                                                   WEALTH_SETTINGS['like'])

        if not can_afford and str(self.current_user['_id']) != str(
                topic['author'].id):
            response_data.update({'error': '金币不足!'})

        topic_dbref = DBRef(TopicDocument.meta['collection'],
                            ObjectId(topic_id))
        liker_dbref = DBRef(UserDocument.meta['collection'],
                            ObjectId(self.current_user['_id']))

        document = {'topic': topic_dbref, 'liker': liker_dbref}

        liked = yield TopicLikeDocument.is_liked(topic_id,
                                                 self.current_user['_id'])

        if not liked and not response_data:
            now = datetime.now()
            document.update({'like_time': now})
            like_id = yield TopicLikeDocument.insert_one(document)

            if str(self.current_user['_id']) != str(topic['author'].id):
                document = {
                    'user':
                    DBRef(UserDocument.meta['collection'],
                          ObjectId(self.current_user['_id'])),
                    'activity_type':
                    UserActivityDocument.LIKE,
                    'time':
                    now,
                    'data':
                    DBRef(TopicLikeDocument.meta['collection'],
                          ObjectId(like_id))
                }
                activity_id = yield UserActivityDocument.insert(document)

                # 赞者
                document = {
                    'user':
                    DBRef(UserDocument.meta['collection'],
                          ObjectId(self.current_user['_id'])),
                    'in_out_type':
                    WealthRecordDocument.OUT,
                    'activity':
                    DBRef(UserActivityDocument.meta['collection'],
                          ObjectId(activity_id)),
                    'quantity':
                    WEALTH_SETTINGS['like'],
                    'time':
                    now
                }
                yield WealthRecordDocument.insert(document)
                yield UserDocument.update_wealth(self.current_user['_id'],
                                                 -WEALTH_SETTINGS['like'])

                # 被赞者
                document = {
                    'user':
                    DBRef(UserDocument.meta['collection'],
                          ObjectId(topic['author'].id)),
                    'in_out_type':
                    WealthRecordDocument.IN,
                    'activity':
                    DBRef(UserActivityDocument.meta['collection'],
                          ObjectId(activity_id)),
                    'quantity':
                    WEALTH_SETTINGS['like'],
                    'time':
                    now
                }
                yield WealthRecordDocument.insert(document)
                yield UserDocument.update_wealth(topic['author'].id,
                                                 WEALTH_SETTINGS['like'])

                document = {
                    'sender':
                    DBRef(UserDocument.meta['collection'],
                          ObjectId(self.current_user['_id'])),
                    'recipient':
                    DBRef(UserDocument.meta['collection'],
                          ObjectId(topic['author'].id)),
                    'message_type':
                    'like:topic',
                    'time':
                    now,
                    'read':
                    False,
                    'data':
                    DBRef(TopicLikeDocument.meta['collection'],
                          ObjectId(like_id))
                }

                message_id = yield MessageDocument.insert(document)
                WriterManager.pub(MessageTopic.LIKE, message_id)

        like_times = yield TopicLikeDocument.get_like_times(topic_id)
        response_data.update({'like_times': like_times})

        self.write_json(response_data)
Example #55
0
def send_has_unread_message_email_handler(message):
    '''如果用户不在线就发送邮件'''

    from young.handler import BaseHandler
    from app.user.document import UserDocument
    from app.message.document import MessageDocument

    message = MessageDocument.get_collection(pymongo=True).find_one(
        {'_id': ObjectId(message.body)}
    )

    if not message:
        return True

    recipient_id = message['recipient'].id
    topic = MessageTopic.message_type2topic(message['message_type'])

    recipient = UserDocument.get_user_sync(recipient_id)
    if recipient and recipient['activated']:
        message = BaseHandler.translate_dbref_in_document(message)
        if 'data' in message:
            message['data'] = BaseHandler.translate_dbref_in_document(
                message['data'], depth=2
            )

        kwargs = {
            'message_topic': topic,
            'message': message,
            'MessageTopic': MessageTopic,
            'handler': BaseHandler
        }

        root = os.path.dirname(os.path.dirname(
            os.path.dirname(os.path.abspath(__file__))
        ))
        path = os.path.join(root, 'app/message/template')

        loader = template.Loader(path)
        html = loader.load("message.html").generate(**kwargs)

        soup = BeautifulSoup(html, "html.parser")
        link_list = soup.find_all('a')
        for link in link_list:
            new_link = link
            if link['href'].startswith('/'):
                new_link['href'] = EMAIL_SETTINGS['url'] + link['href']
                link.replace_with(new_link)

        img_list = soup.find_all('img')
        for img in img_list:
            new_img = img
            if img['src'].startswith('/'):
                new_img['src'] = EMAIL_SETTINGS['url'] + img['src']
                img.replace_with(new_img)

        body = (
            '{} &nbsp;&nbsp; <a href="{}/setting/notification">'
            '关闭邮件提醒</a>'
        ).format(soup.prettify(), EMAIL_SETTINGS["url"])

        msg = MIMEText(body, "html", 'utf-8')
        msg["subject"] = "你有未读消息【Young社区】"
        send_email(recipient['email'], msg)

    return True
Example #56
0
    def _new_chat_message_handler(self, messages):
        '''处理未读的聊天信息, 返回前端易于处理的json格式. 返回的格式为:
        {
            'topic': MessageTopic.CHAT_MESSAGE_NEW,
            'each_people':
            [
                {
                    'sender': {'id': xxx, 'name': xxx},
                    'messages':
                    [
                        {
                            'body': xxx,
                            'html': xxx,
                            'since': xxx
                        },
                    ]
                },
            ]
        }

        :Parameters:
            - `messages`: ChatMessageDocument.get_unread_messages()相同的格式. 即:
              [
                  {
                      '_id': xxx,
                      'messages':
                      [
                          {
                              'send_time': xxx,
                              'body': xxx,
                          },
                      ]
                  },
              ]
        '''

        response_data = {
            'topic': MessageTopic.CHAT_MESSAGE_NEW,
            'each_people': []
        }
        for item in messages:
            sender_id = str(item['_id'].id)
            sender = UserDocument.get_collection(pymongo=True).find_one({
                '_id': ObjectId(sender_id)
            })

            each_people = {
                'sender': {
                    'id': sender_id,
                    'name': sender['name']
                },
                'messages': []
            }
            for message in item['messages']:
                html = self.render_string(
                    "chat/template/message-others.html",
                    message=message, handler=self
                )

                new_message = {
                    'body': xhtml_escape(message['body']),
                    'html': html,
                    'since': time.mktime(
                        message['send_time'].timetuple()
                    ) * 1000
                }
                each_people['messages'].append(new_message)
            response_data['each_people'].append(each_people)

        return response_data
Example #57
0
    def get(self, share_id):
        share = yield ShareDocument.get_share(share_id)

        if not share or not share['passed'] or 'origin_file' not in share:
            raise HTTPError(404)

        self.set_header('Content-Type', self.get_content_type(share))
        self.set_header(
            'Content-Disposition',
            'attachment; filename=%s' % self.get_filename(share)
        )

        fs = self.get_gridfs()
        gridout = yield fs.get(ObjectId(share['origin_file']))
        if gridout.length <= 0:
            raise HTTPError(404)

        if (self.current_user['_id'] != share['uploader']['_id']
                and self.current_user['wealth'] < share['cost']):
            raise HTTPError(404)

        size = 0
        while size < gridout.length:
            content = yield gridout.read(gridout.chunk_size)
            size += len(content)
            self.write(content)

        yield ShareDocument.update(
            {'_id': ObjectId(share_id)},
            {'$inc': {'download_times': 1}}
        )

        now = datetime.now()
        document = {
            'user': DBRef(
                UserDocument.meta['collection'],
                ObjectId(self.current_user['_id'])
            ),
            'activity_type': UserActivityDocument.DOWNLOAD_SHARE,
            'time': now,
            'data': DBRef(
                ShareDocument.meta['collection'],
                ObjectId(share_id)
            )
        }
        activity_id = yield UserActivityDocument.insert(document)

        document = {
            'share': DBRef(
                ShareDocument.meta['collection'],
                ObjectId(share_id)
            ),
            'downloader': DBRef(
                UserDocument.meta['collection'],
                ObjectId(self.current_user['_id'])
            ),
            'download_time': now
        }
        yield ShareDownloadDocument.insert(document)

        if (share['cost'] > 0 and
                self.current_user['_id'] != share['uploader']['_id']):
            document = {
                'user': DBRef(
                    UserDocument.meta['collection'],
                    ObjectId(self.current_user['_id'])
                ),
                'in_out_type': WealthRecordDocument.OUT,
                'activity': DBRef(
                    UserActivityDocument.meta['collection'],
                    ObjectId(activity_id)
                ),
                'quantity': share['cost'],
                'time': now
            }
            yield WealthRecordDocument.insert(document)
            yield UserDocument.update_wealth(
                self.current_user['_id'], -share['cost']
            )

            document = {
                'user': DBRef(
                    UserDocument.meta['collection'],
                    ObjectId(share['uploader']['_id'])
                ),
                'in_out_type': WealthRecordDocument.IN,
                'activity': DBRef(
                    UserActivityDocument.meta['collection'],
                    ObjectId(activity_id)
                ),
                'quantity': share['cost'],
                'time': now
            }
            yield WealthRecordDocument.insert(document)
            yield UserDocument.update_wealth(
                share['uploader']['_id'], share['cost']
            )

        self.finish()
Example #58
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)
Example #59
0
    def post(self):
        form = ShareLikeForm(self.request.arguments)
        if not form.validate():
            raise HTTPError(404)

        response_data = {}
        share_id = form.share_id.data

        share = yield ShareDocument.find_one({
            '_id': ObjectId(share_id)
        })
        if not share:
            raise HTTPError(404)

        can_afford = yield UserDocument.can_afford(
            self.current_user['_id'], WEALTH_SETTINGS['like']
        )

        if (not can_afford and
                str(self.current_user['_id']) != str(share['uploader'].id)):
            response_data.update({'error': '金币不足!'})

        share_dbref = DBRef(
            ShareDocument.meta['collection'],
            ObjectId(share_id)
        )
        liker_dbref = DBRef(
            UserDocument.meta['collection'],
            ObjectId(self.current_user['_id'])
        )

        document = {
            'share': share_dbref,
            'liker': liker_dbref
        }

        liked = yield ShareLikeDocument.is_liked(
            share_id, self.current_user['_id']
        )
        if not liked and not response_data:
            now = datetime.now()

            document.update({
                'like_time': now
            })
            like_id = yield ShareLikeDocument.insert_one(document)

            if str(self.current_user['_id']) != str(share['uploader'].id):
                activity = {
                    'user': DBRef(
                        UserDocument.meta['collection'],
                        ObjectId(self.current_user['_id'])
                    ),
                    'activity_type': UserActivityDocument.LIKE,
                    'time': now,
                    'data': DBRef(
                        ShareLikeDocument.meta['collection'],
                        ObjectId(like_id)
                    )
                }
                activity_id = yield UserActivityDocument.insert(activity)

                # 赞者
                wealth = {
                    'user': DBRef(
                        UserDocument.meta['collection'],
                        ObjectId(self.current_user['_id'])
                    ),
                    'in_out_type': WealthRecordDocument.OUT,
                    'activity': DBRef(
                        UserActivityDocument.meta['collection'],
                        ObjectId(activity_id)
                    ),
                    'quantity': WEALTH_SETTINGS['like'],
                    'time': now
                }
                yield WealthRecordDocument.insert(wealth)
                yield UserDocument.update_wealth(
                    self.current_user['_id'], -WEALTH_SETTINGS['like']
                )

                # 被赞者
                wealth = {
                    'user': DBRef(
                        UserDocument.meta['collection'],
                        ObjectId(share['uploader'].id)
                    ),
                    'in_out_type': WealthRecordDocument.IN,
                    'activity': DBRef(
                        UserActivityDocument.meta['collection'],
                        ObjectId(activity_id)
                    ),
                    'quantity': WEALTH_SETTINGS['like'],
                    'time': now
                }
                yield WealthRecordDocument.insert(wealth)
                yield UserDocument.update_wealth(
                    share['uploader'].id, WEALTH_SETTINGS['like']
                )

                message = {
                    'sender': DBRef(
                        UserDocument.meta['collection'],
                        ObjectId(self.current_user['_id'])
                    ),
                    'recipient': DBRef(
                        UserDocument.meta['collection'],
                        ObjectId(share['uploader'].id)
                    ),
                    'message_type': 'like:share',
                    'time': now,
                    'read': False,
                    'data': DBRef(
                        ShareLikeDocument.meta['collection'],
                        ObjectId(like_id)
                    )
                }

                message_id = yield MessageDocument.insert(message)
                WriterManager.pub(MessageTopic.LIKE, str(message_id))

        like_times = yield ShareLikeDocument.get_like_times(share_id)
        response_data.update({'like_times': like_times})

        self.write_json(response_data)