netdisc.py 6.25 KB
Newer Older
wanli's avatar
wanli committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
#!/usr/bin/env python
# -*- coding: utf_8 -*-
import os
import json
import datetime
import logging
import traceback
from flask import Blueprint, request
from app import config, signalManager
from fullstack.login import Auth
from fullstack.validation import validate_schema
from fullstack.response import ResponseCode, response_result
from schema.netdisc import AddSchema, DeleteSchema, QuerySchema, UpdateSchema
from app.setting import config
from utils import random_string

logger = logging.getLogger("netdiscApi")

netdisc_api = Blueprint("netdisc_api", __name__, url_prefix="/api/v1/%s/netdisc" % config['NAME'])

FileStoragePath = os.path.normpath(os.path.join(config.get("UPLOAD_PATH"), config.get("NETDISC")))

if not os.path.exists(FileStoragePath):
    os.mkdir(FileStoragePath)

@netdisc_api.route("/add", methods=['POST'])
@validate_schema(AddSchema)
@Auth.auth_required
def add():
    try:
        binfile = request.files.get("binfile")

        information = {
            "name": "",
            "size": 0,
            "is_dir": False,
            "file_type": request.schema_data.get("file_type"),
            "parent_dir": request.schema_data.get("parent_dir"),
            "real_path": "",
        }

        if not binfile and not request.schema_data.get("file_type") and not request.schema_data.get("parent_dir") and not request.schema_data.get("name"):
            return response_result(ResponseCode.NO_DATA, msg="file can not be null")
        
        if os.path.normpath(information['parent_dir']).replace('\\', '/') == "/":
            result = { "real_path": FileStoragePath }
        else:
            t = os.path.normpath(information['parent_dir']).replace('\\', '/')
            b = os.path.basename(t)
            d = os.path.dirname(t)
            result, message = signalManager.actionGetNetDisc.emit({ "name": b, "parent_dir": d })
            if not result:
                return response_result(ResponseCode.NO_DATA_FOUND, msg="parent directory does not exists.")

        if not binfile:
            information['is_dir'] = True
            information['file_type'] = 'dir'
            information['name'] = request.schema_data.get("name")
            information['real_path'] = os.path.normpath(os.sep.join([result.get("real_path"), information['name']]))
            information['parent_dir'] = os.path.normpath(information['parent_dir']).replace('\\', '/')
            # os.path.relpath() 

            if os.path.exists(information['real_path']):
                return response_result(ResponseCode.EXISTS_ERROR, msg="File [%s] is existed! Please remove firstly" % information['real_path'])

            print(result.get("real_path"), information['name'])

            os.chdir(result.get("real_path")) # 切换目录
            os.mkdir(information['name']) # 创建目录
        else:
            information['name'] = binfile.filename
            saveFile = os.path.normpath(os.sep.join([result.get("real_path"), information['name']]))

            if os.path.exists(saveFile):
                return response_result(ResponseCode.EXISTS_ERROR, msg="File [%s] is existed! Please remove firstly" % saveFile)

            with open(saveFile, 'wb') as f:
                f.write(binfile.stream.read())

            information['size'] = os.path.getsize(saveFile)
            if not information['file_type']:
                information['file_type'] = os.path.splitext(information['name'])[-1]
            information['real_path'] = saveFile
            information['parent_dir'] = os.path.normpath(information['parent_dir']).replace('\\', '/')

        isSuccess, message = signalManager.actionAddNetDisc.emit(information)
        if isSuccess:
            return response_result(ResponseCode.OK, msg=message)
        else:
            return response_result(ResponseCode.REQUEST_ERROR, msg=message)
    except Exception as e:
        traceback.print_exc()
        logger.error(str(e))
        return response_result(ResponseCode.SERVER_ERROR, msg=str(e))


@netdisc_api.route("/delete", methods=['POST'])
@validate_schema(DeleteSchema)
@Auth.auth_required
def delete():
    try:
        result, message = signalManager.actionDeleteNetDisc.emit(request.schema_data)
        if result:
            for f in result:
                if f[0]: os.rmdir(f[1])
                else: os.remove(f[1])
            return response_result(ResponseCode.OK, msg=message)
        else:
            return response_result(ResponseCode.REQUEST_ERROR, msg=message)
    except Exception as e:
        traceback.print_exc()
        logger.error(str(e))
        return response_result(ResponseCode.SERVER_ERROR)


@netdisc_api.route("/get", methods=["POST"])
@validate_schema(QuerySchema)
@Auth.auth_required
def get():
    try:
        result, message = signalManager.actionGetNetDisc.emit(request.schema_data)
        if result:
            return response_result(ResponseCode.OK, data=result, msg=message)
        else:
            return response_result(ResponseCode.REQUEST_ERROR, msg=message)
    except Exception as e:
        traceback.print_exc()
        logger.error(str(e))
        return response_result(ResponseCode.SERVER_ERROR, msg=str(e))


@netdisc_api.route("/list", methods=['POST'])
@validate_schema(QuerySchema)
@Auth.auth_required
def get_list():
    try:
        result, count, message = signalManager.actionGetNetDiscList.emit(request.schema_data)
        if result:
            return response_result(ResponseCode.OK, data=result, msg=message, count=count, url=config.get("UPLOAD_SERVER"))
        else:
            return response_result(ResponseCode.REQUEST_ERROR, msg=message)
    except Exception as e:
        traceback.print_exc()
        logger.error(str(e))
        return response_result(ResponseCode.SERVER_ERROR)


@netdisc_api.route("/update/<uuid:id>", methods=['POST'])
@validate_schema(UpdateSchema)
@Auth.auth_required
def update(id):
    try:
        result, message = signalManager.actionUpdateNetDisc.emit(id, request.schema_data)
        if result:
            print(result)
            os.rename(result.get("src"), result.get("dst"))
            return response_result(ResponseCode.OK, msg=message)
        else:
            return response_result(ResponseCode.REQUEST_ERROR, msg=message)
    except Exception as e:
        traceback.print_exc()
        logger.error(str(e))
        return response_result(ResponseCode.SERVER_ERROR)