Showing
1 changed file
with
246 additions
and
59 deletions
1 | import mimetypes | 1 | import mimetypes |
2 | import json | 2 | import json |
3 | import os | 3 | import os |
4 | -from datetime import datetime | 4 | +from datetime import datetime, timedelta |
5 | 5 | ||
6 | import boto3 | 6 | import boto3 |
7 | from botocore.client import Config | 7 | from botocore.client import Config |
8 | 8 | ||
9 | -from django.contrib.auth.models import User | ||
10 | from django.core import serializers | 9 | from django.core import serializers |
11 | from django.views.decorators.csrf import csrf_exempt | 10 | from django.views.decorators.csrf import csrf_exempt |
12 | from rest_framework import viewsets | 11 | from rest_framework import viewsets |
... | @@ -15,11 +14,16 @@ from rest_framework.response import Response | ... | @@ -15,11 +14,16 @@ from rest_framework.response import Response |
15 | from rest_framework.decorators import action | 14 | from rest_framework.decorators import action |
16 | from rest_framework.permissions import IsAuthenticated, AllowAny | 15 | from rest_framework.permissions import IsAuthenticated, AllowAny |
17 | 16 | ||
18 | -from api.models import Item, SharedItem | 17 | +from .models import Item, SharedItem, User |
19 | -from api.serializers import UserSerializer,GroupSerializer,ItemSerializer | 18 | +from .serializers import UserSerializer, GroupSerializer, ItemSerializer |
20 | from rest_framework import status | 19 | from rest_framework import status |
21 | from annoying.functions import get_object_or_None | 20 | from annoying.functions import get_object_or_None |
22 | -from khudrive.settings import AWS_SESSION_TOKEN, AWS_SECRET_ACCESS_KEY, AWS_ACCESS_KEY_ID, AWS_REGION, AWS_STORAGE_BUCKET_NAME | 21 | +from django.conf import settings |
22 | +import jwt | ||
23 | +from django.http import HttpResponse, JsonResponse | ||
24 | +from khudrive.settings import AWS_SESSION_TOKEN, AWS_SECRET_ACCESS_KEY, AWS_ACCESS_KEY_ID, AWS_REGION, \ | ||
25 | + AWS_STORAGE_BUCKET_NAME, AWS_ENDPOINT_URL | ||
26 | + | ||
23 | 27 | ||
24 | class UserViewSet(viewsets.ModelViewSet): | 28 | class UserViewSet(viewsets.ModelViewSet): |
25 | """ | 29 | """ |
... | @@ -27,15 +31,113 @@ class UserViewSet(viewsets.ModelViewSet): | ... | @@ -27,15 +31,113 @@ class UserViewSet(viewsets.ModelViewSet): |
27 | """ | 31 | """ |
28 | queryset = User.objects.all().order_by('-date_joined') | 32 | queryset = User.objects.all().order_by('-date_joined') |
29 | serializer_class = UserSerializer | 33 | serializer_class = UserSerializer |
30 | - permission_classes = [permissions.IsAuthenticated] | 34 | + permission_classes = [permissions.IsAuthenticatedOrReadOnly, permissions.AllowAny, |
35 | + # IsOwnerOrReadOnly | ||
36 | + ] | ||
37 | + permission_classes_by_action = {'get': [permissions.AllowAny], | ||
38 | + 'destroy': [permissions.AllowAny]} | ||
31 | 39 | ||
40 | + @csrf_exempt | ||
41 | + @action(detail=False, methods=['POST'], permission_classes=[permissions.AllowAny], url_path='signup', | ||
42 | + url_name='singup') | ||
43 | + def signup(self, request): | ||
44 | + user_id = request.POST.get('user_id', '') | ||
45 | + name = request.POST.get('name', '') | ||
46 | + password = request.POST.get('password', '') | ||
47 | + user = get_object_or_None(User, user_id=user_id) | ||
48 | + if user == None: | ||
49 | + user = User(user_id=user_id, name=name, password=password, total_size=100000, current_size=0) | ||
50 | + user.save() | ||
51 | + root = Item(is_folder=True, name="root", file_type="folder", path="", user_id=user.int_id, size=0, | ||
52 | + status=True) | ||
53 | + root.save() | ||
54 | + user.root_folder = root.item_id | ||
55 | + user.save() | ||
56 | + return Response({ | ||
57 | + 'message': 'user created', | ||
58 | + 'int_id': user.int_id, | ||
59 | + 'user_id': user.user_id, | ||
60 | + 'name': user.name, | ||
61 | + 'root_folder': root.item_id, | ||
62 | + 'total_size': user.total_size, | ||
63 | + 'current_size': user.current_size, | ||
64 | + 'created_time': user.created_time | ||
65 | + }, | ||
66 | + status=status.HTTP_200_OK, | ||
67 | + ) | ||
68 | + else: | ||
69 | + return Response({'message': 'user is already exist.'}, status=status.HTTP_204_NO_CONTENT) | ||
70 | + | ||
71 | + @csrf_exempt | ||
72 | + @action(methods=['post'], detail=False, permission_classes=[permissions.AllowAny], | ||
73 | + url_path='login', url_name='login') | ||
74 | + def login(self, request): | ||
75 | + if not request.data: | ||
76 | + return Response({'Error': "Please provide user_id/password"}, status=status.HTTP_400_BAD_REQUEST) | ||
77 | + user_id = request.POST['user_id'] | ||
78 | + password = request.POST['password'] | ||
79 | + try: | ||
80 | + user = User.objects.get(user_id=user_id, password=password) | ||
81 | + except User.DoesNotExist: | ||
82 | + return Response({'Error': "Invalid user_id/password"}, status=status.HTTP_400_BAD_REQUEST) | ||
83 | + if user: | ||
84 | + payload1 = { | ||
85 | + 'int_id': user.int_id, | ||
86 | + 'user_id': user.user_id, | ||
87 | + 'exp': datetime.utcnow() + timedelta(seconds=300) | ||
88 | + } | ||
89 | + payload2 = { | ||
90 | + 'int_id': user.int_id, | ||
91 | + 'user_id': user.user_id, | ||
92 | + 'exp': datetime.utcnow() + timedelta(days=5) | ||
93 | + } | ||
94 | + access = jwt.encode(payload1, settings.SECRET_KEY, algorithm='HS256').decode('utf-8') | ||
95 | + refresh = jwt.encode(payload2, settings.SECRET_KEY, algorithm='HS256').decode('utf-8') | ||
96 | + exp = jwt.decode(access, settings.SECRET_KEY, algorithm='HS256')['exp'] | ||
97 | + token = {'access': access, | ||
98 | + 'refresh': refresh, | ||
99 | + 'exp': exp, | ||
100 | + 'user': { | ||
101 | + 'int_id': user.int_id, | ||
102 | + 'user_id': user.user_id, | ||
103 | + 'name': user.name, | ||
104 | + 'total_size': user.total_size, | ||
105 | + 'current_size': user.current_size, | ||
106 | + 'root_folder': user.root_folder | ||
107 | + }} | ||
108 | + return JsonResponse( | ||
109 | + token, | ||
110 | + status=status.HTTP_200_OK, | ||
111 | + ) | ||
112 | + else: | ||
113 | + return JsonResponse( | ||
114 | + {'Error': "Invalid credentials"}, | ||
115 | + status=status.HTTP_400_BAD_REQUEST, | ||
116 | + ) | ||
117 | + return JsonResponse(status=status.HTTP_405_METHOD_NOT_ALLOWED) | ||
118 | + | ||
119 | + def get(self, request, pk): | ||
120 | + user = User.objects.filter(int_id=pk) | ||
121 | + data = serializers.serialize("json", user) | ||
122 | + json_data = json.loads(data) | ||
123 | + res = json_data[0]['fields'] | ||
124 | + res['id'] = json_data[0]['pk'] | ||
125 | + return Response({'data': res}, status=status.HTTP_200_OK) | ||
126 | + | ||
127 | + def get_permissions(self): | ||
128 | + try: | ||
129 | + # return permission_classes depending on `action` | ||
130 | + return [permission() for permission in self.permission_classes_by_action[self.action]] | ||
131 | + except KeyError: | ||
132 | + # action is not set return default permission_classes | ||
133 | + return [permission() for permission in self.permission_classes] | ||
32 | 134 | ||
33 | -class ItemViewSet(viewsets.ViewSet): | ||
34 | 135 | ||
136 | +class ItemViewSet(viewsets.ViewSet): | ||
35 | queryset = Item.objects.all() | 137 | queryset = Item.objects.all() |
36 | serializer_class = ItemSerializer | 138 | serializer_class = ItemSerializer |
37 | permission_classes = [permissions.IsAuthenticatedOrReadOnly, permissions.AllowAny, | 139 | permission_classes = [permissions.IsAuthenticatedOrReadOnly, permissions.AllowAny, |
38 | - #IsOwnerOrReadOnly | 140 | + # IsOwnerOrReadOnly |
39 | ] | 141 | ] |
40 | permission_classes_by_action = {'get': [permissions.AllowAny], | 142 | permission_classes_by_action = {'get': [permissions.AllowAny], |
41 | 'destroy': [permissions.AllowAny]} | 143 | 'destroy': [permissions.AllowAny]} |
... | @@ -45,7 +147,8 @@ class ItemViewSet(viewsets.ViewSet): | ... | @@ -45,7 +147,8 @@ class ItemViewSet(viewsets.ViewSet): |
45 | def search(self, request): | 147 | def search(self, request): |
46 | if request.method == 'GET': | 148 | if request.method == 'GET': |
47 | keyword = request.GET.get('keyword', '') | 149 | keyword = request.GET.get('keyword', '') |
48 | - item_list = Item.objects.filter(name__icontains = keyword) | 150 | + # user_id = request.GET.get('user_id', '') |
151 | + item_list = Item.objects.filter(name__icontains=keyword) | ||
49 | 152 | ||
50 | data = serializers.serialize("json", item_list) | 153 | data = serializers.serialize("json", item_list) |
51 | json_data = json.loads(data) | 154 | json_data = json.loads(data) |
... | @@ -54,7 +157,8 @@ class ItemViewSet(viewsets.ViewSet): | ... | @@ -54,7 +157,8 @@ class ItemViewSet(viewsets.ViewSet): |
54 | t = i['fields'] | 157 | t = i['fields'] |
55 | t['id'] = i['pk'] | 158 | t['id'] = i['pk'] |
56 | res.append(t) | 159 | res.append(t) |
57 | - return Response({'data': {'list' : res}}, status=status.HTTP_200_OK) | 160 | + return Response({'data': {'list': res}}, status=status.HTTP_200_OK) |
161 | + | ||
58 | """ | 162 | """ |
59 | # url: items/11/ | 163 | # url: items/11/ |
60 | # 마지막 slash도 써주어야함 | 164 | # 마지막 slash도 써주어야함 |
... | @@ -75,38 +179,42 @@ class ItemViewSet(viewsets.ViewSet): | ... | @@ -75,38 +179,42 @@ class ItemViewSet(viewsets.ViewSet): |
75 | 179 | ||
76 | return Response({'message': presigned_url}, status=status.HTTP_200_OK) | 180 | return Response({'message': presigned_url}, status=status.HTTP_200_OK) |
77 | """ | 181 | """ |
182 | + | ||
78 | # url: items/11/ | 183 | # url: items/11/ |
79 | # 마지막 slash도 써주어야함 | 184 | # 마지막 slash도 써주어야함 |
80 | def get(self, request, pk): | 185 | def get(self, request, pk): |
81 | - s3 = boto3.client('s3', | 186 | + s3 = boto3.client( |
187 | + 's3', | ||
188 | + region_name=AWS_REGION, | ||
82 | aws_access_key_id=AWS_ACCESS_KEY_ID, | 189 | aws_access_key_id=AWS_ACCESS_KEY_ID, |
83 | aws_secret_access_key=AWS_SECRET_ACCESS_KEY, | 190 | aws_secret_access_key=AWS_SECRET_ACCESS_KEY, |
84 | aws_session_token=AWS_SESSION_TOKEN, | 191 | aws_session_token=AWS_SESSION_TOKEN, |
85 | - config=Config(signature_version='s3v4')) | 192 | + endpoint_url=AWS_ENDPOINT_URL or None, |
193 | + config=Config(s3={'addressing_style': 'path'}) | ||
194 | + ) | ||
86 | s3_bucket = AWS_STORAGE_BUCKET_NAME | 195 | s3_bucket = AWS_STORAGE_BUCKET_NAME |
87 | 196 | ||
88 | item = Item.objects.filter(item_id=pk) | 197 | item = Item.objects.filter(item_id=pk) |
89 | - object_name = item.get().name | 198 | + object_id = item.get().item_id |
90 | data = serializers.serialize("json", item) | 199 | data = serializers.serialize("json", item) |
91 | json_data = json.loads(data) | 200 | json_data = json.loads(data) |
92 | 201 | ||
93 | presigned_url = s3.generate_presigned_url( | 202 | presigned_url = s3.generate_presigned_url( |
94 | 'get_object', | 203 | 'get_object', |
95 | Params={'Bucket': s3_bucket, | 204 | Params={'Bucket': s3_bucket, |
96 | - 'Key': object_name}, | 205 | + 'Key': object_id}, |
97 | - ExpiresIn = 3600 | 206 | + ExpiresIn=3600 |
98 | ) | 207 | ) |
99 | 208 | ||
100 | res = json_data[0]['fields'] | 209 | res = json_data[0]['fields'] |
101 | - res['id']=json_data[0]['pk'] | 210 | + res['id'] = json_data[0]['pk'] |
102 | - res['signed_url']=presigned_url | 211 | + res['signed_url'] = presigned_url |
103 | return Response({'data': res}, status=status.HTTP_200_OK) | 212 | return Response({'data': res}, status=status.HTTP_200_OK) |
104 | 213 | ||
105 | # url: items/11/ | 214 | # url: items/11/ |
106 | # 마지막 slash도 써주어야함 | 215 | # 마지막 slash도 써주어야함 |
107 | def destroy(self, request, pk): | 216 | def destroy(self, request, pk): |
108 | if request.method == 'DELETE': | 217 | if request.method == 'DELETE': |
109 | - print(pk) | ||
110 | item = get_object_or_None(Item, item_id=pk) | 218 | item = get_object_or_None(Item, item_id=pk) |
111 | if item != None: | 219 | if item != None: |
112 | if item.is_folder == True: # 폴더는 삭제 안되도록 처리 | 220 | if item.is_folder == True: # 폴더는 삭제 안되도록 처리 |
... | @@ -114,9 +222,31 @@ class ItemViewSet(viewsets.ViewSet): | ... | @@ -114,9 +222,31 @@ class ItemViewSet(viewsets.ViewSet): |
114 | item.is_deleted = True | 222 | item.is_deleted = True |
115 | item.save() | 223 | item.save() |
116 | # item.delete() 이거 하면 완전 삭제되어버림 is deleted True 면 휴지통에서 리스트 조회할 수 있도록! | 224 | # item.delete() 이거 하면 완전 삭제되어버림 is deleted True 면 휴지통에서 리스트 조회할 수 있도록! |
117 | - return Response({'message': 'delete complete'},status=status.HTTP_200_OK) | 225 | + return Response({'message': 'destroy complete'}, status=status.HTTP_200_OK) |
226 | + return Response({'message': 'item is not existed.'}, status=status.HTTP_204_NO_CONTENT) | ||
227 | + | ||
228 | + @action(methods=['POST'], detail=True, permission_classes=[AllowAny], url_path='restore', url_name='restore') | ||
229 | + def restore(self, request, pk): | ||
230 | + if request.method == 'POST': | ||
231 | + item = get_object_or_None(Item, item_id=pk) | ||
232 | + if item != None: | ||
233 | + item.is_deleted = False | ||
234 | + item.save() | ||
235 | + return Response({'message': 'restore complete'}, status=status.HTTP_200_OK) | ||
236 | + return Response({'message': 'item is not existed.'}, status=status.HTTP_204_NO_CONTENT) | ||
237 | + | ||
238 | + @action(methods=['DELETE'], detail=True, permission_classes=[AllowAny], url_path='delete', url_name='delete') | ||
239 | + def delete(self, request, pk): | ||
240 | + if request.method == 'DELETE': | ||
241 | + item = get_object_or_None(Item, item_id=pk) | ||
242 | + if item != None: | ||
243 | + if item.is_folder == True: # 폴더는 삭제 안되도록 처리 | ||
244 | + return Response({'message': 'This item is folder.'}, status=status.HTTP_200_OK) | ||
245 | + item.delete() | ||
246 | + return Response({'message': 'delete permanently complete'}, status=status.HTTP_200_OK) | ||
118 | return Response({'message': 'item is not existed.'}, status=status.HTTP_204_NO_CONTENT) | 247 | return Response({'message': 'item is not existed.'}, status=status.HTTP_204_NO_CONTENT) |
119 | 248 | ||
249 | + | ||
120 | # url: items/11/move | 250 | # url: items/11/move |
121 | # 마지막 slash도 써주어야함 | 251 | # 마지막 slash도 써주어야함 |
122 | @action(methods=['POST'], detail=True, permission_classes=[AllowAny], url_path='move', url_name='move') | 252 | @action(methods=['POST'], detail=True, permission_classes=[AllowAny], url_path='move', url_name='move') |
... | @@ -124,12 +254,27 @@ class ItemViewSet(viewsets.ViewSet): | ... | @@ -124,12 +254,27 @@ class ItemViewSet(viewsets.ViewSet): |
124 | if request.method == 'POST': | 254 | if request.method == 'POST': |
125 | parent_id = request.POST.get('parent', '') | 255 | parent_id = request.POST.get('parent', '') |
126 | name = request.POST.get('name','') | 256 | name = request.POST.get('name','') |
127 | - parent = get_object_or_None(Item, item_id=parent_id) | ||
128 | - if parent != None and parent.is_folder == True: | ||
129 | child = get_object_or_None(Item, item_id=pk) | 257 | child = get_object_or_None(Item, item_id=pk) |
258 | + | ||
130 | if child == None: | 259 | if child == None: |
131 | return Response({'message': 'item is not existed.'}, status=status.HTTP_204_NO_CONTENT) | 260 | return Response({'message': 'item is not existed.'}, status=status.HTTP_204_NO_CONTENT) |
261 | + | ||
262 | + if parent_id != '': | ||
263 | + parent = get_object_or_None(Item, item_id=parent_id) | ||
264 | + | ||
265 | + if parent == None: | ||
266 | + return Response({'message': 'parent is not existed.'}, status=status.HTTP_200_OK) | ||
267 | + if parent.is_folder == False: | ||
268 | + return Response({'message': 'parent is not folder.'}, status=status.HTTP_200_OK) | ||
269 | + | ||
270 | + if parent != None and parent.is_folder == True: | ||
132 | child.parent = parent_id | 271 | child.parent = parent_id |
272 | + else: | ||
273 | + parent_id = child.parent | ||
274 | + | ||
275 | + if name != '': | ||
276 | + child.name = name; | ||
277 | + | ||
133 | child.save() | 278 | child.save() |
134 | child = Item.objects.filter(item_id = pk) | 279 | child = Item.objects.filter(item_id = pk) |
135 | child_data = serializers.serialize("json", child) | 280 | child_data = serializers.serialize("json", child) |
... | @@ -140,12 +285,8 @@ class ItemViewSet(viewsets.ViewSet): | ... | @@ -140,12 +285,8 @@ class ItemViewSet(viewsets.ViewSet): |
140 | parent_data = serializers.serialize("json", parent) | 285 | parent_data = serializers.serialize("json", parent) |
141 | json_parent = json.loads(parent_data)[0]['fields'] | 286 | json_parent = json.loads(parent_data)[0]['fields'] |
142 | res['parentInfo'] = json_parent | 287 | res['parentInfo'] = json_parent |
288 | + | ||
143 | return Response({'data': res}, status=status.HTTP_200_OK) | 289 | return Response({'data': res}, status=status.HTTP_200_OK) |
144 | - if parent == None: | ||
145 | - return Response({'message': 'parent is not existed.'}, status=status.HTTP_200_OK) | ||
146 | - if parent.is_folder == False: | ||
147 | - return Response({'message': 'parent is not folder.'}, status=status.HTTP_200_OK) | ||
148 | - return Response({'message': 'item is not existed.'}, status=status.HTTP_204_NO_CONTENT) | ||
149 | 290 | ||
150 | @action(methods=['POST'], detail=True, permission_classes=[AllowAny], url_path='copy', url_name='copy') | 291 | @action(methods=['POST'], detail=True, permission_classes=[AllowAny], url_path='copy', url_name='copy') |
151 | def copy(self, request, pk): | 292 | def copy(self, request, pk): |
... | @@ -159,15 +300,16 @@ class ItemViewSet(viewsets.ViewSet): | ... | @@ -159,15 +300,16 @@ class ItemViewSet(viewsets.ViewSet): |
159 | if child.is_folder == True: | 300 | if child.is_folder == True: |
160 | return Response({'message': 'item is folder'}, status=status.HTTP_204_NO_CONTENT) | 301 | return Response({'message': 'item is folder'}, status=status.HTTP_204_NO_CONTENT) |
161 | copiedName = child.name + "_복사본_" + str(datetime.now().strftime('%Y-%m-%d %H:%M')) | 302 | copiedName = child.name + "_복사본_" + str(datetime.now().strftime('%Y-%m-%d %H:%M')) |
162 | - copiedItem = Item(is_folder = False, name = copiedName, path =child.path, parent = parent_id, user_id= child.user_id, size=child.size, status=child.status) | 303 | + copiedItem = Item(is_folder=False, name=copiedName, path=child.path, parent=parent_id, |
304 | + user_id=child.user_id, size=child.size, status=child.status) | ||
163 | copiedItem.save() | 305 | copiedItem.save() |
164 | 306 | ||
165 | - copiedItem = Item.objects.filter(name = copiedName) | 307 | + copiedItem = Item.objects.filter(name=copiedName) |
166 | copied_data = serializers.serialize("json", copiedItem) | 308 | copied_data = serializers.serialize("json", copiedItem) |
167 | json_data = json.loads(copied_data) | 309 | json_data = json.loads(copied_data) |
168 | res = json_data[0]['fields'] | 310 | res = json_data[0]['fields'] |
169 | res['id'] = json_data[0]['pk'] | 311 | res['id'] = json_data[0]['pk'] |
170 | - parent = Item.objects.filter(item_id = parent_id) | 312 | + parent = Item.objects.filter(item_id=parent_id) |
171 | parent_data = serializers.serialize("json", parent) | 313 | parent_data = serializers.serialize("json", parent) |
172 | json_parent = json.loads(parent_data)[0]['fields'] | 314 | json_parent = json.loads(parent_data)[0]['fields'] |
173 | res['parentInfo'] = json_parent | 315 | res['parentInfo'] = json_parent |
... | @@ -186,36 +328,74 @@ class ItemViewSet(viewsets.ViewSet): | ... | @@ -186,36 +328,74 @@ class ItemViewSet(viewsets.ViewSet): |
186 | # action is not set return default permission_classes | 328 | # action is not set return default permission_classes |
187 | return [permission() for permission in self.permission_classes] | 329 | return [permission() for permission in self.permission_classes] |
188 | 330 | ||
189 | - #url: items/{key}/children/ | 331 | + # url: items/{key}/children/ |
190 | @action(methods=['GET', 'POST'], detail=True, permission_classes=[AllowAny], | 332 | @action(methods=['GET', 'POST'], detail=True, permission_classes=[AllowAny], |
191 | url_path='children', url_name='children') | 333 | url_path='children', url_name='children') |
192 | - def children(self, request, pk, *args, **kwargs): | 334 | + def children(self, request, pk): |
193 | if request.method == 'GET': | 335 | if request.method == 'GET': |
194 | - parent_item = Item.objects.get(item_id = pk) | 336 | + children = Item.objects.filter(parent=pk, is_deleted=False, status=True) |
195 | - try: | 337 | + children_data = serializers.serialize("json", children) |
196 | - parent_item = get_object_or_404(Item, pk = pk) | 338 | + json_children = json.loads(children_data) |
197 | - except parent_item.DoesNotExist: | 339 | + parent = Item.objects.filter(item_id=pk) # item |
198 | - return Response({'Error': 'Folder does not exist.'}) | 340 | + parent_data = serializers.serialize("json", parent) |
199 | - items = Item.objects.get(parent = parent_item.pk) | 341 | + json_parent = json.loads(parent_data)[0]['fields'] |
200 | - return Response(items, status=status.HTTP_200_OK) | 342 | + res = json_parent |
201 | - | 343 | + res['id'] = pk |
344 | + children_list = [] | ||
345 | + for i in json_children: | ||
346 | + t = i['fields'] | ||
347 | + t['id'] = i['pk'] | ||
348 | + children_list.append(t) | ||
349 | + res['list'] = children_list | ||
350 | + return Response({'data': res}, status=status.HTTP_200_OK) | ||
202 | if request.method == 'POST': | 351 | if request.method == 'POST': |
203 | - data = JSONParser().parse(request) | 352 | + name = request.POST.get('name', '') |
204 | - serializer = ItemSerializer(data=data) | 353 | + user_id = request.GET.get('user_id', '') |
205 | - if serializer.is_valid(): | 354 | + item = Item(is_folder=True, name=name, file_type="folder", path="", parent=pk, user_id=user_id, size=0, |
206 | - serializer.save() | 355 | + status=True) |
207 | - return Response(serializer.data, status=status.HTTP_200_OK) | 356 | + item.save() |
208 | - return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) | 357 | + item = Item.objects.filter(item_id=item.item_id) |
358 | + item_data = serializers.serialize("json", item) | ||
359 | + json_item = json.loads(item_data) | ||
360 | + res = json_item[0]['fields'] | ||
361 | + res['id'] = json_item[0]['pk'] | ||
362 | + res['inside_folder_list'] = [] | ||
363 | + res['inside_file_list'] = [] | ||
364 | + return Response({'data': res}, status=status.HTTP_200_OK) | ||
365 | + | ||
366 | + @action(methods=['GET'], detail=False, permission_classes=[AllowAny], | ||
367 | + url_path='trash', url_name='trash') | ||
368 | + def trash(self, request): | ||
369 | + if request.method == 'GET': | ||
370 | + children = Item.objects.filter(is_deleted = True) | ||
371 | + children_data = serializers.serialize("json", children) | ||
372 | + json_children = json.loads(children_data) | ||
373 | + res = {} | ||
374 | + children_list = [] | ||
375 | + for i in json_children: | ||
376 | + t = i['fields'] | ||
377 | + t['id'] = i['pk'] | ||
378 | + children_list.append(t) | ||
379 | + res['list'] = children_list | ||
380 | + return Response({'data': res}, status=status.HTTP_200_OK) | ||
209 | 381 | ||
210 | # url: /upload/ | 382 | # url: /upload/ |
211 | @action(methods=['POST'], detail=True, permission_classes=[AllowAny], | 383 | @action(methods=['POST'], detail=True, permission_classes=[AllowAny], |
212 | url_path='upload', url_name='upload') | 384 | url_path='upload', url_name='upload') |
213 | def upload(self, request, pk): | 385 | def upload(self, request, pk): |
214 | if request.method == 'POST': | 386 | if request.method == 'POST': |
215 | - s3 = boto3.client('s3') | 387 | + s3 = boto3.client( |
388 | + 's3', | ||
389 | + region_name=AWS_REGION, | ||
390 | + aws_access_key_id=AWS_ACCESS_KEY_ID, | ||
391 | + aws_secret_access_key=AWS_SECRET_ACCESS_KEY, | ||
392 | + aws_session_token=AWS_SESSION_TOKEN, | ||
393 | + endpoint_url=AWS_ENDPOINT_URL or None, | ||
394 | + config=Config(s3={'addressing_style': 'path'}) | ||
395 | + ) | ||
216 | s3_bucket = AWS_STORAGE_BUCKET_NAME | 396 | s3_bucket = AWS_STORAGE_BUCKET_NAME |
217 | 397 | ||
218 | - #파일 객체 생성 | 398 | + # 파일 객체 생성 |
219 | file_name = request.POST.get('name', '') | 399 | file_name = request.POST.get('name', '') |
220 | file_size = request.POST.get('size', '') | 400 | file_size = request.POST.get('size', '') |
221 | file_parent = pk | 401 | file_parent = pk |
... | @@ -227,10 +407,11 @@ class ItemViewSet(viewsets.ViewSet): | ... | @@ -227,10 +407,11 @@ class ItemViewSet(viewsets.ViewSet): |
227 | 407 | ||
228 | presigned_post = s3.generate_presigned_post( | 408 | presigned_post = s3.generate_presigned_post( |
229 | s3_bucket, | 409 | s3_bucket, |
230 | - file_name, | 410 | + file_id, |
231 | { | 411 | { |
232 | "acl": "private", | 412 | "acl": "private", |
233 | "Content-Type": file_type, | 413 | "Content-Type": file_type, |
414 | + "Content-Disposition": "attachment", | ||
234 | 'region': AWS_REGION, | 415 | 'region': AWS_REGION, |
235 | 'x-amz-algorithm': 'AWS4-HMAC-SHA256', | 416 | 'x-amz-algorithm': 'AWS4-HMAC-SHA256', |
236 | 'x-amz-date': date_long | 417 | 'x-amz-date': date_long |
... | @@ -238,18 +419,26 @@ class ItemViewSet(viewsets.ViewSet): | ... | @@ -238,18 +419,26 @@ class ItemViewSet(viewsets.ViewSet): |
238 | [ | 419 | [ |
239 | {"acl": "private"}, | 420 | {"acl": "private"}, |
240 | {"Content-Type": file_type}, | 421 | {"Content-Type": file_type}, |
422 | + {"Content-Disposition": "attachment"}, | ||
241 | {'x-amz-algorithm': 'AWS4-HMAC-SHA256'}, | 423 | {'x-amz-algorithm': 'AWS4-HMAC-SHA256'}, |
242 | {'x-amz-date': date_long} | 424 | {'x-amz-date': date_long} |
243 | ], | 425 | ], |
244 | 3600 | 426 | 3600 |
245 | ) | 427 | ) |
246 | 428 | ||
429 | + item = Item.objects.filter(item_id=upload_item.item_id) | ||
430 | + item_data = serializers.serialize("json", item) | ||
431 | + json_item = json.loads(item_data) | ||
432 | + res = json_item[0]['fields'] | ||
433 | + res['id'] = json_item[0]['pk'] | ||
434 | + | ||
247 | data = { | 435 | data = { |
248 | "signed_url": presigned_post, | 436 | "signed_url": presigned_post, |
249 | - 'url': 'https://%s.s3.amazonaws.com/%s' % (s3_bucket, file_name) | 437 | + 'url': '%s/%s' % (presigned_post["url"], file_id), |
438 | + 'item': res | ||
250 | } | 439 | } |
251 | 440 | ||
252 | - return Response({'presigned_post':presigned_post, 'proc_data':data}, status=status.HTTP_200_OK) | 441 | + return Response(data, status=status.HTTP_200_OK) |
253 | 442 | ||
254 | # url: /status/ | 443 | # url: /status/ |
255 | @action(methods=['POST'], detail=True, permission_classes=[AllowAny], | 444 | @action(methods=['POST'], detail=True, permission_classes=[AllowAny], |
... | @@ -257,7 +446,7 @@ class ItemViewSet(viewsets.ViewSet): | ... | @@ -257,7 +446,7 @@ class ItemViewSet(viewsets.ViewSet): |
257 | def status(self, request, *args, **kwargs): | 446 | def status(self, request, *args, **kwargs): |
258 | if request.method == 'POST': | 447 | if request.method == 'POST': |
259 | pk = request.POST.get('item_id', '') | 448 | pk = request.POST.get('item_id', '') |
260 | - queryset = Item.objects.filter(item_id = pk) | 449 | + queryset = Item.objects.filter(item_id=pk) |
261 | for cand in queryset: | 450 | for cand in queryset: |
262 | cand.status = True | 451 | cand.status = True |
263 | cand.save() | 452 | cand.save() |
... | @@ -265,16 +454,13 @@ class ItemViewSet(viewsets.ViewSet): | ... | @@ -265,16 +454,13 @@ class ItemViewSet(viewsets.ViewSet): |
265 | return Response({'Error': 'No such item found in queryset'}, status=status.HTTP_400_BAD_REQUEST) | 454 | return Response({'Error': 'No such item found in queryset'}, status=status.HTTP_400_BAD_REQUEST) |
266 | 455 | ||
267 | 456 | ||
268 | - | ||
269 | - | ||
270 | - | ||
271 | class SharedItemViewSet(viewsets.ModelViewSet): | 457 | class SharedItemViewSet(viewsets.ModelViewSet): |
272 | - | ||
273 | queryset = SharedItem.objects.all() | 458 | queryset = SharedItem.objects.all() |
274 | # serializer_class = SharedItemSerializer | 459 | # serializer_class = SharedItemSerializer |
275 | permission_classes = [permissions.IsAuthenticatedOrReadOnly, permissions.AllowAny, | 460 | permission_classes = [permissions.IsAuthenticatedOrReadOnly, permissions.AllowAny, |
276 | # IsOwnerOrReadOnly | 461 | # IsOwnerOrReadOnly |
277 | ] | 462 | ] |
463 | + | ||
278 | # url: http://localhost:8000/items/1/share/ | 464 | # url: http://localhost:8000/items/1/share/ |
279 | # 마지막 slash도 써주어야함 | 465 | # 마지막 slash도 써주어야함 |
280 | @csrf_exempt | 466 | @csrf_exempt |
... | @@ -288,19 +474,20 @@ class SharedItemViewSet(viewsets.ModelViewSet): | ... | @@ -288,19 +474,20 @@ class SharedItemViewSet(viewsets.ModelViewSet): |
288 | if sharedfile != None: | 474 | if sharedfile != None: |
289 | # 서버는 정상이나 이미 공유객체로 등록된 파일임 | 475 | # 서버는 정상이나 이미 공유객체로 등록된 파일임 |
290 | return Response({'message': 'This file is already shared'}, status=status.HTTP_200_OK) | 476 | return Response({'message': 'This file is already shared'}, status=status.HTTP_200_OK) |
291 | - sharedfile = SharedItem(item_id =pk, password=password, expires = expires) | 477 | + sharedfile = SharedItem(item_id=pk, password=password, expires=expires) |
292 | sharedfile.save() | 478 | sharedfile.save() |
293 | - sharedfile = SharedItem.objects.get(item_id = pk) | 479 | + sharedfile = SharedItem.objects.get(item_id=pk) |
294 | 480 | ||
295 | # sf = serializers.serialize("json", sharedfile) | 481 | # sf = serializers.serialize("json", sharedfile) |
296 | - item = Item.objects.filter(item_id = pk) | 482 | + item = Item.objects.filter(item_id=pk) |
297 | item_json = serializers.serialize("json", item) | 483 | item_json = serializers.serialize("json", item) |
298 | 484 | ||
299 | json_data = json.loads(item_json) | 485 | json_data = json.loads(item_json) |
300 | print(json_data) | 486 | print(json_data) |
301 | res = json_data[0]['fields'] | 487 | res = json_data[0]['fields'] |
302 | res['id'] = json_data[0]['pk'] | 488 | res['id'] = json_data[0]['pk'] |
303 | - return Response({"shared": sharedfile.created_time , 'data': res}, status=status.HTTP_200_OK) | 489 | + return Response({"shared": sharedfile.created_time, 'data': res}, status=status.HTTP_200_OK) |
490 | + | ||
304 | 491 | ||
305 | item = ItemViewSet.as_view({ | 492 | item = ItemViewSet.as_view({ |
306 | 'delete': 'destroy', | 493 | 'delete': 'destroy', | ... | ... |
-
Please register or login to post a comment