Exemplo n.º 1
0
    def post(self):
        form = NodeDescriptionEditForm(self.request.arguments)
        if not form.validate():
            raise HTTPError(404)

        node_id = form.node_id.data
        description = form.description.data

        node = yield NodeDocument.find_one({'_id': ObjectId(node_id)})
        if not node:
            raise HTTPError(404)

        yield NodeDocument.update(
            {'_id': ObjectId(node_id)},
            {'$set': {
                'description': description,
                'last_modified_by': DBRef(
                    UserDocument.meta['collection'],
                    ObjectId(self.current_user['_id'])
                ),
                'last_modified_time': datetime.now()
            }}
        )

        node = yield NodeDocument.get_node(node_id)
        html = self.render_string(
            'community/template/node-description.html',
            current_node=node
        )

        self.write_json({'html': html})
Exemplo n.º 2
0
    def post(self):
        form = NodeDescriptionEditForm(self.request.arguments)
        if not form.validate():
            raise HTTPError(404)

        node_id = form.node_id.data
        description = form.description.data

        node = yield NodeDocument.find_one({'_id': ObjectId(node_id)})
        if not node:
            raise HTTPError(404)

        yield NodeDocument.update({'_id': ObjectId(node_id)}, {
            '$set': {
                'description':
                description,
                'last_modified_by':
                DBRef(UserDocument.meta['collection'],
                      ObjectId(self.current_user['_id'])),
                'last_modified_time':
                datetime.now()
            }
        })

        node = yield NodeDocument.get_node(node_id)
        html = self.render_string('community/template/node-description.html',
                                  current_node=node)

        self.write_json({'html': html})
Exemplo n.º 3
0
    def get(self):
        sort = self.get_argument('sort', "time")
        if sort not in ['time', 'popularity']:
            sort = 'time'

        node = self.get_argument('node', None)
        try:
            page = max(int(self.get_argument("page", 1)), 1)
        except:
            page = 1

        query = {
            'user_id': self.current_user and self.current_user['_id'],
            'sort': sort,
            'skip': (page - 1) * COMMUNITY_SETTINGS["topic_number_per_page"],
            'limit': COMMUNITY_SETTINGS['topic_number_per_page']
        }
        if node:
            node = yield NodeDocument.get_node(node)
            if not node:
                raise HTTPError(404)

            query.update({'node_id': node['_id']})

        topic_list = yield TopicDocument.get_topic_list(**query)
        hot_topic_list = yield TopicDocument.get_hot_topic_list(
            period=timedelta(days=1),
            limit=COMMUNITY_SETTINGS['hot_topic_number']
        )
        hot_node_list = yield NodeDocument.get_hot_node_list(
            size=COMMUNITY_SETTINGS['hot_node_number']
        )
        top_header_node_list = yield NodeDocument.get_top_header_node_list()

        total_page, pages = self.paginate(
            (yield TopicDocument.get_topic_number(node and node['_id'])),
            COMMUNITY_SETTINGS['topic_number_per_page'],
            page
        )

        kwargs = {}
        if self.current_user:
            kwargs = yield self.get_sidebar_arguments()

        kwargs.update({
            'sort': sort,
            'current_node': node,
            'topic_list': topic_list,
            'hot_topic_list': hot_topic_list,
            'top_header_node_list': top_header_node_list,
            'hot_node_list': hot_node_list,
            'page': page,
            'total_page': total_page,
            'pages': pages
        })

        self.render('community/template/community.html', **kwargs)
Exemplo n.º 4
0
    def post(self):
        form = TopicEditForm(self.request.arguments)
        if not form.validate():
            raise HTTPError(404)

        response_data = {}

        topic_id = form.topic_id.data
        title = form.title.data
        content = form.content.data
        nodes = form.nodes.data.split(',')
        anonymous = form.anonymous.data

        topic = yield TopicDocument.get_topic(
            topic_id, self.current_user['_id']
        )
        if (not topic or len(nodes) > 3 or
                topic['author']['_id'] != self.current_user['_id']):
            raise HTTPError(404)

        nodes = list(set(nodes))

        node_ids = []
        for node in nodes:
            existed = yield NodeDocument.find_one({'name': node})
            if existed:
                node_id = existed['_id']
            else:
                node_id = yield NodeDocument.insert({'name': node})

            node_ids.append(
                DBRef(NodeDocument.meta['collection'], ObjectId(node_id))
            )

        document = {
            'author': DBRef(
                UserDocument.meta['collection'],
                ObjectId(self.current_user['_id'])
            ),
            'title': title,
            'anonymous': anonymous,
            'nodes': node_ids,
            'content': content
        }

        images = yield self.get_images(content)
        document.update({'images': images})

        topic_id = yield TopicDocument.update(
            {'_id': ObjectId(topic_id)},
            {'$set': document}
        )

        self.write_json(response_data)
Exemplo n.º 5
0
    def post(self):
        form = TopicEditForm(self.request.arguments)
        if not form.validate():
            raise HTTPError(404)

        response_data = {}

        topic_id = form.topic_id.data
        title = form.title.data
        content = form.content.data
        nodes = form.nodes.data.split(',')
        anonymous = form.anonymous.data

        topic = yield TopicDocument.get_topic(topic_id,
                                              self.current_user['_id'])
        if (not topic or len(nodes) > 3
                or topic['author']['_id'] != self.current_user['_id']):
            raise HTTPError(404)

        nodes = list(set(nodes))

        node_ids = []
        for node in nodes:
            existed = yield NodeDocument.find_one({'name': node})
            if existed:
                node_id = existed['_id']
            else:
                node_id = yield NodeDocument.insert({'name': node})

            node_ids.append(
                DBRef(NodeDocument.meta['collection'], ObjectId(node_id)))

        document = {
            'author':
            DBRef(UserDocument.meta['collection'],
                  ObjectId(self.current_user['_id'])),
            'title':
            title,
            'anonymous':
            anonymous,
            'nodes':
            node_ids,
            'content':
            content
        }

        images = yield self.get_images(content)
        document.update({'images': images})

        topic_id = yield TopicDocument.update({'_id': ObjectId(topic_id)},
                                              {'$set': document})

        self.write_json(response_data)
Exemplo n.º 6
0
    def get(self):
        sort = self.get_argument('sort', "time")
        if sort not in ['time', 'popularity']:
            sort = 'time'

        node = self.get_argument('node', None)
        try:
            page = max(int(self.get_argument("page", 1)), 1)
        except:
            page = 1

        query = {
            'user_id': self.current_user and self.current_user['_id'],
            'sort': sort,
            'skip': (page - 1) * COMMUNITY_SETTINGS["topic_number_per_page"],
            'limit': COMMUNITY_SETTINGS['topic_number_per_page']
        }
        if node:
            node = yield NodeDocument.get_node(node)
            if not node:
                raise HTTPError(404)

            query.update({'node_id': node['_id']})

        topic_list = yield TopicDocument.get_topic_list(**query)
        hot_topic_list = yield TopicDocument.get_hot_topic_list(
            period=timedelta(days=1),
            limit=COMMUNITY_SETTINGS['hot_topic_number'])
        hot_node_list = yield NodeDocument.get_hot_node_list(
            size=COMMUNITY_SETTINGS['hot_node_number'])
        top_header_node_list = yield NodeDocument.get_top_header_node_list()

        total_page, pages = self.paginate(
            (yield TopicDocument.get_topic_number(node and node['_id'])),
            COMMUNITY_SETTINGS['topic_number_per_page'], page)

        kwargs = {}
        if self.current_user:
            kwargs = yield self.get_sidebar_arguments()

        kwargs.update({
            'sort': sort,
            'current_node': node,
            'topic_list': topic_list,
            'hot_topic_list': hot_topic_list,
            'top_header_node_list': top_header_node_list,
            'hot_node_list': hot_node_list,
            'page': page,
            'total_page': total_page,
            'pages': pages
        })

        self.render('community/template/community.html', **kwargs)
Exemplo n.º 7
0
def init_community_nodes():
    node_list = [
        u'问与答', u'分享', u'技术', u'小道消息', u'酷工作', u'求职', u'面经', u'交易', u'活动',
        u'考研', u'出国', u'原创小说', u'设计'
    ]

    for i, node in enumerate(node_list):
        document = {'name': node, 'sort': i, 'category': NodeDocument.BUILTIN}

        existed = yield NodeDocument.find_one({"name": node})
        if not existed:
            yield NodeDocument.insert(document)

    raise gen.Return()
Exemplo n.º 8
0
def init_community_nodes():
    node_list = [
        u'问与答', u'分享', u'技术', u'小道消息', u'酷工作', u'求职',
        u'面经', u'交易', u'活动', u'考研', u'出国', u'原创小说', u'设计']

    for i, node in enumerate(node_list):
        document = {
            'name': node,
            'sort': i,
            'category': NodeDocument.BUILTIN
        }

        existed = yield NodeDocument.find_one({"name": node})
        if not existed:
            yield NodeDocument.insert(document)

    raise gen.Return()
Exemplo n.º 9
0
    def get(self):
        node_id = self.get_argument("node_id", None)

        node = None
        if node_id:
            node = yield NodeDocument.get_node(node_id)
            if not node:
                node = None

        self.render("community/template/topic-new.html",
                    action="new",
                    node_one=node)
Exemplo n.º 10
0
    def post(self):
        form = NodeDescriptionEditTemplateForm(self.request.arguments)
        if not form.validate():
            raise HTTPError(404)

        node_id = form.node_id.data

        node = yield NodeDocument.find_one({'_id': ObjectId(node_id)})
        if not node:
            raise HTTPError(404)

        self.render('community/template/node-description-edit-template.html',
                    node=node)
Exemplo n.º 11
0
    def get(self):
        node_id = self.get_argument("node_id", None)

        node = None
        if node_id:
            node = yield NodeDocument.get_node(node_id)
            if not node:
                node = None

        self.render(
            "community/template/topic-new.html",
            action="new",
            node_one=node
        )
Exemplo n.º 12
0
    def post(self):
        form = NodeDescriptionEditTemplateForm(self.request.arguments)
        if not form.validate():
            raise HTTPError(404)

        node_id = form.node_id.data

        node = yield NodeDocument.find_one({'_id': ObjectId(node_id)})
        if not node:
            raise HTTPError(404)

        self.render(
            'community/template/node-description-edit-template.html',
            node=node
        )
Exemplo n.º 13
0
    def get(self, node_id):
        current_node = yield NodeDocument.get_node(node_id)
        if not current_node:
            raise HTTPError(404)

        sort = self.get_argument('sort', "time")
        if sort not in ['time', 'popularity']:
            sort = 'time'

        try:
            page = max(int(self.get_argument("page", 1)), 1)
        except:
            page = 1

        node_avatar_url = yield NodeAvatarDocument.get_node_avatar_url(
            node_id
        )
        topic_list = yield TopicDocument.get_topic_list(
            node_id=node_id,
            user_id=self.current_user and self.current_user['_id'],
            sort=sort,
            skip=(page - 1) * COMMUNITY_SETTINGS["topic_number_per_page"],
            limit=COMMUNITY_SETTINGS['topic_number_per_page']
        )
        active_author_list = yield TopicStatisticsDocument.get_active_author_list(
            node_id=node_id,
            period=timedelta(days=100),
            limit=10
        )
        total_page, pages = self.paginate(
            (yield TopicDocument.get_topic_number(current_node["_id"])),
            COMMUNITY_SETTINGS['topic_number_per_page'],
            page
        )

        kwargs = {
            'current_node': current_node,
            'node_avatar_url': node_avatar_url,
            'sort': sort,
            'topic_list': topic_list,
            'active_author_list': active_author_list,
            'page': page,
            'total_page': total_page,
            'pages': pages
        }

        self.render('community/template/node-one.html', **kwargs)
Exemplo n.º 14
0
    def get(self, node_id):
        current_node = yield NodeDocument.get_node(node_id)
        if not current_node:
            raise HTTPError(404)

        sort = self.get_argument('sort', "time")
        if sort not in ['time', 'popularity']:
            sort = 'time'

        try:
            page = max(int(self.get_argument("page", 1)), 1)
        except:
            page = 1

        node_avatar_url = yield NodeAvatarDocument.get_node_avatar_url(node_id)
        topic_list = yield TopicDocument.get_topic_list(
            node_id=node_id,
            user_id=self.current_user and self.current_user['_id'],
            sort=sort,
            skip=(page - 1) * COMMUNITY_SETTINGS["topic_number_per_page"],
            limit=COMMUNITY_SETTINGS['topic_number_per_page'])
        active_author_list = yield TopicStatisticsDocument.get_active_author_list(
            node_id=node_id, period=timedelta(days=100), limit=10)
        total_page, pages = self.paginate(
            (yield TopicDocument.get_topic_number(current_node["_id"])),
            COMMUNITY_SETTINGS['topic_number_per_page'], page)

        kwargs = {
            'current_node': current_node,
            'node_avatar_url': node_avatar_url,
            'sort': sort,
            'topic_list': topic_list,
            'active_author_list': active_author_list,
            'page': page,
            'total_page': total_page,
            'pages': pages
        }

        self.render('community/template/node-one.html', **kwargs)
Exemplo n.º 15
0
    def post(self):
        from app.base.document import ImageDocument

        form = NodeAvatarSetForm(self.request.arguments)
        if not form.validate() or 'avatar' not in self.request.files:
            raise HTTPError(404)

        node_id = form.node_id.data
        x = form.x.data
        y = form.y.data
        w = form.w.data
        h = form.h.data
        target_width = form.target_width.data

        node = yield NodeDocument.find_one({'_id': ObjectId(node_id)})
        if not node:
            raise HTTPError(404)

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

        now = datetime.now()
        document = {
            'name':
            upload_file['filename'],
            'body':
            Binary(upload_file['body']),
            'content_type':
            upload_file['content_type'].split('/')[1].upper(),
            'uploader':
            DBRef(UserDocument.meta['collection'],
                  ObjectId(self.current_user['_id'])),
            'upload_time':
            now
        }

        image = Image.open(StringIO(upload_file['body']))

        if image.size[0] < target_width:
            target_width = image.size[0]

        scale = image.size[0] * 1.0 / target_width

        x = int(x * scale)
        y = int(y * scale)
        w = int(w * scale)
        h = int(h * scale)

        box = (x, y, x + w, y + h)
        image = image.crop(box)

        output = StringIO()
        image = image.resize((64, 64),
                             Image.ANTIALIAS).save(output,
                                                   document['content_type'],
                                                   quality=100)
        document.update({'thumbnail': Binary(output.getvalue())})
        output.close()

        yield NodeAvatarDocument.remove_one({
            'node':
            DBRef(NodeDocument.meta['collection'], ObjectId(node_id))
        })

        image_id = yield ImageDocument.insert(document)

        document = {
            'node':
            DBRef(NodeDocument.meta['collection'], ObjectId(node_id)),
            'image':
            DBRef(ImageDocument.meta['collection'], ObjectId(image_id)),
            'uploader':
            DBRef(UserDocument.meta['collection'],
                  ObjectId(self.current_user['_id'])),
            'upload_time':
            now
        }
        yield NodeAvatarDocument.insert(document)

        self.finish()
Exemplo n.º 16
0
    def post(self):
        from app.base.document import ImageDocument

        form = NodeAvatarSetForm(self.request.arguments)
        if not form.validate() or 'avatar' not in self.request.files:
            raise HTTPError(404)

        node_id = form.node_id.data
        x = form.x.data
        y = form.y.data
        w = form.w.data
        h = form.h.data
        target_width = form.target_width.data

        node = yield NodeDocument.find_one({'_id': ObjectId(node_id)})
        if not node:
            raise HTTPError(404)

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

        now = datetime.now()
        document = {
            'name': upload_file['filename'],
            'body': Binary(upload_file['body']),
            'content_type': upload_file['content_type'].split('/')[1].upper(),
            'uploader': DBRef(
                UserDocument.meta['collection'],
                ObjectId(self.current_user['_id'])
            ),
            'upload_time': now
        }

        image = Image.open(StringIO(upload_file['body']))

        if image.size[0] < target_width:
            target_width = image.size[0]

        scale = image.size[0] * 1.0 / target_width

        x = int(x * scale)
        y = int(y * scale)
        w = int(w * scale)
        h = int(h * scale)

        box = (x, y, x + w, y + h)
        image = image.crop(box)

        output = StringIO()
        image = image.resize((64, 64), Image.ANTIALIAS).save(
            output, document['content_type'], quality=100
        )
        document.update({'thumbnail': Binary(output.getvalue())})
        output.close()

        yield NodeAvatarDocument.remove_one({
            'node': DBRef(
                NodeDocument.meta['collection'],
                ObjectId(node_id)
            )
        })

        image_id = yield ImageDocument.insert(document)

        document = {
            'node': DBRef(
                NodeDocument.meta['collection'],
                ObjectId(node_id)
            ),
            'image': DBRef(
                ImageDocument.meta['collection'],
                ObjectId(image_id)
            ),
            'uploader': DBRef(
                UserDocument.meta['collection'],
                ObjectId(self.current_user['_id'])
            ),
            'upload_time': now
        }
        yield NodeAvatarDocument.insert(document)

        self.finish()
Exemplo n.º 17
0
    def post(self):
        form = TopicNewForm(self.request.arguments)
        if not form.validate():
            raise HTTPError(404)

        response_data = {}

        title = form.title.data
        content = form.content.data
        nodes = form.nodes.data.split(',')
        anonymous = form.anonymous.data

        nodes = list(set(nodes))

        if len(nodes) > 3:
            response_data = {'error': '节点请不要超过3个!'}

        can_afford = yield UserDocument.can_afford(
            self.current_user['_id'], WEALTH_SETTINGS['topic_new'])
        if not can_afford:
            response_data = {'error': '金币不足!'}

        new_nodes = []
        for node in nodes:
            existed = yield NodeDocument.find_one({'name': node})
            if existed:
                node_id = existed['_id']
            else:
                node_id = yield NodeDocument.insert({'name': node})

            new_nodes.append(
                DBRef(NodeDocument.meta['collection'], ObjectId(node_id)))

        now = datetime.now()
        document = {
            'author':
            DBRef(UserDocument.meta['collection'],
                  ObjectId(self.current_user['_id'])),
            'title':
            title,
            'anonymous':
            anonymous,
            'nodes':
            new_nodes,
        }

        existed = yield TopicDocument.find_one(document)
        if existed and (now - existed['publish_time'] < timedelta(minutes=1)):
            response_data.update({'error': '你已经发布了一个相同的帖子!'})
        else:
            document.update({'publish_time': now, 'last_update_time': now})

        if not response_data:
            if content:
                document.update({'content': content})

                images = yield self.get_images(content)
                if images:
                    document.update({'images': images})

            topic_id = yield TopicDocument.insert_one(document)

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

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

            if not anonymous:
                friends = yield FriendDocument.get_reached_friends(
                    self.current_user['_id'])

                message_list = []
                for friend in friends:
                    document = {
                        'sender':
                        DBRef(UserDocument.meta['collection'],
                              ObjectId(self.current_user['_id'])),
                        'recipient':
                        DBRef(UserDocument.meta['collection'],
                              ObjectId(friend['_id'])),
                        'message_type':
                        MessageTopic.TOPIC_NEW,
                        'time':
                        now,
                        'read':
                        False,
                        'data':
                        DBRef(TopicDocument.meta['collection'],
                              ObjectId(topic_id))
                    }
                    message_id = yield MessageDocument.insert(document)
                    message_list.append(str(message_id))

                if message_list:
                    try:
                        WriterManager.mpub(MessageTopic.TOPIC_NEW,
                                           message_list)
                    except:
                        pass

        self.write_json(response_data)
Exemplo n.º 18
0
    def post(self):
        form = TopicNewForm(self.request.arguments)
        if not form.validate():
            raise HTTPError(404)

        response_data = {}

        title = form.title.data
        content = form.content.data
        nodes = form.nodes.data.split(',')
        anonymous = form.anonymous.data

        nodes = list(set(nodes))

        if len(nodes) > 3:
            response_data = {'error': '节点请不要超过3个!'}

        can_afford = yield UserDocument.can_afford(
            self.current_user['_id'], WEALTH_SETTINGS['topic_new']
        )
        if not can_afford:
            response_data = {'error': '金币不足!'}

        new_nodes = []
        for node in nodes:
            existed = yield NodeDocument.find_one({'name': node})
            if existed:
                node_id = existed['_id']
            else:
                node_id = yield NodeDocument.insert({'name': node})

            new_nodes.append(
                DBRef(NodeDocument.meta['collection'], ObjectId(node_id))
            )

        now = datetime.now()
        document = {
            'author': DBRef(
                UserDocument.meta['collection'],
                ObjectId(self.current_user['_id'])
            ),
            'title': title,
            'anonymous': anonymous,
            'nodes': new_nodes,
        }

        existed = yield TopicDocument.find_one(document)
        if existed and (now - existed['publish_time'] < timedelta(minutes=1)):
            response_data.update({'error': '你已经发布了一个相同的帖子!'})
        else:
            document.update({'publish_time': now, 'last_update_time': now})

        if not response_data:
            if content:
                document.update({'content': content})

                images = yield self.get_images(content)
                if images:
                    document.update({'images': images})

            topic_id = yield TopicDocument.insert_one(document)

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

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

            if not anonymous:
                friends = yield FriendDocument.get_reached_friends(
                    self.current_user['_id']
                )

                message_list = []
                for friend in friends:
                    document = {
                        'sender': DBRef(
                            UserDocument.meta['collection'],
                            ObjectId(self.current_user['_id'])
                        ),
                        'recipient': DBRef(
                            UserDocument.meta['collection'],
                            ObjectId(friend['_id'])
                        ),
                        'message_type': MessageTopic.TOPIC_NEW,
                        'time': now,
                        'read': False,
                        'data': DBRef(
                            TopicDocument.meta['collection'],
                            ObjectId(topic_id)
                        )
                    }
                    message_id = yield MessageDocument.insert(document)
                    message_list.append(str(message_id))

                if message_list:
                    try:
                        WriterManager.mpub(MessageTopic.TOPIC_NEW, message_list)
                    except:
                        pass

        self.write_json(response_data)