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

        form = StatusNewForm(self.request.arguments)
        if form.validate():
            content = form.content.data

            n = len(content)
            if n > HOME_SETTINGS['status_max_length']:
                response_data.update({
                    'error': (
                        '状态内容不能超过%s字' %
                        HOME_SETTINGS['status_max_length']
                    )
                })
            elif n <= 0 and not (
                    self.request.files and 'picture' in self.request.files):
                response_data.update({'error': '请输入文字内容或者照片'})
            else:
                picture = None
                if self.request.files and 'picture' in self.request.files:
                    picture = self.request.files['picture'][0]
                    image_types = [
                        'image/jpg', 'image/png', 'image/jpeg', 'image/gif'
                    ]
                    if picture['content_type'].lower() not in image_types:
                        response_data.update({
                            'error': '请上传jpg/png/gif格式的图片'
                        })

                if 'error' not in response_data:
                    now = datetime.now()

                    document = {
                        'author': DBRef(
                            UserDocument.meta['collection'],
                            self.current_user['_id']
                        ),
                        'publish_time': now,
                        'content': content
                    }
                    status_id = yield StatusDocument.insert(document)
                    friends = yield FriendDocument.get_reached_friends(
                        self.current_user['_id']
                    )

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

                    if message_list:
                        WriterManager.mpub(
                            MessageTopic.STATUS_NEW, message_list
                        )

                    if picture is not None:
                        try:
                            image = Image.open(StringIO(picture['body']))
                        except:
                            raise HTTPError(404)

                        try:
                            content_type = picture[
                                'content_type'
                            ].split('/')[-1].upper()
                        except:
                            content_type = 'JPEG'

                        document = {
                            'status': DBRef(
                                StatusDocument.meta['collection'],
                                ObjectId(status_id)
                            ),
                            'name': picture['filename'],
                            'content_type': content_type,
                            'upload_time': datetime.now()
                        }

                        width = 1024
                        if image.size[0] > width:
                            height = width * 1.0 * image.size[1] / image.size[0]
                            image = image.resize(
                                map(int, (width, height)), Image.ANTIALIAS
                            )

                        output = StringIO()
                        image.save(output, content_type, quality=100)
                        document.update({'body': Binary(output.getvalue())})
                        output.close()

                        thumbnail_width = 200
                        thumbnail_height = (
                            thumbnail_width * 1.0 * image.size[1] / image.size[0]
                        )

                        output = StringIO()
                        image = image.resize(
                            map(int, (thumbnail_width, thumbnail_height)),
                            Image.ANTIALIAS
                        )
                        image.save(output, content_type, quality=100)
                        document.update({
                            'thumbnail': Binary(output.getvalue())
                        })
                        output.close()

                        yield StatusPhotoDocument.insert(document)

                    status = yield StatusDocument.get_status(
                        status_id, self.current_user['_id']
                    )
                    html = self.render_string(
                        'home/template/status/status-list-item.html',
                        status=status
                    )
                    response_data.update({'html': html})
        else:
            for field in form.errors:
                response_data.update({'error': form.errors[field][0]})
                break

        self.write_json(response_data)
Exemple #3
0
    def post(self):
        response_data = {}

        form = StatusNewForm(self.request.arguments)
        if form.validate():
            content = form.content.data

            n = len(content)
            if n > HOME_SETTINGS['status_max_length']:
                response_data.update({
                    'error': (
                        '状态内容不能超过%s字' %
                        HOME_SETTINGS['status_max_length']
                    )
                })
            elif n <= 0 and not (
                    self.request.files and 'picture' in self.request.files):
                response_data.update({'error': '请输入文字内容或者照片'})
            else:
                picture = None
                if self.request.files and 'picture' in self.request.files:
                    picture = self.request.files['picture'][0]
                    image_types = [
                        'image/jpg', 'image/png', 'image/jpeg', 'image/gif'
                    ]
                    if picture['content_type'].lower() not in image_types:
                        response_data.update({
                            'error': '请上传jpg/png/gif格式的图片'
                        })

                if 'error' not in response_data:
                    now = datetime.now()

                    document = {
                        'author': DBRef(
                            UserDocument.meta['collection'],
                            self.current_user['_id']
                        ),
                        'publish_time': now,
                        'content': content
                    }
                    status_id = yield StatusDocument.insert(document)
                    friends = yield FriendDocument.get_reached_friends(
                        self.current_user['_id']
                    )

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

                    if message_list:
                        WriterManager.mpub(
                            MessageTopic.STATUS_NEW, message_list
                        )

                    if picture is not None:
                        try:
                            image = Image.open(StringIO(picture['body']))
                        except:
                            raise HTTPError(404)

                        try:
                            content_type = picture[
                                'content_type'
                            ].split('/')[-1].upper()
                        except:
                            content_type = 'JPEG'

                        document = {
                            'status': DBRef(
                                StatusDocument.meta['collection'],
                                ObjectId(status_id)
                            ),
                            'name': picture['filename'],
                            'content_type': content_type,
                            'upload_time': datetime.now()
                        }

                        width = 1024
                        if image.size[0] > width:
                            height = width * 1.0 * image.size[1] / image.size[0]
                            image = image.resize(
                                map(int, (width, height)), Image.ANTIALIAS
                            )

                        output = StringIO()
                        image.save(output, content_type, quality=100)
                        document.update({'body': Binary(output.getvalue())})
                        output.close()

                        thumbnail_width = 200
                        thumbnail_height = (
                            thumbnail_width * 1.0 * image.size[1] / image.size[0]
                        )

                        output = StringIO()
                        image = image.resize(
                            map(int, (thumbnail_width, thumbnail_height)),
                            Image.ANTIALIAS
                        )
                        image.save(output, content_type, quality=100)
                        document.update({
                            'thumbnail': Binary(output.getvalue())
                        })
                        output.close()

                        yield StatusPhotoDocument.insert(document)

                    status = yield StatusDocument.get_status(
                        status_id, self.current_user['_id']
                    )
                    html = self.render_string(
                        'home/template/status/status-list-item.html',
                        status=status
                    )
                    response_data.update({'html': html})
        else:
            for field in form.errors:
                response_data.update({'error': form.errors[field][0]})
                break

        self.finish(json.dumps(response_data))
Exemple #4
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)