김재형

Fix conflict

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