netdisc_manager.py 5.23 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
#!/usr/bin/env python
# -*- coding: utf_8 -*-

import os
import copy
import time
import types
import json
import logging
import traceback
from datetime import datetime
from pony.orm import *
from flask import request
from model import fullStackDB
from model.netdisc import Netdisc
from model.user import User
from app.setting import config

logger = logging.getLogger("NetDiscManager")

class NetDiscManager(object):
    def __init__(self):
        super(NetDiscManager, self).__init__()

    def add(self, data):
        editor = User.get(id=request.current_user.get("id"))
        if not editor:
            return False, "current user is not exists"

        data.update({
            'create_by': editor,
            'create_at': datetime.now(),
            'update_by': editor,
            'update_at': datetime.now(),
        })

        result = fullStackDB.add(Netdisc, **data)
        return result, "add netdisc {}.".format("success" if result else "fail")

    def delete(self, data):
        # 通过uuid查询出所有的文件列表,然后全部删除
        editor = User.get(id=request.current_user.get("id"))
        if not editor:
            return False, "current user is not exists"

        count = 0
        result = []
        with db_session:
            for uuid in data.get("uuids"):
                nd = Netdisc.get(uuid=uuid)
                if nd:
                    # nd.is_delete = True
                    # nd.delete_at = datetime.now()
                    # nd.delete_by = editor
                    nd.set(is_delete = True, delete_at = datetime.now(), delete_by = editor)
                    count = count + 1
                    result.append([nd.is_dir, nd.real_path])
                    commit()

        return result, "delete {} netdisc {}.".format(count, "success" if result else "fail")

    def get(self, data):
        result = Netdisc.get(**data)
        if result:
            result = result.to_dict(only=["uuid", "name", "real_path"])
        return result, "get netdisc {}.".format("success" if result else "no data")

    def getList(self, data):
        data.update({ "is_delete": False })

        count = 0
        result = []
        with db_session:
            editor = User.get(id=request.current_user.get("id"))
            if not editor:
                return False, "current user is not exists"

            if editor.role.name != "超级管理员":
                data.update({ "create_by": editor })

            result = Netdisc.select().where(**data).order_by(Netdisc.name)
            count = len(result)

            files = []
            folders = []
            for item in result:
                t = item.to_dict(with_collections=True, related_objects=True, only=["uuid", "name", "size", "is_dir", "parent_dir", "file_type", "create_at", "update_at"])
                if item.is_dir:
                    t.update({
                        "is_dir": 1 if item.is_dir else 0,
                        "real_path": os.path.relpath(item.real_path, config.get("UPLOAD_PATH")).replace('\\', '/'),
                        "create_by": item.create_by.to_dict(only=["uuid", "username"]),
                        "update_by": item.update_by.to_dict(only=["uuid", "username"]),
                        "create_at": item.create_at.strftime("%Y-%m-%d %H:%M:%S"),
                        "update_at": item.update_at.strftime("%Y-%m-%d %H:%M:%S")
                    })
                    folders.append(t)
                else:
                    t.update({
                        "is_dir": 1 if item.is_dir else 0,
                        "real_path": os.path.relpath(item.real_path, config.get("UPLOAD_PATH")).replace('\\', '/'),
                        "create_by": item.create_by.to_dict(only=["uuid", "username"]),
                        "update_by": item.update_by.to_dict(only=["uuid", "username"]),
                        "create_at": item.create_at.strftime("%Y-%m-%d %H:%M:%S"),
                        "update_at": item.update_at.strftime("%Y-%m-%d %H:%M:%S")
                    })
                    files.append(t)

            result = folders + files

        return result, count, "get netdisc {}.".format("success" if result else "no data")

    def update(self, uuid, data):
        # 当参数为空时,直接返回错误
        if len(data) <= 0 or (len(data.keys()) == 1 and "id" in data):
            return False, "parameters can not be null."

        result = None
        with db_session:
            # 查询请求者是否存在
            editor = User.get(id=request.current_user.get("id"))
            if not editor:
                return False, "current user is not exists"

            result = Netdisc.get(uuid=uuid)
            if result:
                _real = result.real_path
                result.set(update_at=datetime.now(), update_by=editor, **data)
                commit()

                _ext = os.path.splitext(result.real_path)[-1]
                _dir = os.path.dirname(result.real_path)

                filename = data.get("name") + _ext
                data.update({ "real_path": os.path.normpath(os.sep.join([_dir, filename])) })
                result = { "src": _real, "dst": data.get("real_path") }

        return result, "update netdisc {}.".format("success" if result else "fail")

netDiscManager = NetDiscManager()