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_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 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_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 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 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 test_same_vimeo_with_different_urls(self): """ Tries to create a model object to the same youtube clip starting with slightly different urls. It should not work """ v1 = Video(url="http://vimeo.com/57370112") v1.save() v2 = Video(url="http://vimeo.com/57370112#") self.assertRaises(IntegrityError, v2.save)
def test_same_youtube_with_different_urls(self): """ Tries to create a model object to the same youtube clip starting with slightly different urls. It should not work """ v1 = Video(url="http://www.youtube.com/watch?v=iYHjpZe5NDY") v1.save() v2 = Video(url="http://youtu.be/iYHjpZe5NDY?t=2s") self.assertRaises(IntegrityError, v2.save)
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 test_used_in_the_future(self): """ No quotes may be used in the future... Save a quote used in the future (1 day) and check if it is in the future """ q = Video(url="http://www.youtube.com/watch?v=iYHjpZe5neh", used=timezone.now() + timedelta(days=1)) q.save() # If used is in the future this will be negative dt = (timezone.now() - q.used).total_seconds() self.assertGreaterEqual(dt, 0, msg="The video is %F sec in the future" % (dt * -1))
def test_video_save(self): vid = Video(embed_url="http://player.vimeo.com/video/41088675", artist="Mirel Wagner", url="http://pitchfork.com/tv/musicvideos/1983-joe/", image="http://cdn3.pitchfork.com/video-archive/1983/medium.bb8aa5ef.jpg", title="Joe") vid.save() saved = Video.query.get(vid.mongo_id) self.assertIsNotNone(saved, "Video not saved") self.assertIsNotNone(saved.source, "No video source set on save") self.assertIsNotNone(saved.image_gridfs, "No video gridfs image_gridfs")
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 import_video(request): if request.method == 'POST': form = VideoImportForm(request.POST) if form.is_valid(): rules = list(ProviderRule.objects.all()) patterns = [re.compile(r.regex) for r in rules] for i, part in re_parts(patterns, form.cleaned_data['url']): rule = rules[i] FORMAT = getattr(settings, "OEMBED_FORMAT", "json") url = u"%s?url=%s&maxwidth=%s&maxheight=%s&format=%s" % ( rule.endpoint, part, 600, 400, FORMAT ) resp = simplejson.loads(fetch(url)) replacement = render_to_string('oembed/%s.html' % resp['type'], {'response': resp}) # TODO: this should be in oembed, bit dont want to modify it now if(resp): if(resp.has_key('thumbnail_url')): thumbnail_url = resp['thumbnail_url'] else: p = re.compile('v=([^&]+)') m = p.search(form.cleaned_data['url']) id = m.group() id = id.replace("v=","") thumbnail_url = "http://img.youtube.com/vi/"+id+"/1.jpg" #import pdb; pdb.set_trace() video = Video(creator= request.user, import_url=form.cleaned_data['url'], was_uploaded=False, thumbnail_url=thumbnail_url, title=form.cleaned_data['title'], ) video.save() request.user.message_set.create(message=_("Video '%s' was \ successfully imported!") % video.title) return HttpResponseRedirect(reverse('show_video', args=(video.id,))) else: return render_to_response('video/unsuccessful_import.html', { 'url': form.cleaned_data['url'] }, context_instance=RequestContext(request)); else: form = VideoImportForm(request.POST) return render_to_response("", {'form': form}, context_instance=RequestContext(request))
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 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 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 save(self, *args, **kwargs): resource = super(FormResource, self).save(*args, **kwargs) UploadedFile.bind_files( self.cleaned_data.get('files', '').split('|'), resource) videos = json.loads(self.cleaned_data.get('videos', '')) Video.save_videos(videos, resource) # Add to project if a project id was given. project_id = self.cleaned_data.get('project_id', None) if project_id: project = get_object_or_None(Project, pk=int(project_id)) if project: project.save_related_object(resource, self.user) return resource
def save(self, *args, **kwargs): need = super(NeedForm, self).save(*args, **kwargs) UploadedFile.bind_files( self.cleaned_data.get('files', '').split('|'), need) videos = json.loads(self.cleaned_data.get('videos', '')) Video.save_videos(videos, need) # Add to project if a project id was given. project_id = self.cleaned_data.get('project_id', None) if project_id: project = get_object_or_None(Project, pk=int(project_id)) if project: project.save_related_object(need, self.user) return need
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()
class VideoForm(forms.Form): title = forms.CharField(required=True, error_messages=ERROR_MESSAGES) text = forms.CharField(required=True, error_messages=ERROR_MESSAGES) youtube_id = forms.CharField(required=True, error_messages=ERROR_MESSAGES) published_at = forms.DateTimeField(required=True, error_messages=ERROR_MESSAGES) introductions = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, choices=lambda: [(v.id, v.id) for v in Introduction.get_all()], error_messages=ERROR_MESSAGES) topics = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, choices=lambda: [(v.id, v.id) for v in Topic.get_all()], error_messages=ERROR_MESSAGES) categories = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, choices=lambda: [(v.id, v.id) for v in Category.get_all()], error_messages=ERROR_MESSAGES) videos = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, choices=lambda: [(v.id, v.id) for v in Video.get_all()], error_messages=ERROR_MESSAGES)
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 save(self, *args, **kwargs): comm = super(CommunityForm, self).save(*args, **kwargs) UploadedFile.bind_files( self.cleaned_data.get('files', '').split('|'), comm ) videos = json.loads(self.cleaned_data.get('videos', '')) Video.save_videos(videos, comm) # Add the community to project if a project id was given. project_id = self.cleaned_data.get('project_id', None) if project_id: project = get_object_or_None(Project, pk=int(project_id)) if project: project.save_related_object(comm, self.user) return comm
def init_cache_table(): existing_videos = Video.objects.all() if existing_videos.count() > 0: existing_videos.delete() cached_videos = get_local_videos() # print(cached_videos) real_cached_videos = get_real_local_videos() # print(real_cached_videos) num_real_videos = len(real_cached_videos) hostname = get_local_name() for vid in cached_videos: vid_id = int(vid) vid_name = real_cached_videos[vid_id%num_real_videos] # vid_name = random.choice(real_cached_videos) vid_srvs = hostname + ', ' cur_vid = Video(id=vid_id, name=vid_name, srvs=vid_srvs) cur_vid.save()
def process_item(self, item, spider): valid = True for data in item: if not data: valid = False raise DropItem("Missing %s from %s" % (data, item['url'])) log.msg("Missing %s from %s" % (data, item['url'])) if valid: vid = Video(embed_url=item["embed_url"], artist=item["artist"], url=item["url"], image=item["image"], title=item["title"]) vid.save() print "Saved video %s " % vid log.msg("Video saved to database %s" % vid, level=log.DEBUG, spider=spider) return item
def post(self,request,*args,**kwargs): form_post = VideoForm(request.POST, request.FILES) if request.is_ajax() and form_post.is_valid(): video = form_post.save(commit=False) new_video = Video.create_video(creator=request.user, title=video.title, file=video.file, image=video.image, uri=video.uri, lists=request.POST.getlist("list"), is_public=request.POST.get("is_public"), community=None) return render_for_platform(request, 'user_video/new_video.html',{'object': new_video}) else: return HttpResponseBadRequest()
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 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 load_videos(context, obj=None): if obj: videos = Video.get_videos_for(obj) object_id = obj.id content_type = ContentType.objects.get_for_model(obj).id else: videos = [] object_id = '' content_type = '' return dict(videos=videos, object_id=object_id, content_type=content_type)
def add(request): cur_host = get_local_name() remote_host = request.META['HTTP_AGENS_REMOTE'] print("The video/add request sent by", remote_host) if request.method == "POST": print(request.POST) new_updates = defaultdict(list) srvs = request.POST.keys() for srv in srvs: vid_list_str = request.POST.get(srv, "") vid_list = [int(s) for s in vid_list_str.split(',')] # print(vid_list) for vid in vid_list: vid_id = vid # print('Processing video ', vid_id, "!") vid_exist = Video.objects.filter(id=vid_id) if vid_exist.count() > 0: vid_obj = Video.objects.get(id=vid_id) # print("Video object with id = ", vid_id, " found in local cache table!") vid_srv_list = vid_obj.srvs.split(', ') # print("Video server list in cache table:", vid_srv_list) if srv not in vid_srv_list: vid_obj.srvs = vid_obj.srvs + srv + ', ' new_updates[srv].append(vid) # print("New srvs for video ", vid, " is ", vid_obj.srvs) vid_obj.save() # print("Server ", srv, " has been added to Video ", vid, " in cache table!") else: vid_name = 'BBB' isLocal = False vid_srvs = srv + ', ' # print("srvs for video ", vid, " is ", vid_srvs) new_vid_obj = Video(id=vid_id, name=vid_name, isLocal=isLocal, srvs=vid_srvs) new_vid_obj.save() new_updates[srv].append(vid) # print("Video ", vid, " on server ", srv," has been added to cache table!") # print('Start forwarding the updates on this agent from', remote_host) new_update_str = update_list2str(new_updates) # print('The updates are', new_update_str) forward_updates(remote_host, new_update_str) return HttpResponse("Successfully update video list cached on " + srv + "!") elif request.method == "GET": return HttpResponse("You should use POST method when calling http://cache_agent:port/video/add/ to add video lists!")
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 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 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, })
class SimpleVideoTests(TestCase): def setUp(self): self.video = Video() def test_matches_file_type(self): self.assertTrue(self.video.matches_file_type('videofile.mp4', None, None)) self.assertTrue(self.video.matches_file_type('~/videofile.mp4', None, None)) self.assertTrue(self.video.matches_file_type('video file with spaces.mp4', None, None)) self.assertTrue(self.video.matches_file_type('videofile.dv', None, None)) self.assertTrue(self.video.matches_file_type('videofile.mov', None, None)) self.assertTrue(self.video.matches_file_type('videofile.avi', None, None)) self.assertTrue(self.video.matches_file_type('videofile.wmv', None, None)) self.assertFalse(self.video.matches_file_type('videofile', None, None)) self.assertFalse(self.video.matches_file_type('videofile.zzz', None, None))
def get_youku_playlist_from_playlist_config(video_id): """ 根据视频video_id所属的youtube playlist,在PlaylistConfig 中查找其对应 的youku playlist,可能是1-n个 :param video_id: :return: """ video = Video.get(video_id=video_id) youtube_playlist = video.playlist playlist_config_list = PlaylistConfig.filter( youtube_playlist=youtube_playlist) return playlist_config_list
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 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(_, 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 save(self, user): video = None rules = list(ProviderRule.objects.all()) patterns = [re.compile(r.regex) for r in rules] self.full_clean() for i, part in re_parts(patterns, self.cleaned_data['url']): rule = rules[i] FORMAT = getattr(settings, "OEMBED_FORMAT", "json") url = u"%s?url=%s&maxwidth=%s&maxheight=%s&format=%s" % ( rule.endpoint, part, 600, 400, FORMAT ) resp = simplejson.loads(fetch(url)) replacement = render_to_string('oembed/%s.html' % resp['type'], {'response': resp}) # TODO: this should be in oembed, bit dont want to modify it now if(resp): if(resp.has_key('thumbnail_url')): thumbnail_url = resp['thumbnail_url'] else: p = re.compile('v=([^&]+)') m = p.search(self.cleaned_data['url']) id = m.group() id = id.replace("v=","") thumbnail_url = "http://img.youtube.com/vi/"+id+"/1.jpg" #import pdb; pdb.set_trace() video = Video(creator= user, import_url=self.cleaned_data['url'], was_uploaded=False, thumbnail_url=thumbnail_url, title=self.cleaned_data['title'], ) video.save() return video
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 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, })
class IntroductionForm(forms.Form): name = forms.CharField(required=True, error_messages=ERROR_MESSAGES) text = forms.CharField(required=True, error_messages=ERROR_MESSAGES) thumbnail = forms.CharField(required=True, error_messages=ERROR_MESSAGES) titles = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, choices=lambda: [(v.id, v.id) for v in Title.get_all()], error_messages=ERROR_MESSAGES) videos = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, choices=lambda: [(v.id, v.id) for v in Video.get_all()], error_messages=ERROR_MESSAGES) published_at = forms.DateTimeField(required=True, error_messages=ERROR_MESSAGES)
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 test_url_title_correct(self): """ Check if the url's name is filled in """ v1 = Video(url="http://www.youtube.com/watch?v=KWJpKNQfXWo&list=FLoxcjq-8xIDTYp3uz647V5A") v1.save() self.assertEqual("Iodine Clock (slow motion) - Periodic Table of Videos", v1.title) v2 = Video(url="http://vimeo.com/57691682") v2.save() self.assertEqual("Cool Hunting Video Presents: The Planetarium Projector Museum", v2.title)
def set_youku_playlist_online_from_config_playlist(video_id): """ 根据上传到优酷的视频的video_id的YouTube上的playlist,设置视频在优酷上的playlist 数据库中youtube_playlist与youku_playlist是多对多关系 :param youku_video_id: :return: """ playlist_id_list = get_youku_playlist_from_playlist_config(video_id) if playlist_id_list: video = Video.get(video_id=video_id) setted_playlist_id_list = [] for playlist_id in playlist_id_list: setted_playlist_id = set_youku_playlist_online( video.youku_video_id, playlist_id) setted_playlist_id_list.append(setted_playlist_id) return setted_playlist_id_list else: return False
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(_, lang, category_id): if lang == 'ja': cached_videos = Cache.get('api_videos_' + str(category_id)) if cached_videos is None: res = VideosSerializer(Video.get_by_category_id(category_id), many=True).data Cache.set('api_videos_' + str(category_id), res) else: res = cached_videos elif lang == 'en': cached_videos_en = Cache.get('api_videos_en_' + str(category_id)) if cached_videos_en is None: res = VideosEnSerializer( VideoEn.get_by_category_id(category_id), many=True).data Cache.set('api_videos_en_' + str(category_id), res) else: res = cached_videos_en else: return JsonResponse({'message': 'Not Found'}, status=404) return JsonResponse(res, safe=False)
def get(_, lang): if lang == 'ja': cached_videos = Cache.get('api_videos_all') if cached_videos is None: res = VideosSerializer(Video.get_published_all(), many=True).data Cache.set('api_videos_all', res) else: res = cached_videos elif lang == 'en': cached_videos_en = Cache.get('api_videos_en_all') if cached_videos_en is None: res = VideosEnSerializer(VideoEn.get_published_all(), many=True).data Cache.set('api_videos_en_all', res) else: res = cached_videos_en else: return JsonResponse({'message': 'Not Found'}, status=404) return JsonResponse(res, safe=False)
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 )
class TopicForm(forms.Form): post_type = forms.CharField(required=True, error_messages=ERROR_MESSAGES) new = forms.BooleanField(required=False, error_messages=ERROR_MESSAGES) title = forms.CharField(required=True, error_messages=ERROR_MESSAGES) text = forms.CharField(required=True, error_messages=ERROR_MESSAGES) url = forms.CharField(required=True, error_messages=ERROR_MESSAGES) button_label = forms.CharField(required=True, error_messages=ERROR_MESSAGES) published_at = forms.DateTimeField(required=True, error_messages=ERROR_MESSAGES) event_date = forms.DateTimeField(required=False, error_messages=ERROR_MESSAGES) thumbnail = forms.CharField(required=True, error_messages=ERROR_MESSAGES) images = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, choices=lambda: [(v.id, v.id) for v in Image.get_all()], error_messages=ERROR_MESSAGES) videos = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, choices=lambda: [(v.id, v.id) for v in Video.get_all()], error_messages=ERROR_MESSAGES)
def video_gallery(context, obj=None): videos = Video.get_videos_for(obj) if obj else [] return dict(videos=videos, STATIC_URL=settings.STATIC_URL)
def _saveVideo(self,videoFields): video=Video(**videoFields) video.save() return video
def upload_handler(request): if request.method == "POST": f = request.FILES["upload"] filename = str(f) f_ext = os.path.splitext(str(f))[1] # If file is a compatible music file, build a filesystem structure for # it (media/artist-name/album-name), then write it to that location and # add details of the file to the database. if f_ext in [".mp3", ".MP3"]: with open(MEDIA_ROOT + str(f), "wb") as destination: for chunk in f.chunks(): destination.write(chunk) filename = eyed3.load(MEDIA_ROOT + filename) dir_struct = MEDIA_ROOT + "music" + "/" + filename.tag.artist + "/" + filename.tag.album + "/" try: if not os.path.isdir(dir_struct): os.makedirs(dir_struct) shutil.move(MEDIA_ROOT + str(f), dir_struct) except OSError as ose: if ose.errno != 17: raise # Need to pass on Errno 17, due to race conditions caused # by making directories that already exist. pass except Exception as e: # File already exists. Remove the duplicate copy. os.remove(MEDIA_ROOT + str(f)) return render_to_response( "errors/file_already_exists.html", locals(), context_instance=RequestContext(request) ) # If the artist or album doesn't exist in the database, create # table(s) for them. If they already exists, perform a query to # obtain an Artist or Album object for use as a foreign key. if not Artist.objects.filter(name=filename.tag.artist).exists(): artist = Artist(name=filename.tag.artist) artist.save() else: artist_set = Artist.objects.filter(name=filename.tag.artist) artist = [a for a in artist_set][0] if not Album.objects.filter(title=filename.tag.album).exists(): album = Album(title=filename.tag.album, artist=artist) album.save() else: album_set = Album.objects.filter(title=filename.tag.album) album = [a for a in album_set][0] if not Track.objects.filter(title=filename.tag.title).exists(): track = Track( title=filename.tag.title, album=album, artist=artist, fspath=dir_struct + str(f), media_url=MEDIA_URL + (dir_struct + str(f)).split(MEDIA_ROOT)[1], ) track.save() print "Added to DB: " + filename.tag.title return render_to_response( "errors/upload_success.html", locals(), context_instance=RequestContext(request) ) else: return render_to_response( "errors/file_already_exists.html", locals(), context_instance=RequestContext(request) ) elif f_ext in [".jpg", ".JPG"]: if not os.path.exists(MEDIA_ROOT + "pictures/" + str(f)): with open(MEDIA_ROOT + "pictures/" + str(f), "wb") as destination: for chunk in f.chunks(): destination.write(chunk) else: # File already exists. Remove the duplicate copy. return render_to_response( "errors/file_already_exists.html", locals(), context_instance=RequestContext(request) ) # If the picture doesn't exist in the database, add it. if not Picture.objects.filter(name=str(f)).exists(): picture = Picture( name=os.path.splitext(str(f))[0], filename=str(f), fspath=MEDIA_ROOT + "pictures/" + str(f), media_url=MEDIA_URL + (MEDIA_ROOT + "pictures/" + str(f)).split(MEDIA_ROOT)[1], ) picture.save() print "Added to DB: " + str(f) return render_to_response( "errors/upload_success.html", locals(), context_instance=RequestContext(request) ) else: return render_to_response( "errors/file_already_exists.html", locals(), context_instance=RequestContext(request) ) elif f_ext in [".mp4", ".MP4", ".m4v", ".M4V"]: if not os.path.exists(MEDIA_ROOT + "videos/" + str(f)): with open(MEDIA_ROOT + "videos/" + str(f), "wb") as destination: for chunk in f.chunks(): destination.write(chunk) else: # File already exists. Remove the duplicate copy. return render_to_response( "errors/file_already_exists.html", locals(), context_instance=RequestContext(request) ) # If the video doesn't exist in the database, add it. if not Video.objects.filter(title=str(f)).exists(): video = Video( title=os.path.splitext(str(f))[0], filename=str(f), fspath=MEDIA_ROOT + "videos/" + str(f), media_url=MEDIA_URL + (MEDIA_ROOT + "videos/" + str(f)).split(MEDIA_ROOT)[1], ) video.save() print "Added to DB: " + str(f) return render_to_response( "errors/upload_success.html", locals(), context_instance=RequestContext(request) ) else: return render_to_response( "errors/file_already_exists.html", locals(), context_instance=RequestContext(request) ) return render_to_response("errors/upload_failure.html", locals(), context_instance=RequestContext(request))
def _saveVideo(self,videoFields): v=Video(**videoFields) v.save()
def upload_video(request, template_name='video/upload.html'): if request.method == 'POST': form = VideoForm(request.POST, request.FILES) if form.is_valid(): vimeoClient = VimeoClient(settings.VIMEO_API_KEY, settings.VIMEO_API_SECRET) tempVideo = open(tempfile.mktemp(".AVI"), 'wb+') for chunk in form.files['video'].chunks(): tempVideo.write(chunk) try: ticked_id = vimeoClient.upload(tempVideo.name) except Exception, inst: mail_admins("Error Uploading Video", "Vimeo Video konnte nicht hochgeladen werden: "\ +str(inst.args)) return render_to_response("video/upload_error.html", { }, context_instance=RequestContext(request)) tempVideo.close() if ticked_id: video_id = vimeoClient.check_upload_status(ticked_id) if video_id: #get thumbnail url rsp = vimeoClient.call("vimeo.videos.getThumbnailUrl", {"video_id": video_id, "size":"160x120"} ) thumbnail_url = rsp.getElementsByTagName("thumbnail")[0]\ .childNodes[0].nodeValue #set the values video = Video(creator=request.user, import_url="http://vimeo.com/"+video_id, was_uploaded=True, is_viewable=False, external_id=video_id, ticket_id=ticked_id, comment=form.cleaned_data['comment'], title=form.cleaned_data['title'], tags=form.cleaned_data['tags'], thumbnail_url=thumbnail_url ) video.save(); rsp = vimeoClient.call("vimeo.videos.setTitle", { "title": form.cleaned_data['title'], "video_id": video_id } ) if(rsp.attributes['stat'].value!="ok"): mail_admins("Error", "Vimeo Titel konnte nicht gesetzt werden:\ Video_id: "+str(video.pk)) rsp = vimeoClient.call("vimeo.videos.setCaption", { "caption": form.cleaned_data['comment'], "video_id": video_id } ) if(rsp.attributes['stat'].value!="ok"): mail_admins("Error", "Vimeo Caption konnte nicht gesetzt werden:\ Video_id: "+str(video.pk)) rsp = vimeoClient.call("vimeo.videos.setPrivacy", {"privacy": "anybody", "video_id": video_id} ) if(rsp.attributes['stat'].value!="ok"): mail_admins("Error", "Vimeo Privacy konnte nicht gesetzt werden:\ Video_id: "+str(video.id)) if form.cleaned_data['tags']: tags = parse_tag_input(video.tags) tags = ",".join(tags) rsp = vimeoClient.call("vimeo.videos.addTags", {"tags": tags, "video_id": video_id} ) if(rsp.attributes['stat'].value!="ok"): mail_admins("Error", "Vimeo Tags konnten nicht gesetzt \ werden: Video_id: "+str(video.id)) return render_to_response("video/upload_success.html", { "video": video, }, context_instance=RequestContext(request)) # an error has occurred return render_to_response("video/upload_error.html", { }, context_instance=RequestContext(request)) else: request.user.message_set.create(message=_("Video '%s' was \ successfully uploaded!") % video.title) return HttpResponseRedirect(reverse('show_video', args=(video.id,)))
def store_user(data): # # User # firstname = data['firstname'] if not firstname: firstname = " " lastname = data['lastname'] if not lastname: lastname = " " user = User(username=data['name'], first_name=firstname, last_name=lastname, email=data['email'], password="******"+data["pass"]) user.save(force_insert=True) print "User: "******" " #profile = Profile(user=user, # first_name=firstname, # last_name=lastname, # city=city, # about=data['description']) #profile.save() #account = Account(user=user) #account.save() # avatar # # stories - do them first, since they are containers that we want to add items to # stories = get_stories(data["user_id"]) for story in stories: print "-Story: "+str(story['story_id']) title = story['title'] if not title: title = " " new_story = Story(title=title, slug=slugify(title), creator=user, description=story['text'], mapmode=convert_mapmode(story['mapmode']), creation_date=convert_time(story['timestamp']), update_date=convert_time(story['timestamp']), privacy=get_privacy_of_old_privacy(story['right_view']), status=get_status_of_old_privacy(story['right_view'])) new_story.slug = make_unique(new_story, lambda x: Story.objects.filter(slug__exact=x.slug).count() == 0) new_story.save() migrated_post = MigratedItem(type="story", old_id=story["story_id"], new_id=new_story.pk) migrated_post.save() store_tags_of_item(new_story, story['story_id']) set_hit_count(new_story, story['view_count']) # lines lines = get_lines(data["user_id"]) if lines: for line in lines: print "-Line: "+str(line['line_id']) linestring = make_linestring_of_string(line["controlpoints"], line["start_marker_id"], line["end_marker_id"]) if linestring: line_post = get_post_of_line(line['line_id']) if not line_post: title = " " description = " " else: if line_post['title']: title = line_post['title'] else: title = " " if line_post['text']: description = line_post['text'] else: description = " " new_line = GeoLineTag(creator=user, title=title, description=description, line=linestring, ) # add to story line_w_story = get_story_of_line(line['line_id']) if line_w_story and line_w_story['story_id']: try: new_story = Story.objects.get(pk=get_new_id("story",line_w_story['story_id'])) print "Adding line %s (%s) to story %s (%s)"%(line['line_id'], new_line.id, line_w_story['story_id'], new_story.id) new_line.content_object = new_story except: print "Could not add Story" new_line.save() migrated_line = MigratedItem(type="line", old_id=line["line_id"], new_id=new_line.pk) migrated_line.save() # video videos = get_videos(data["user_id"]) for video in videos: print "-Video: "+str(video['video_id']) if video['medialocation']: import re video_id = re.findall(r"/v/(.+)", video['medialocation'])[0] import_url = "http://www.youtube.com/watch?v="+video_id comment = video['text'] if not comment: comment = " " new_video = Video(creator=user, title=video['title'], comment=comment, was_uploaded=False, import_url=import_url, thumbnail_url=video['thumb1'], safetylevel=get_privacy_of_old_privacy(video['right_view']), last_modified=convert_time(video['timestamp']), date_added=convert_time(video['timestamp']), ) new_video.save() migrated_video = MigratedItem(type="video", old_id=video["video_id"], new_id=new_video.pk) migrated_video.save() # add to story if video["story_id"]: story = Story.objects.get(pk=get_new_id("story", video["story_id"])) count = StoryLineItem.objects.filter(creator=user, story=story, timestamp_start__lte=convert_time(video['timestamp'])).count() print "Adding video %s (%s) to story %s (%s) at position: %s "%(video['video_id'], new_video.id, video["story_id"], story.id, count) text = video['text'] if not text: text = " " story_line_item = StoryLineItem(creator=user, story=story, text=text, timestamp_start=convert_time(video['timestamp']), timestamp_end=convert_time(video['timestamp'])) story_line_item.save() story_line_item_media = StoryLineItemMedia(storylineitem=story_line_item, content_object=new_video) story_line_item_media.save() # geotag if video['mapobject_id']: geotag_item(video["video_id"], story_line_item, user) if video['mapobject_id']: geotag_item(video["video_id"], new_video, user) store_tags_of_item(new_video, video["video_id"]) set_hit_count(new_video, video['view_count']) # posts posts = get_posts(data["user_id"]) for post in posts: print "-Post: "+str(post['post_id']) if post['story_id']: post_text = post['text'] if not post_text: post_text = " " try: post_story = Story.objects.get(pk=get_new_id("story", post['story_id'])) count = StoryLineItem.objects.filter(creator=user, story=story, timestamp_start__lte=convert_time(post['timestamp'])).count() print "Adding post %s to story %s (%s) at position: %s "%(post['post_id'], post["story_id"], post_story.id, count) new_post = StoryLineItem(creator=user, story=post_story, text=post_text, timestamp_start=convert_time(post['timestamp']), timestamp_end=convert_time(post['timestamp'])) new_post.save() migrated_post = MigratedItem(type="post", old_id=post["post_id"], new_id=new_post.pk) migrated_post.save() if post['mapobject_id']: geotag_item(post["post_id"], new_post, user) store_tags_of_item(new_post, post["post_id"]) set_hit_count(new_post, post['view_count']) except: print "Could not add to Story" # images images = get_images(data["user_id"]) if images: for image in images: print "-Image: "+str(image['image_id']) caption = image['text'] if not caption: caption = " " title = image['title'] if not title: title = " " new_image = Image(member=user, title=title, caption=caption, date_added=convert_time(image['timestamp']), ) try: new_image.image.save(os.path.basename(image["filename"]+".jpg"), ContentFile(open(path_to_images+image["filename"]+".jpg", "r").read())) migrated_image = MigratedItem(type="image", old_id=image["image_id"], new_id=new_image.pk) new_image.save() migrated_image.save() if image["story_id"]: story = Story.objects.get(pk=get_new_id("story", image["story_id"])) count = StoryLineItem.objects.filter(creator=user, story=story, timestamp_start__lte=convert_time(image['timestamp'])).count() print "Adding image %s (%s) to story %s (%s) at position: %s "%(image['image_id'], new_image.id, image["story_id"], story.id, count) story_line_item = StoryLineItem(creator=user, story=story, text=caption, position=count, timestamp_start=convert_time(image['timestamp']), timestamp_end=convert_time(image['timestamp'])) story_line_item.save() story_line_item_media = StoryLineItemMedia(storylineitem=story_line_item, content_object=new_image) story_line_item_media.save() if image['mapobject_id']: geotag_item(image['image_id'], story_line_item, user) if image['mapobject_id']: geotag_item(image['image_id'], new_image, user) store_tags_of_item(new_image, image["image_id"]) set_hit_count(new_image, image['view_count']) except: print "Could not store image: %s filename: %s"%(image['image_id'], image['filename']) # story image # store user migrated_user = MigratedItem(type="user", old_id=data["user_id"], new_id=user.pk) migrated_user.save() make_avatar(data) # flickr images # TODO: