views.py 7 KB
from collections import OrderedDict
from django.shortcuts import render
from .models import File
# from django.views.generic import View
# from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
import boto3
import os
import xmltodict
import json
from django.http import JsonResponse
from rest_framework import viewsets, permissions, generics, status
from rest_framework.response import Response
from rest_framework.authtoken.models import Token
import json
from .serializers import (
    FileSerializer,
    FileViewSerializer,
)
from accounts.serializers import (
    UserSerializer
)
from rest_framework.parsers import MultiPartParser, FormParser

#from cloud.aws import aws_key
import configparser
from .s3_function import *
config = configparser.ConfigParser()
config.read('config.ini')


# 현재 폴더 로딩
class loadFolder(generics.GenericAPIView):
    serializer_class = FileViewSerializer

    def get(self, request, *args, **kwargs):
        folder = {}
        id = request.GET.get('id')
        owner = request.GET.get('owner')
        print("폴더로딩 유저: ", settings.AWS_STORAGE_BUCKET_NAME)
        query = File.objects.get(owner=owner, id=id)
        folder['id'] = query.id
        folder['name'] = query.name
        folder['isFolder'] = query.isFolder
        folder['path'] = query.path
        folder['modifiedDate'] = query.modifiedDate
        folder['share'] = query.share
        folder['cid'] = query.cid
        folder['filesize'] = query.filesize
        folder['owner'] = query.owner
        return Response({'folder': folder})


# 파일 로딩
class loadFiles(generics.GenericAPIView):
    serializer_class = FileSerializer

    def get(self, request, *args, **kwargs):
        files = []
        cid = request.GET.get('cid')
        #owner = request.GET.get('owner')
        queryset = File.objects.filter(cid=cid).filter(
            owner=settings.AWS_STORAGE_BUCKET_NAME)
        print("파일로딩 유저: ", settings.AWS_STORAGE_BUCKET_NAME)
        xmlList = []
        for query in queryset:
            file = {}
            xml = OrderedDict()
            file['id'] = query.id
            file['name'] = query.name
            file['isFolder'] = query.isFolder
            file['path'] = query.path
            file['modifiedDate'] = query.modifiedDate
            file['share'] = query.share
            file['cid'] = query.cid
            file['filesize'] = query.filesize
            file['owner'] = query.owner
            files.append(file)

            xml['id'] = query.id
            xml['version'] = query.version
            xml['name'] = query.name
            xml['thumbnail'] = query.thumbnail
            xml['zipurl'] = query.zipurl
            xmlList.append(xml)

        xmlFile = json.dumps({"catalog": {"book": xmlList}})
        xmlString = xmltodict.unparse(json.loads(xmlFile), pretty=True)
        print('\nXML output(json_to_xml.xml):')
        print(xmlString)
        with open('cdglist.xml', 'w') as f:
            f.write(xmlString)

        return Response({'files': files})


# 폴더 업로드
class uploadFolder(generics.GenericAPIView):
    serializer_class = FileSerializer

    def post(self, request, *args, **kwargs):
        print(request.data)
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        folder = serializer.save()
        return Response({
            'file': FileViewSerializer(folder).data
        })


# 다중 파일 업로드
class uploadFiles(generics.GenericAPIView):
    permissions_classes = [
        permissions.IsAuthenticated,
    ]
    serializer_class = FileSerializer

    def post(self, request, *args, **kwargs):
        files = []
        user = UserSerializer(self.request.user).data
        print("User: ", user)
        print("username: ", user['username'])
        print("username: ", settings.AWS_STORAGE_BUCKET_NAME)
        for key, file in enumerate(request.FILES.getlist('file')):
            uploadFile = {}
            #s3_upload_file(request.data.getlist('path')[key], request.FILES.getlist('file')[key])
            uploadFile['name'] = request.data.getlist('name')[key]
            uploadFile['isFolder'] = request.data.getlist('isFolder')[key]
            uploadFile['path'] = request.data.getlist('path')[key]
            uploadFile['owner'] = settings.AWS_STORAGE_BUCKET_NAME
            uploadFile['filesize'] = request.data.getlist('filesize')[key]
            uploadFile['share'] = request.data.getlist('share')[key]
            uploadFile['modifiedDate'] = request.data.getlist('modifiedDate')[
                key]
            uploadFile['cid'] = int(request.data.getlist('cid')[key])
            # xmlFile =
            serializer = self.get_serializer(data=uploadFile)
            serializer.is_valid(raise_exception=True)
            file = serializer.save()
            file = FileViewSerializer(file).data
            print(file)
            files.append(file)
        return Response({'files': files})



## 파일 삭제
class deleteTrash(generics.GenericAPIView):
    permissions_classes = [
            permissions.IsAuthenticated,
        ]
    def delete(self, request, id):
        print(id)
        queryset = File.objects.filter(id=id)
        print(queryset)
        file = FileSerializer(queryset, many=True).data
        location = file[0]['path']
        delete_file = s3_delete_file(location)
        print(delete_file)
        if queryset.delete():
            print("DATABASE DELETE!")
        else:
            print("DATABASE NOT DELETE!")
        return JsonResponse(delete_file)


# 휴지통에서 파일 복원
class restore(generics.GenericAPIView):
    def get(self, request, *args, **kwargs):
        id = request.data.get('id')
        File.objects.get_or_restore(id=id)
        return Response({'message': 'Success to restore!'})


# 파일 다운로드
class downloadFile(generics.GenericAPIView):
    def get(self, request, id):
        print(id)
        queryset = File.objects.filter(id=id)
        print(queryset.values())
        file_name = FileSerializer(queryset, many=True).data
        file_name = file_name[0]['path']
        print(file_name)
        download_file = s3_download_file(file_name)
        return Response({'file_url': download_file})


# 파일 이름 변경
class renameFile(generics.GenericAPIView):
    def post(self, request, id):
        queryset = File.objects.filter(id=id)
        owner = queryset.values('owner')[0]['owner']
        path = queryset.values('path')[0]['path']
        oldname = queryset.values('name')[0]['name']
        newname = request.data.get('newname')

        response = s3_rename_file(newname, owner, path)
        queryset.update(name=newname, path=path[:path.index(oldname)]+newname)


class viewXml(generics.GenericAPIView):
    def get(self, request, *args, **kwargs):
        f = open('cdglist.xml', 'r')
        while True:
            line = f.readline()
            if not line:
                break
            print(line)
        f.close
        return HttpResponse(open('cdglist.xml').read(), content_type='text/xml')