def do_import_video_task(task): video_id = task.video_id file_path = task.file_path rating = task.rating file_name = os.path.basename(file_path)[:-4] tlog = get_logger(current_thread().name) videos = Video.objects.filter(path=file_path) if videos: tlog.info("Existing video: {0}".format(task.file_path)) return video = Video() video.video_id = video_id video.rating = rating thumb_path = get_thumb_path(video.video_id) cover_path = get_cover_path(video.video_id) if not gen_cover(task.file_path, cover_path): tlog.error("Failed to gen cover for {0}".format(file_path)) return success, duration = gen_thumb(file_path, thumb_path) if success: if not gen_flips(file_path, video.video_id, duration, FLIP_DIR, FLIP_NUM): tlog.error("Failed to gen flips for {0}".format(file_path)) else: tlog.error("Failed to gen thumb for {0}".format(file_path)) video.title = file_name video.path = file_path video.duration = duration video.save() tlog.info('#Video: {0} [{1}] {2}'.format(video.title, video.duration, video.path))
def insert_video(self,search ,page): goal_url = "https://www.pornhub.com/video/search?search={}&page={}".format(search ,page) for item in self.get_video_info(goal_url): v = Video(video_link=item['video_link'] ,video_url= item['video_url'] ,video_image=item['video_image'] ,video_length= item['video_length'] , video_title= item['video_title'] ,video_keyword =search ,video_quality=item['video_quality'] ,video_source=item['video_source']) print(v) v.save()
def video_info_process(self): video_fp = os.path.join(self.object.file.storage.base_location, self.object.file.name) command = [ 'ffprobe -v quiet -print_format json -show_format %s' % video_fp ] result = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out = result.stdout.read() json_info = json.loads(str(out.decode('utf-8'))) if 'format' in json_info and 'duration' in json_info['format']: duration_str = json_info['format']['duration'] duration = math.floor(float(duration_str)) else: duration = 0 if 'format' in json_info \ and 'tags' in json_info['format'] \ and 'creation_time' in json_info['format']['tags']: # 2018-06-28T07:43:21.000000Z take_time_str = str(json_info['format']['tags']['creation_time']) take_time = datetime.strptime(take_time_str, '%Y-%m-%dT%H:%M:%S.%fZ') else: take_time = datetime.now() video = Video() video.id = self.object.id video.file = self.object.file video.slug = self.object.slug video.dirname = self.object.dirname video.duration = duration video.take_time = take_time video.create_time = datetime.now() video.save(save_file=False)
def form_valid(self, form): # This method is called when valid form data has been POSTed. # It should return an HttpResponse. account_id = Account.objects.get( pk=self.request.session['active_user']) video = Video(account=account_id, title=form.cleaned_data['title'], created_date=timezone.now(), note=form.cleaned_data['note'], file=form.cleaned_data['file']) video.save() ### Get Video, compress It and make a thumbnail #vidfile = Video.objects.get(pk=video.id) #new_path = str(vidfile.file.path).replace(str(vidfile.file), str(self.request.session['active_user']) + "/" + str(vidfile.file)) #new_thumb = str(vidfile.file.path).replace(".","-") + ".jpg" #new_vid = str(vidfile.file.path).replace(str(vidfile.file), str(self.request.session['active_user']) + "/comp_" + str(vidfile.file)) #check_output(["ffmpeg", "-i", str(vidfile.file.path), "-y", "-acodec", "mp2", str(new_vid)]) #check_output(["ffmpeg", "-itsoffset", "-4", "-i", str(vidfile.file.path), "-vcodec", "mjpeg", "-vframes", "1", "-an", "-f", "rawvideo", "-s", "320x240", str(new_thumb)]) return super(AddVideoView, self).form_valid(form)
def test_youtube_video(self): """ Test that newly saved youtube videos are correctly capturing values from youtube. """ url = 'https://www.youtube.com/watch?v=c-wXZ5-Yxuc' test_video = Video(url=url) test_video.save() self.assertIsInstance(test_video, Video) self.assertEqual(test_video.source, 'youtube') video_dict = test_video.__dict__ self.assertIn('title', video_dict) self.assertIn('slug', video_dict) self.assertIn('summary', video_dict) self.assertIn('thumb_url', video_dict) response = self.client.get(reverse('video_detail', args=[test_video.slug, ])) self.assertEqual(response.status_code, 200) self.assertTemplateUsed('video_detail.html') self.assertIn('object', response.context) object = response.context['object'] self.assertIsInstance(object, Video) self.assertTrue(hasattr(object, 'title')) self.assertTrue(hasattr(object, 'summary')) self.assertTrue(hasattr(object, 'embed_src')) # test template Tag: out = Template( "{% load video_tags %}" "{% show_video object %}" ).render(Context({'object': object})) self.assertIn(object.title, out) self.assertIn(object.embed_src, out)
def test_vimeo_video(self): """ Test that newly saved vimeo videos are correctly capturing values from youtube. """ url = 'http://vimeo.com/67325705' test_video = Video(url=url) test_video.save() self.assertIsInstance(test_video, Video) self.assertEqual(test_video.source, 'vimeo') self.assertTrue('Tango' in test_video.title) video_dict = test_video.__dict__ self.assertIn('title', video_dict) self.assertIn('slug', video_dict) self.assertIn('summary', video_dict) self.assertIn('thumb_url', video_dict) response = self.client.get(reverse('video_detail', args=[test_video.slug, ])) self.assertEqual(response.status_code, 200) self.assertTemplateUsed('video_detail.html') self.assertIn('object', response.context) object = response.context['object'] self.assertIsInstance(object, Video)
def video_share(request, video_id): video_object = Video.objects.get(id=video_id) video = Video() video.owner = request.user video.title = video_object.title video.file = video_object.file video.description = video_object.description video.save() return HttpResponseRedirect('/videoplay/{}'.format(video_id))
def get_recent_item(): for i in range(1, recent_vender.get_all_page()): list = recent_vender.get_recent_list(i) try: for node in list: video = Video(**node) video.save() except Exception as e: traceback.print_exc()
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 post(request, lang): try: values = json.loads(request.body.decode("utf-8")) except: values = {} form = FavoriteForm(values) if form.errors: messages.add_message(request, messages.INFO, dict(form.errors.items())) return JsonResponse( { 'result': 'failure', 'error_messages': get_error_message(request), }, status=500) if form.is_valid(): try: if lang == 'ja': video_model = Video() else: video_model = VideoEn() video = video_model.get_by_id( video_id=form.cleaned_data.get('video_id')) if video is None: return JsonResponse( { 'result': 'failure', 'messages': 'Does Not Exist' }, status=404) Favorite.create_favorite({ 'uuid': form.cleaned_data.get('uuid'), 'video_id': form.cleaned_data.get('video_id'), 'lang': lang }) return JsonResponse({'result': 'success'}) except Exception as e: return JsonResponse({ 'result': 'failure', 'message': str(e) }, status=500)
def handle_label(self, label, **options): """Copy all glossvideos to taggedvideo instances""" self.stdout.write("handling " + label) if label == 'copy': self.stdout.write("Copying") for gv in GlossVideo.objects.all(): tv, created = TaggedVideo.objects.get_or_create( category='Gloss', tag=str(gv.gloss.pk)) vid = Video(tag=tv, videofile=gv.videofile, version=gv.version) vid.save() elif label == 'revert': done = TaggedVideo.objects.all().delete() self.stdout.write(str(done))
def add_bookmark(request): if request.method == "POST": video = Video( kind=request.POST['kind'], videoId=request.POST['videoId'], title=request.POST['title'], description=request.POST['description'], publishedAt=request.POST['publishedAt'], thumbnails=request.POST['thumbnails'], ) video.save() return redirect('video:search') else: pass
def fetch(): youtube_object = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey = DEVELOPER_KEY[0]) search_keyword = youtube_object.search().list(q = 'football',type='video', part = "id, snippet", maxResults = 5).execute() results = search_keyword.get("items", []) ids=[] for vid in Video.objects.all(): ids.append(vid.videoID) print(*results) for result in results: if result['id']['kind'] == 'youtube#video': if result["id"]["videoId"] in ids: continue video = Video(videoID=result["id"]["videoId"],title=result["snippet"]["title"],description=result['snippet']['description'],published=result['snippet']['publishedAt'],thumbUrls=result['snippet']['thumbnails']['default']['url']) video.save()
def upload(request): uploadFlag = True if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): video = Video() video.owner = request.user video.title = form.cleaned_data['title'] video.file = request.FILES['file'] video.description = form.cleaned_data["description"] video.save() return HttpResponseRedirect('success/') else: form = UploadFileForm() return render_to_response('upload.html', locals(), context_instance=RequestContext(request))
def setUp(self): path = os.path.dirname(os.path.abspath(__file__)) thumb_path = os.path.join(path, 'test.jpg') video_path = os.path.join(path, 'test.wmv') self.youtube = Youtube() video = Video() video.caption = 'Testing Video' video.description = 'Testing Video description' video.category = self.youtube.get_categories()[0][0] video.tags = 'vcelnice, vcelka, med' video.file = SimpleUploadedFile('test.wmv', bytes(video_path, 'utf-8'), content_type='video/x-ms-wmv') video.thumb = SimpleUploadedFile('test.jpg', open(thumb_path, 'rb').read(), content_type='image/jpeg') video.save()
def upload( request ): try: username = request.session['DukUser'] user = DukUser.objects.get(username = username) ui = user.usermovie_set.all()[0] except: user = None url = request.get_full_path() code = url.split('?')[1] m = Movie.objects.get(code = code) f = upload_receive(request) f.name = code+"_"+f.name v = Video(file_field = f) if user: v.uploader = user v.movie = m v.save() path, ext = os.path.splitext(v.file_field.name) path = "media/" + path #subprocess.call( ["ffmpeg", "-i" , path + ext, path + ".webm"]) basename = os.path.basename( v.file_field.file.name ) file_dict = { 'name' : basename, 'size' : v.file_field.file.size, # The assumption is that file_field is a FileField that saves to # the 'media' directory. 'url': settings.MEDIA_URL + basename, 'thumbnail_url': settings.MEDIA_URL + basename, 'delete_url': reverse('jfu_delete', kwargs = { 'pk': v.pk }), 'delete_type': 'POST', } return UploadResponse( request, file_dict )
def add_video(request: Request): access_token = request.headers.get('Access-Token') user_id = get_user_id_from_payload(access_token) audio_data = { 'name': request.data.get('audio_name'), 'author_name': request.data.get('author_name') } print(audio_data) audio = Audio(name=audio_data.get('name'), author_name=audio_data.get('author_name')) audio.save() video = request.data.get('video') path = os.path.join(settings.BASE_DIR) + '/static/video/{}/'.format(video) # if not os.path.isfile(path): default_storage.save( os.path.join(settings.BASE_DIR) + '/static/video/{}/'.format(video), ContentFile(video.read())) video_data = { 'url': '/static/video/{}/'.format(video), 'user_id': User.objects.get(id=user_id), 'description': request.data.get('video_description'), 'audio_id': audio, } video = Video(url=video_data.get('url'), uri=video_data.get('url'), user_id=video_data.get('user_id'), description=video_data.get('description'), audio_id=video_data.get('audio_id')) video.save() video = VideoStatistics.objects.get(id=video.video_id) hashtags_array = request.data.get('hashtags').split(' ') print(hashtags_array) for i in hashtags_array: hashtag = Hashtags(hashtag=i) hashtag.save() hashtags_on_video = HashtagsOnVideo(video_id=video, hashtag=hashtag) hashtags_on_video.save() print(video_data) return Response('LOL', status=status.HTTP_200_OK)
def get(request, lang, paged=1): try: value = request.GET.get('value') post_id = request.GET.get('post_id') if lang == 'ja': video_model = Video() else: video_model = VideoEn() if value != '': total = video_model.get_search_all(value, post_id).count() else: total = video_model.get_exclude_all(post_id).count() pagination = Pagination( page=paged, per_page=10, total=total, slug='') if value != '': videos = video_model.get_search_all(value, post_id)[ pagination.offset:pagination.offset + pagination.per_page] else: videos = video_model.get_exclude_all(post_id)[ pagination.offset:pagination.offset + pagination.per_page] if lang == 'ja': res = VideosSerializer(videos, many=True).data else: res = VideosEnSerializer(videos, many=True).data return JsonResponse({ 'total': pagination.pages, 'paged': paged, 'videos': res, }, safe=False) except Exception as e: return JsonResponse({ 'status': 500, 'message': 'Exception Error ' + str(e) }, status=500)
def get(request, lang): if lang == 'ja': introduction_model = Introduction() video_model = Video() topic_model = Topic() else: introduction_model = IntroductionEn() video_model = VideoEn() topic_model = TopicEn() introductions = introduction_model.get_all()[:3] videos = video_model.get_all()[:3] topics = topic_model.get_all()[:3] return TemplateResponse(request, 'top.html', { 'title': 'FEED App 管理', 'introductions': introductions, 'videos': videos, 'topics': topics, 'lang': lang, })
def post(_, lang, topic_id): sid = transaction.savepoint() if lang == 'ja': topic_model = Topic() video_model = Video() else: topic_model = TopicEn() video_model = VideoEn() try: video_model.remove_video_from_topic(topic_id) topic_model.delete_topic(topic_id) topic_model.remove_image(topic_id) transaction.savepoint_commit(sid) except: transaction.savepoint_rollback(sid) pass return HttpResponseRedirect('/{}/admin/topics'.format(lang))
def post(request, lang, video_id): if lang == 'ja': video_model = Video() else: video_model = VideoEn() video = video_model.get_by_id(video_id) if video is None: return JsonResponse({ 'status': 503, 'message': '投稿が存在しません' }, status=503) form = StatusForm(request.POST) if form.errors: messages.add_message(request, messages.INFO, dict(form.errors.items())) if form.is_valid(): try: video_model.status_change(form.cleaned_data.get('status'), video_id) except: return JsonResponse({ 'status': 500, 'message': 'Not Change' }, status=500) else: return JsonResponse( { 'status': 500, 'message': get_error_message(request) }, status=500) return JsonResponse({'status': 200, 'message': 'Changed'}, status=200)
def post(_, lang, video_id): sid = transaction.savepoint() if lang == 'ja': video_model = Video() else: video_model = VideoEn() try: video_model.remove_introduction(video_id) video_model.remove_topic(video_id) video_model.remove_video_self(video_id) video_model.remove_category(video_id) video_model.delete_video(video_id) transaction.savepoint_commit(sid) except: transaction.savepoint_rollback(sid) pass return HttpResponseRedirect('/{}/admin/videos'.format(lang))
def post(_, lang, introduction_id): sid = transaction.savepoint() if lang == 'ja': introduction_model = Introduction() video_model = Video() else: introduction_model = IntroductionEn() video_model = VideoEn() try: video_model.remove_video(introduction_id) introduction_model.remove_title(introduction_id) introduction_model.delete_introduction(introduction_id) transaction.savepoint_commit(sid) except: transaction.savepoint_rollback(sid) pass return HttpResponseRedirect('/{}/admin/introductions'.format(lang))
def get(request, lang, paged=1): search = request.GET.get('search', '') if lang == 'ja': video_model = Video() else: video_model = VideoEn() if search != '': total = video_model.get_search_all(search, None).count() else: total = video_model.get_all().count() pagination = Pagination(page=paged, per_page=10, total=total, query=search, slug='/{}/admin/videos/page/'.format(lang)) if search != '': videos = video_model.get_search_all( search, None)[pagination.offset:pagination.offset + pagination.per_page] else: videos = video_model.get_all( )[pagination.offset:pagination.offset + pagination.per_page] return TemplateResponse( request, 'videos.html', { 'title': '動画 | FEED App 管理', 'videos': videos, 'information': pagination.information(), 'pagination': pagination, 'lang': lang, 'search': search, })
def get(request, lang, video_id): if lang == 'ja': video_model = Video() else: video_model = VideoEn() video = video_model.get_by_id(video_id) if video is None: raise Http404 use_categories = video.category.all() groups = Group.get_all() if lang == 'ja': use_introductions = video.introduction.all().order_by( 'video_introduction.id') use_videos = video.video.all().order_by('video_video.id') else: use_introductions = video.introduction.all().order_by( 'video_en_introduction.id') use_videos = video.video.all().order_by('video_en_video.id') title = video.title return TemplateResponse( request, 'video.html', { 'title': title + ' | 動画 | FEED App 管理', 'video': video, 'use_videos': use_videos, 'use_introductions': use_introductions, 'use_categories': use_categories, 'groups': groups, 'form_data': {}, 'error_messages': {}, 'lang': lang, })
def post(request, lang): sid = transaction.savepoint() if lang == 'ja': form = TopicForm(request.POST) topic_model = Topic() video_model = Video() else: form = TopicEnForm(request.POST) topic_model = TopicEn() video_model = VideoEn() if form.errors: messages.add_message(request, messages.INFO, dict(form.errors.items())) if form.is_valid(): try: res_topic = topic_model.create_topic({ 'new': form.cleaned_data.get('new'), 'post_type': form.cleaned_data.get('post_type'), 'title': form.cleaned_data.get('title'), 'text': form.cleaned_data.get('text'), 'thumbnail': form.cleaned_data.get('thumbnail'), 'url': form.cleaned_data.get('url'), 'event_date': form.cleaned_data.get('event_date'), 'button_label': form.cleaned_data.get('button_label'), }) add_videos = form.cleaned_data.get('videos') if add_videos: video_model.add_video_from_topic(res_topic.id, add_videos) add_images = form.cleaned_data.get('images') if add_images: topic_model.add_image(res_topic.id, add_images) transaction.savepoint_commit(sid) return HttpResponseRedirect('/{}/admin/topics'.format(lang)) except: transaction.savepoint_rollback(sid) pass select_videos = [] if form.cleaned_data.get('videos'): video_ids = list(map(int, form.cleaned_data.get('videos'))) select_videos = video_model.get_by_ids(video_ids) select_images = [] if form.cleaned_data.get('images'): image_ids = list(map(int, form.cleaned_data.get('images'))) select_images = Image.get_by_ids(image_ids) return TemplateResponse( request, 'topic_create.html', { 'title': '新規投稿 | トピックス | FEED App 管理', 'select_videos': select_videos, 'select_images': select_images, 'form_data': form.cleaned_data, 'error_messages': get_error_message(request), 'lang': lang, 'post_types': [ {'name': 'トピック', 'val': 'topic'}, {'name': 'イベント', 'val': 'event'}, ] })
def setUp(self): self.video = Video()
def _saveVideo(self, videoFields): v = Video(**videoFields) v.save()
def _saveVideo(self, videoFields): video = Video(**videoFields) video.save() return video
def handle(self, *args, **options): task = Server_Task.objects.filter(task_wait=True, task_type="imgtovid") # There are no need to run outsorce if task.count() == 0: return # There are active tasks else: if DEBUG: print("start") print(datetime.now()) # Iterate tasks for t in task: if DEBUG: print(t) print(datetime.now()) # DO THE TASK try: os.system('cat ' + home_folder + t.task_input + '*.jpg | ffmpeg -f image2pipe -i - ' + task_folder + t.task_output + console_out) except: pass # TASK - OK if os.path.exists(task_folder + t.task_output): # If file already exists TASK try: obj = Video.objects.get(video_name=t.task_output) # UPDATE TASK ENTRY t.task_wait = False t.task_done = False t.save() # Create new Video object except: try: # GET KAMERA c = Camera.objects.get(cam_user=t.task_input.split("/") [0]) #t.task_object ) # SET DATE new_date = datetime(int(t.task_output[0:4]), int(t.task_output[4:6]), int(t.task_output[6:8])) # GET VIDEO FILE open_file = open(task_folder + t.task_output, 'rb') temp_file = File(open_file) new_video = Video(video_name=t.task_output, video_date=new_date, video_cam=c, video_file=temp_file) new_video.save() # CLEANUP RECIEVED FILE os.remove(task_folder + t.task_output) # UPDATE TASK ENTRY t.task_wait = False t.task_done = True t.task_done_time = timezone.now() t.save() except: try: # CLEANUP RECIEVED FILE os.remove(task_folder + t.task_output) except: pass if DEBUG: print( "!!!!! SOMETHING WENT WRONG CREATING VIDEO MODEL !!!!!" ) print(datetime.now()) # TASK FAILED - output file does not exist else: try: # CLEANUP RECIEVED FILE os.remove(task_folder + t.task_output) except: pass # UPDATE TASK ENTRY t.task_wait = False t.task_done = False t.save()