views.py
8.63 KB
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
import boto3
import botocore
import threading
from django.http import HttpResponse
from django.core import serializers
from django.core.exceptions import FieldDoesNotExist, ObjectDoesNotExist
from django.shortcuts import render
from django.contrib.auth.models import User
from api.videorecord import record
from api.models import Video, Device, RemoteHistory, Lock, Record, Door
from api.serializers import VideoSerializer, DeviceSerializer, RemoteHistorySerializer, RecordSerializer
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.authtoken.models import Token
"""
from boto3.session import Session
from src.settings import AWS_REGION
from src.settings import S3_ACCESS_URL
from src.settings import S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY, S3_STORAGE_BUCKET_NAME
"""
import time
from datetime import datetime, timedelta
import json
import uuid
# Create your views here.
#로그인 및 토큰 반환
class Login(APIView) :
def get(self, request, format = None) : # request query에 door_id 포함되어있음 : api/auth?door_id=12345
try :
request_id = request.GET.get('door_id', None)
if request_id == None :
raise FieldDoesNotExist
queryset = Door.objects.filter(door_id = request_id) # door_id 유효성 검색
if queryset.exists() :# 유효할 때
userid = uuid.uuid4()
pw = uuid.uuid4()
user = User.objects.create_user(username=str(userid), password=str(pw))
token = Token.objects.create(user=user)
res = {
'is_available' : True,
'access_token' : token.key
}
else :
res = {
'is_available' : False
}
return Response(res, status = status.HTTP_200_OK)
except FieldDoesNotExist as error :
return Response({
'error' : "FieldDoesNotExist ",
'date' : datetime.now()
}, status = status.HTTP_400_BAD_REQUEST)
'''
def post(self, request, format = None) :
queryset = Door.objects.create(door_id = 12345)
return Response({
'msg' : 'doorid값 삽입 완료',
})
'''
#기기 관련 api
class Devices(APIView) :
# 기기 목록 조회
def get(self, request, format = None) :
queryset = Device.objects.all()
serializer = DeviceSerializer(queryset, many = True)
res = {
'deviceList': serializer.data
}
return Response(res, status = status.HTTP_200_OK)
# 기기 추가
def post(self, request, format = None) : # request body에 rfid_id 포함되어있음
try :
print('냐냐냐냐냐냐')
print(request.body)
data = json.loads(request.body)
request_id = data.get('rfid_id', None)
if request_id == None :
raise FieldDoesNotExist
queryset = Device.objects.create(rfid_id = request_id)
return Response({
'msg' : 'success device add'
})
except FieldDoesNotExist as error :
return Response({
'error' : "FieldDoesNotExist ",
'date' : datetime.now()
}, status = status.HTTP_400_BAD_REQUEST)
# 기기 삭제
def delete(self, request, device_id, format = None): # request URI에 device_id(자동생성되는 기기 고유 번호 != rfid_id) 포함
try :
request_id = device_id
if request_id == None:
raise FieldDoesNotExist
queryset = Device.objects.get(device_id=request_id)
queryset.delete()
return Response({
'msg' : 'success delete device'
})
except FieldDoesNotExist as error :
return Response({
'error' : "FieldDoesNotExist ",
'date' : datetime.now()
}, status = status.HTTP_400_BAD_REQUEST)
# 원격 잠금 해제
class Remote(APIView):
# 원격 잠금 해제 기록 조회
def get(self, request, format = None) :
#models.py의 class History 사용.
queryset = RemoteHistory.objects.all()
serializer = RemoteHistorySerializer(queryset, many = True)
res = {
"remoteHistoryList": serializer.data
}
return Response(res, status = status.HTTP_200_OK)
# 비디오 목록 조회
class VideoList(APIView) :
def get(self, request, format = None) :
queryset = Video.objects.all()
serializer = VideoSerializer(queryset, many = True)
res = {
'videoList': serializer.data
} # 응답코드에 포함될 데이터
return Response(res, status = status.HTTP_200_OK)
# 비디오 수동 삭제
def delete(self, request, vid_name, format = None) : # request URI에 vid_name가 포함되어있음 : api/video/{vid_name}
try :
request_id = vid_name
if request_id == 'None' :
raise FieldDoesNotExist
session = boto3.session.Session(aws_access_key_id = S3_ACCESS_KEY_ID, aws_secret_access_key = S3_SECRET_ACCESS_KEY, region_name = AWS_REGION)
s3 = session.client('s3')
target = Video.objects.get(vid_name = request_id)
s3.delete_object(Bucket = S3_STORAGE_BUCKET_NAME, Key = str(target.vid_name))
target.delete()
return Response(status = status.HTTP_200_OK)
except FieldDoesNotExist as error :
return Response({
'error' : "FieldDoesNotExist ",
'date' : datetime.now()
}, status = status.HTTP_400_BAD_REQUEST)
# 비디오 확인(다운로드)
class VideoDownload(APIView) :
def get(self, request, vid_name, format = None) : # 요청한 URI에 vid_name가 포함되어있음
try :
request_id = vid_name
if request_id == 'None' :
raise FieldDoesNotExist
download_url = S3_ACCESS_URL + str(request_id) # S3 다운로드 링크 변환
if not download_url :
raise ObjectDoesNotExist
res = {
's3_link' : download_url
} # 응답 코드에 보낼 데이터
return Response(res, status = status.HTTP_200_OK)
except FieldDoesNotExist as error :
return Response({
'error' : "FieldDoesNotExist ",
'date' : datetime.now()
}, status = status.HTTP_400_BAD_REQUEST)
except ObjectDoesNotExist as error :
return Response({
'error' : "ObjectDoesNotExist",
'date' : datetime.now()
}, status = status.HTTP_404_NOT_FOUND)
# 비디오 자동 삭제
class CheckDate(APIView) :
def delete(self, request, format = None) :
checkdate = datetime.now() + timedelta(days = -7)
quaryset = Video.objects.filter(created__lt = checkdate)
session = boto3.session.Session(aws_access_key_id = S3_ACCESS_KEY_ID, aws_secret_access_key = S3_SECRET_ACCESS_KEY, region_name = AWS_REGION)
s3 = session.client('s3')
for delvid in quaryset :
s3.delete_object(Bucket = S3_STORAGE_BUCKET_NAME, Key = str(delvid.vid_name))
quaryset.delete()
return Response(status = status.HTTP_200_OK)
# 비디오 녹화 설정 조회/변경
class Recording(APIView) :
def get(self, request, format = None) :
try :
target = Record.objects.get(id = 1)
serializer = RecordSerializer(target, many = False)
res = {
'recording' : serializer.data['recording']
}
return Response(res, status = status.HTTP_200_OK)
except FieldDoesNotExist as error :
return Response({
'error' : "FieldDoesNotExist ",
'date' : datetime.now()
}, status = status.HTTP_400_BAD_REQUEST)
def put(self, request, format = None) :
try :
target = Record.objects.filter(id = 1)
target.update(recording = request.data['recording'])
if request.data['recording'] :
threading.Thread(target=record).start()
return Response(status = status.HTTP_200_OK)
except FieldDoesNotExist as error :
return Response({
'error' : "FieldDoesNotExist ",
'date' : datetime.now()
}, status = status.HTTP_400_BAD_REQUEST)