class VideoListSerializer(ModelSerializer): video1 = VideoSerializer() video2 = VideoSerializer() video3 = VideoSerializer() video4 = VideoSerializer() video5 = VideoSerializer() class Meta: model = VideoList fields = ('list_id', 'list_name', 'video1', 'video2', 'video3', 'video4', 'video5')
def get(_, lang, video_id): if lang == 'ja': cached_video = Cache.get('api_video_' + str(video_id)) if cached_video is None: video = Video.get_published_by_id(video_id) if video is None: return JsonResponse({'message': 'Not Found'}, status=404) res = VideoSerializer(video).data Cache.set('api_video_' + str(video_id), res) else: res = cached_video elif lang == 'en': cached_video_en = Cache.get('api_video_en_' + str(video_id)) if cached_video_en is None: video = VideoEn.get_published_by_id(video_id) if video is None: return JsonResponse({'message': 'Not Found'}, status=404) res = VideoEnSerializer(video).data Cache.set('api_video_en_' + str(video_id), res) else: res = cached_video_en else: return JsonResponse({'message': 'Not Found'}, status=404) return JsonResponse(res, safe=False)
def upload(self, request, pk=None): instance = get_object_or_404(Video, pk=pk) upload_to_youtube(VideoSerializer(instance).data) return Response({'messagem': f'Video was successfully uploaded.'}, status=status.HTTP_200_OK)
def send_fcm_test(self): # fcm 푸시 메세지 요청 주소 url = 'https://fcm.googleapis.com/fcm/send' obj = get_object_or_404(UserInfo, name='기범') video_obj = get_object_or_404(Video, video_id=3) # 인증 정보(서버 키)를 헤더에 담아 전달 headers = { 'Authorization': 'key=' + getattr(settings, 'SERVER_KEY'), 'Content-Type': 'application/json; UTF-8', } content = { 'to': obj.push_id, 'notification': { 'title': 'deliciousbody test', 'body': 'deliciousbody test' }, 'data': { 'video': VideoSerializer(video_obj).data } } response = requests.post(url, headers=headers, data=json.dumps(content)) return HttpResponse(response)
def get(self, request, pk): cache_name_list = ['vl'] cache_name_list.append(str(pk)) cache_name = ''.join(cache_name_list) data = cache.get(cache_name) if data is None: vl = VideoList.objects.filter(list_id=pk).get() all_video = cache.get('all_video') if all_video is None: all_video = Video.objects.all() cache.set('all_video', all_video) qs = Video.objects.none() for i in range(1, vl.list_count + 1): if i == 1: qs = qs | all_video.filter(video_id=vl.video1.video_id) if i == 2: qs = qs | all_video.filter(video_id=vl.video2.video_id) if i == 3: qs = qs | all_video.filter(video_id=vl.video3.video_id) if i == 4: qs = qs | all_video.filter(video_id=vl.video4.video_id) if i == 5: qs = qs | all_video.filter(video_id=vl.video5.video_id) data = VideoSerializer(qs, many=True).data cache.set(cache_name, data) return Response(data, status=status.HTTP_200_OK)
def get(self, request, pk): if not request.user.is_anonymous: # ! 만약 유저가 로그인 되어 있는 상태라면 구독 및 좋아요 정보를 넘겨준다. video = Video.objects.get(pk=pk) is_subscribe = Feed.is_subscribe(video.uploader, request.user) is_video_like = VideoLike.is_video_like(video, request.user) is_video_dis_like = VideoDisLike.is_video_dis_like( video, request.user) user_dict = { "user_status": { "is_subscribe": is_subscribe, "is_video_like": is_video_like, "is_video_dis_like": is_video_dis_like } } else: user_dict = {} query_set = Video.objects.get(pk=pk) if query_set: serializer = VideoSerializer(query_set) user_dict.update(serializer.data) return Response(user_dict, status=status.HTTP_200_OK) else: return Response(None, status=status.HTTP_400_BAD_REQUEST)
def search(self, request,*args, **kwargs): # find all categories first # then, filter the categories itself. for item in kwargs.values(): name=item queryset = Video.objects.filter(Q(title__icontains=name) | Q(description__icontains=name)) paginator = Paginator(queryset, 20) serializer = VideoSerializer(paginator.get_page(1), many=True) return Response(serializer.data, status=status.HTTP_200_OK)
class ConceptSerializer(serializers.ModelSerializer): """ Serializer for Concept """ videos = VideoSerializer(many=True) quizzes = QuizSerializer(many=True) pages = DocumentSerializer(many=True) class Meta: """ Defining model """ model = models.Concept fields = ('id', 'title', 'description', 'image', 'playlist', 'is_published')
def VideoView(req): if req.method == 'GET': # video = get_object_or_404(Video) VIDEO_COUNT_PER_PAGE = 3 page = int(req.GET.get('page', 1)) video = Video.objects.all() start_page = page - 1 total_page = video.count() videos = video[start_page * VIDEO_COUNT_PER_PAGE : (start_page + 1) * VIDEO_COUNT_PER_PAGE] pager = {} pager['current'] = page pager['per_page'] = VIDEO_COUNT_PER_PAGE pager['total_page'] = total_page + VIDEO_COUNT_PER_PAGE serializer = VideoSerializer(videos, many=True) return render(req, 'admin_templates/video/list.html', {"videos" : serializer.data, 'page': page,'pager': pager})
def create_video(request): try: payload = json.loads(request.body) video = Video.objects.create(id=payload["id"], tag_id=payload["tag"]) serializer = VideoSerializer(video) return JsonResponse(serializer.data, safe=False, status=status.HTTP_201_CREATED) except ObjectDoesNotExist as e: return JsonResponse({'error': str(e)}, safe=False, status=status.HTTP_404_NOT_FOUND) except Exception as e: return JsonResponse({'error': str(e)}, safe=False, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def update_video(request, video_id): payload = json.loads(request.body) try: video_item = Video.objects.filter(id=video_id) video_item.update(**payload) video = Video.objects.get(id=video_id) serializer = VideoSerializer(video) return JsonResponse(serializer.data, safe=False, status=status.HTTP_200_OK) except ObjectDoesNotExist as e: return JsonResponse({'error': str(e)}, safe=False, status=status.HTTP_404_NOT_FOUND) except Exception: return JsonResponse({'error': 'Something terrible went wrong'}, safe=False, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def add_video(self, request, pk=None): """ Add video in the given concept """ concept = get_object_or_404(Concept, pk=pk) self.check_object_permissions(request, concept.group.course) serializer = AddVideoSerializer(data=request.DATA) if serializer.is_valid(): if 'other_file' in request.FILES: video = Video( title=serializer.data['title'], content=serializer.data['content'], video_file=request.FILES['video_file'], other_file=request.FILES['other_file'], #duration=duration ) else: video = Video( title=serializer.data['title'], content=serializer.data['content'], video_file=request.FILES['video_file'], #duration=duration ) video.save() duration = video.get_length() video.duration = duration video.save() try: if 'video_config_file' in request.FILES: import_quiz_camtasia8(request.FILES['video_config_file'], video) concept.playlist = typed_playlist.append( video.id, concept.playlist, 0) concept.videos.add(video) concept.save() return Response(VideoSerializer(video).data) except Exception, e: print "Camtasia 8 exception : " + str(e) video.delete() return Response({"error": "Cannot parse Config File"}, status.HTTP_400_BAD_REQUEST)
def get_video_list(self, obj): if not obj.videolist: return None list_id = obj.videolist.list_id vl = VideoList.objects.filter(list_id=list_id).get() all_video = Video.objects.all() qs = Video.objects.none() for i in range(1, vl.list_count + 1): if i == 1: qs = qs | all_video.filter(video_id=vl.video1.video_id) if i == 2: qs = qs | all_video.filter(video_id=vl.video2.video_id) if i == 3: qs = qs | all_video.filter(video_id=vl.video3.video_id) if i == 4: qs = qs | all_video.filter(video_id=vl.video4.video_id) if i == 5: qs = qs | all_video.filter(video_id=vl.video5.video_id) return VideoSerializer(qs, many=True).data
def send_fcm(push_id, video_obj): # fcm 푸시 메세지 요청 주소 url = 'https://fcm.googleapis.com/fcm/send' # 인증 정보(서버 키)를 헤더에 담아 전달 headers = { 'Authorization': 'key=' + getattr(settings, 'SERVER_KEY'), 'Content-Type': 'application/json; UTF-8', } content = { 'to': push_id, 'notification': { #'title' : 'push', 'body': '맛있는 운동이 도착했어요.' }, 'data': { 'video': VideoSerializer(video_obj).data } } response = requests.post(url, headers=headers, data=json.dumps(content)) print(response)
def test_create(): title = Title.create_title({'title': 'test_title'}) introduction = Introduction.create_introduction({ 'name': 'introduction_name', 'text': 'text', 'status': 1, 'thumbnail': 'thumbnail', 'published_at': '2018-09-04 14:57', }) Introduction.add_title(introduction.id, [title.id]) res1 = Video.create_video({ 'published_at': '2018-09-04 14:57', 'title': 'video_title1', 'text': 'video_body1', 'youtube_id': 'youtube_id', 'pickup': False, 'status': 1, }) res = Video.create_video({ 'published_at': '2018-09-04 14:57', 'title': 'video_title2', 'text': 'video_body2', 'youtube_id': 'youtube_id', 'pickup': False, 'status': 1, }) Video.add_video_from_video(res.id, [res1.id]) Video.add_introduction(res.id, [introduction.id]) video = Video.get_published_by_id(res.id) topic = Topic.create_topic({ 'title': 'topic_title', 'text': 'topic_body', 'status': 1, 'images': 'https://aaaa.com/aaa.jpg', 'url': 'https://yahoo.co.jp', 'button_label': 'ボタン', 'published_at': '2018-09-04 14:57' }) pprint( IntroductionSerializer(Introduction.get_by_id( introduction.id)).data) pprint(VideoSerializer(video).data) pprint(VideosSerializer(Video.get_all(), many=True).data) pprint(TopicSerializer(topic).data) pprint(TopicsSerializer(Topic.get_all(), many=True).data) Introduction.remove_title(introduction.id) Video.remove_video_from_introduction(introduction.id) Video.remove_video_self(video.id) pprint( IntroductionSerializer(Introduction.get_by_id( introduction.id)).data) pprint(VideoSerializer(Video.get_by_id(video.id)).data)
def GetVideosByCategory(request): pk = request.GET['category'] result = Video.objects.filter(category=pk, status="published") print(result) serializer = VideoSerializer(result, many=True) return Response(serializer.data)
def playlist_as_array(self, request, pk=None, with_history=False): """ Gets all the elements in the playlist """ concept = get_object_or_404(Concept, pk=pk) #videos_obj = concept.videos.all() videos_obj = [] for elem in json.loads(concept.playlist): if elem[2] == 0: videos_obj.append(Video.objects.get(pk=elem[0])) pages_obj = concept.pages.all() #pages_obj = [] #for elem in json.loads(concept.playlist): # if elem[2] == 2: # pages_obj.append(Document.objects.get(pk=elem[0])) quizzes_obj = concept.quizzes.all() videos = VideoSerializer(videos_obj, many=True) pages = [page.to_dict() for page in pages_obj] quizzes = QuizSerializer(quizzes_obj, many=True) _playlist = typed_playlist.to_array(concept.playlist) if with_history: videos_history = [] for video in videos_obj: videohistory = VideoHistory.objects.filter(video=video, user=request.user) if (len(videohistory) == 0): videohistory = VideoHistory(video=video, user=request.user) videohistory.save() else: videohistory = videohistory[0] videos_history.append( VideoHistorySerializer(videohistory).data) quizzes_history = [] for quiz in quizzes_obj: quizhistory = ConceptQuizHistory.objects.filter( quiz=quiz, user=request.user) if (len(quizhistory) == 0): quizhistory = ConceptQuizHistory(quiz=quiz, user=request.user) quizhistory.save() else: quizhistory = quizhistory[0] quizzes_history.append( ConceptQuizHistorySerializer(quizhistory).data) pages_history = [] for document in pages_obj: documenthistory = ConceptDocumentHistory.objects.filter( document=document, user=request.user) if (len(documenthistory) == 0): documenthistory = ConceptDocumentHistory(document=document, user=request.user) documenthistory.save() else: documenthistory = documenthistory[0] pages_history.append( ConceptDocumentHistorySerializer(documenthistory).data) ordered_data = [] for elem in _playlist: if elem[2] == 0: next_item = {'type': 'video', 'content': videos.data[elem[1]]} if with_history: next_item['history'] = videos_history[elem[1]] elif elem[2] == 1: next_item = {'type': 'quiz', 'content': quizzes.data[elem[1]]} if with_history: next_item['history'] = quizzes_history[elem[1]] elif elem[2] == 2: next_item = {'type': 'document', 'content': pages[elem[1]]} if with_history: next_item['history'] = pages_history[elem[1]] ordered_data.append(next_item) return ordered_data
def list_videos(request): videos = Video.objects.all() serializer = VideoSerializer(videos, many=True) return JsonResponse(serializer.data, safe=False, status=status.HTTP_200_OK)
def get_video(request, video_id): video = Video.objects.get(id=video_id) serializer = VideoSerializer(video, many=False) return JsonResponse(serializer.data, safe=False, status=status.HTTP_200_OK)