Example #1
0
def detail(request, movie_id):
	try:
		movie = Movie.objects.get(pk=movie_id)
	except Movie.DoesNotExist:
		raise Http404('Movie does not exist')

# Make request to YouTube API for trailer
	q = movie.title + ' trailer'
	args = {
		'q': q,
		'max_results': '1',
		'safeSearch': 'moderate'
	}

	link = execute_youtube_search(args)

	if link:
		movie.video = detect_backend(link)
	else:
		movie.video = detect_backend('https://www.youtube.com/watch?v=dQw4w9WgXcQ')
		# Defaults to this video if one is not found. If you have
		# time, check it out! It's one of my favorites :)
	context = {
		'movie': movie,
		'trailer': movie.video
	}

	return render(request, 'movies/detail.html', context);
 def video_upload(self, event):
     try:
         resource = Resource.objects.get(pk=event['pk'])
         detect_backend(resource.url).upload_resource(resource=resource)
         logger.info("Async task video upload: {}".format(resource.url))
     except ObjectDoesNotExist:
         logger.error(
             "UploadChannelConsumer.video_upload.ObjectDoesNotExist: {}".
             format(event.get("pk")))
    def validate_url(self, data):
        try:
            detect_backend(data)
            if Resource.objects.draft_and_available().filter_by_url(
                    data).exists():
                raise serializers.ValidationError("duplicated")
        except UnknownBackendException:
            raise serializers.ValidationError("invalid")

        return data
Example #4
0
def embedVideo(request):
    param = dict()
    param['my_video'] = detect_backend('https://player.vimeo.com/video/263910146')
    print(detect_backend('https://player.vimeo.com/video/263910146').url)
    print(detect_backend('https://player.vimeo.com/video/263910146').thumbnail)
    print(detect_backend('https://player.vimeo.com/video/263910146').backend)
    print(param)
    #param['url'] = 'http://player.vimeo.com/video/263910146'
    #param['thumbnail'] = 'http://i.vimeocdn.com/video/693556885_640.jpg'
    #param['backend'] = 'VimeoBackend'
    return  render_to_response('embed_video.html',param)
def create_thumbnail(model_instance):
    # http://stackoverflow.com/a/25648427/1179222
    from wagtail.wagtailimages.models import get_image_model
    WagtailImage = get_image_model()

    # CREATING IMAGE FROM THUMBNAIL
    backend = detect_backend(model_instance.url)
    thumbnail_url = backend.get_thumbnail_url()
    if backend.__class__.__name__ == 'YoutubeBackend':
        if thumbnail_url.endswith('hqdefault.jpg'):
            for resolution in YOUTUBE_RESOLUTIONS:
                temp_thumbnail_url = thumbnail_url.replace(
                    'hqdefault.jpg', resolution)
                if checkUrl(temp_thumbnail_url):
                    thumbnail_url = temp_thumbnail_url
                    break

    img_temp = NamedTemporaryFile(delete=True)
    try:
        img_temp.write(urllib2.urlopen(thumbnail_url).read())
    except:
        http = urllib3.PoolManager()
        img_temp.write(http.request('GET', thumbnail_url).data)
    img_temp.flush()

    image = WagtailImage(title=model_instance.title)
    image.file.save(model_instance.title + '.jpg', File(img_temp))

    model_instance.thumbnail = image
    model_instance.thumbnail.tags.add('video-thumbnail')
    model_instance.save()
Example #6
0
    def _build_object(self):
        polygon = 'SRID=%s;MULTIPOLYGON(((0 0, 0 3, 3 3, 3 0, 0 0)))' % settings.SRID
        self.city = zoning_factories.CityFactory(geom=polygon)
        self.district = zoning_factories.DistrictFactory(geom=polygon)

        self.content = self.factory(geom='SRID=%s;POINT(1 1)' % settings.SRID)

        self.picture = common_factories.AttachmentFactory(obj=self.content,
                                                          attachment_file=get_dummy_uploaded_image())
        self.document = common_factories.AttachmentFactory(obj=self.content,
                                                           attachment_file=get_dummy_uploaded_document())
        self.video = common_factories.AttachmentFactory(obj=self.content, attachment_file='',
                                                        attachment_video='https://www.youtube.com/watch?v=Jm3anSjly0Y')
        self.video_detected = detect_backend(self.video.attachment_video)

        self.theme = common_factories.ThemeFactory()
        self.content.themes.add(self.theme)
        self.source = common_factories.RecordSourceFactory()
        self.content.source.add(self.source)

        path = core_factories.PathFactory(geom='SRID=%s;LINESTRING(0 10, 10 10)' % settings.SRID)
        self.trek = trekking_factories.TrekFactory(no_path=True)
        self.trek.add_path(path)
        self.poi = trekking_factories.POIFactory(no_path=True)
        self.poi.add_path(path, start=0.5, end=0.5)
Example #7
0
def chooser_select_format(request, embed_video_id):
    embed_video = get_object_or_404(get_embed_video_model(), id=embed_video_id)

    if request.POST:
        form = EmbedVideoInsertionForm(request.POST, initial={'alt_text': embed_video.default_alt_text})

        if form.is_valid():

            # format = get_embed_video_format(form.cleaned_data['format'])
            preview_embed_video = detect_backend(embed_video.url).get_thumbnail_url()

            embed_video_json = json.dumps({
                'id': embed_video.id,
                'title': embed_video.title,
                'format': format.name,
                'alt': form.cleaned_data['alt_text'],
                'class': format.classnames,
                'edit_link': reverse('wagtail_embed_videos:edit', args=(embed_video.id,)),
                'preview': {
                    'url': preview_embed_video,
                },
                'html': format.embed_video_to_editor_html(embed_video, form.cleaned_data['alt_text']),
            })

            return render_modal_workflow(
                request, None, 'wagtail_embed_videos/chooser/embed_video_chosen.js',
                {'embed_video_json': embed_video_json}
            )
    else:
        form = EmbedVideoInsertionForm(initial={'alt_text': embed_video.default_alt_text})

    return render_modal_workflow(
        request, 'wagtail_embed_videos/chooser/select_format.html', 'wagtail_embed_videos/chooser/select_format.js',
        {'embed_video': embed_video, 'form': form}
    )
def create_thumbnail(model_instance):
    # CREATING IMAGE FROM THUMBNAIL
    backend = detect_backend(model_instance.url)
    thumbnail_url = backend.get_thumbnail_url()
    if backend.__class__.__name__ == 'YoutubeBackend':
        if thumbnail_url.endswith('hqdefault.jpg'):
            for resolution in YOUTUBE_RESOLUTIONS:
                temp_thumbnail_url = thumbnail_url.replace(
                    'hqdefault.jpg', resolution)
                if checkUrl(temp_thumbnail_url):
                    thumbnail_url = temp_thumbnail_url
                    break

    img_temp = NamedTemporaryFile(delete=True)
    try:
        img_temp.write(urllib2.urlopen(thumbnail_url).read())
    except:
        http = urllib3.PoolManager()
        img_temp.write(http.request('GET', thumbnail_url).data)
    img_temp.flush()

    image = WagtailImage(title=model_instance.title)
    image.file.save(model_instance.title + '.jpg', File(img_temp))

    model_instance.thumbnail = image
    model_instance.thumbnail.tags.add('video-thumbnail')
    model_instance.save()
Example #9
0
 def get_video_id(self):
     """
     Get the video id for video referenced.
     """
     video = detect_backend(self.video)
     video_id = video.get_code()
     return video_id
Example #10
0
def strate(url):

    data = {}

    # Youtube, Vimeo, SoundCloud
    try:
        video = detect_backend(url)
    except UnknownBackendException:
        pass
    else:
        data = {
            'type': 'video',
            'thumbnail': video.thumbnail,
            'title': video.title,
            'description': video.description,
            'author': video.author,
            'embed_video': video.get_embed_code(),
            'strate_name': 'YouTube',
            'strate_logo': 'youtube.png',
        }

    d = detect_input(url)
    if d is not None:
        data = d

    return data
Example #11
0
    def test_videos(self):
        self.assertDictEqual(
            self.result['videos'][0], {
                u'backend': 'Youtube',
                u'url':
                'http://www.youtube.com/embed/Jm3anSjly0Y?wmode=opaque',
                u'title': self.video.title,
                u'legend': self.video.legend,
                u'author': self.video.author,
                u'code': self.video_detected.code
            })
        self.video = common_factories.AttachmentFactory(
            content_object=self.content,
            attachment_file='',
            attachment_video='http://www.dailymotion.com/video/x6e0q24')
        self.video_detected = detect_backend(self.video.attachment_video)
        self.pk = self.content.pk
        url = '/api/en/{model}s/{pk}.json'.format(
            model=self.content._meta.model_name, pk=self.pk)
        self.response = self.client.get(url)
        self.result = json.loads(self.response.content)

        self.assertDictEqual(
            self.result['videos'][0], {
                u'backend': 'Dailymotion',
                u'url': 'http://www.dailymotion.com/embed/video/x6e0q24',
                u'title': self.video.title,
                u'legend': self.video.legend,
                u'author': self.video.author,
                u'code': self.video_detected.code
            })
Example #12
0
def create_thumbnail(model_instance):
    # CREATING IMAGE FROM THUMBNAIL
    backend = detect_backend(model_instance.url.strip())
    thumbnail_url = backend.get_thumbnail_url()
    if backend.__class__.__name__ == 'YoutubeBackend':
        if thumbnail_url:
            if thumbnail_url.endswith('hqdefault.jpg'):
                for resolution in YOUTUBE_RESOLUTIONS:
                    temp_thumbnail_url = thumbnail_url.replace(
                        'hqdefault.jpg', resolution)
                    if checkUrl(temp_thumbnail_url):
                        thumbnail_url = temp_thumbnail_url
                        break
    
    img_temp = NamedTemporaryFile()

    if not thumbnail_url:
        image = Image.new('RGB', (165,92), (255,255,255))
        bytesArr = BytesIO()
        image.save(bytesArr, 'PNG')
        img_temp.write(bytesArr.getvalue())
    else:
        try:
            img_temp.write(urllib2.urlopen(thumbnail_url).read())
        except:
            http = urllib3.PoolManager()
            img_temp.write(http.request('GET', thumbnail_url).data)
    img_temp.flush()

    image = get_image_model()(title=model_instance.title)
    image.file.save(model_instance.title + '.jpg', File(img_temp))

    model_instance.thumbnail = image
    model_instance.thumbnail.tags.add('video-thumbnail')
    model_instance.save()
Example #13
0
    def internal(self):
        try:
            internal = detect_backend(self.url).is_internal
        except (UnknownBackendException, TypeError):
            internal = False

        return internal
Example #14
0
    def _build_object(self):
        polygon = 'SRID=%s;MULTIPOLYGON(((0 0, 0 3, 3 3, 3 0, 0 0)))' % settings.SRID
        self.city = zoning_factories.CityFactory(geom=polygon)
        self.district = zoning_factories.DistrictFactory(geom=polygon)

        self.content = self.factory(geom='SRID=%s;POINT(1 1)' % settings.SRID)

        self.picture = common_factories.AttachmentFactory(
            content_object=self.content,
            attachment_file=get_dummy_uploaded_image())
        self.document = common_factories.AttachmentFactory(
            content_object=self.content,
            attachment_file=get_dummy_uploaded_document())
        self.video = common_factories.AttachmentFactory(
            content_object=self.content,
            attachment_file='',
            attachment_video=
            'http://www.youtube.com/embed/Jm3anSjly0Y?wmode=opaque')
        self.video_detected = detect_backend(self.video.attachment_video)

        self.theme = common_factories.ThemeFactory()
        self.content.themes.add(self.theme)
        self.source = common_factories.RecordSourceFactory()
        self.content.source.add(self.source)

        self.portal = common_factories.TargetPortalFactory()
        self.content.portal.add(self.portal)

        path = core_factories.PathFactory(
            geom='SRID=%s;LINESTRING(0 10, 10 10)' % settings.SRID)
        self.trek = trekking_factories.TrekFactory(no_path=True)
        self.trek.add_path(path)
        self.poi = trekking_factories.POIFactory(no_path=True)
        self.poi.add_path(path, start=0.5, end=0.5)
 def get_embed_url_source(self):
     if self.video_url:
         backed_class = type(detect_backend(self.video_url))
         if backed_class is embed_video.backends.YoutubeBackend:
             return "YouTube"
         elif backed_class is embed_video.backends.VimeoBackend:
             return "Vimeo"
     else:
         return None
Example #16
0
 def video_link(self):
     if self.url:
         try:
             match = detect_backend(self.url)
             if match:
                 return True
         except:
             pass
     return False
Example #17
0
    def video(self):
        if not self.description_link:
            return None
        try:
            backend = detect_backend(self.description_link)

            return self.get_video_embed_link(backend)
        except UnknownBackendException:
            return None
Example #18
0
 def get_embed_url_source(self):
     if self.video_url:
         backed_class = type(detect_backend(self.video_url))
         if backed_class is embed_video.backends.YoutubeBackend:
             return "YouTube"
         elif backed_class is embed_video.backends.VimeoBackend:
             return "Vimeo"
     else:
         return None
Example #19
0
def _video_link(video_url):
    try:
        backend = detect_backend(video_url)
        return mark_safe(
            backend.get_embed_code(MAX_VIDEO_HEIGHT, MAX_VIDEO_WIDTH))
    except UnknownBackendException:
        return ""
    except UnknownIdException:
        return ""
Example #20
0
 def get_video_thumbnail_url(self):
     """
     Get the thumbnail for the video at size 3400 x 1500 in jpg format.
     """
     video = detect_backend(self.video)
     orig_thumbnail_url = video.get_thumbnail_url().split('_')
     new_thumbnail_url = (
         '{}_{}'.format(orig_thumbnail_url[0], '3400x1500.jpg')
     )
     return new_thumbnail_url
Example #21
0
 def video_link(self):
     if self.url:
         try:
             match = detect_backend(self.url)
             print(match)
             if match:
                 return True
         except:
             pass
     return False
Example #22
0
 def get_featured_image_url(self):
     
     imageURL = ""
     if self.featured_image:
         imageURL = self.featured_image.url
     elif self.embeded_video:
         try:
             imageURL = detect_backend(self.embeded_video).thumbnail
         except Exception, e:
             imageURL = ""
Example #23
0
 def post(self, request, *args, **kwargs):
     print(request.POST)
     video = detect_backend(request.POST['url'])
     cc_url = "https://www.youtube.com/api/timedtext?lang=en&v=%s" % (
         video.get_code())
     vid_url = video.get_code()
     return render(request, 'vidsearch/view.html', {
         "my_video": video,
         "cc_url": cc_url,
         'vid_url': vid_url
     })
Example #24
0
 def serializable_videos(self):
     serialized = []
     for att in self.videos:
         video = detect_backend(att.attachment_video)
         serialized.append({
             'author': att.author,
             'title': att.title,
             'legend': att.legend,
             'backend': type(video).__name__.replace('Backend', ''),
             'url': att.attachment_video,
         })
     return serialized
Example #25
0
    def get_context_data(self, **kwargs):
        context = super(HomePageView, self).get_context_data(**kwargs)
        context['nav_dashboard'] = True
        context['add_google_analytis'] = settings.ADD_GOOGLE_ANALYTICS
        context['not_show_breadcrumbs'] = True  ## to not show breadcrumbs
        context['is_authenticated'] = self.request.user.is_authenticated
        if (settings.SHOW_VIDEO_TUTORIAL):
            context['video_tutorial'] = detect_backend(
                'https://www.youtube.com/watch?v=8AGaNrCGmtI')
        context['show_info_main_page'] = ShowInfoMainPage(
        )  ## show main information about the institute

        return context
Example #26
0
 def serializable_videos(self):
     serialized = []
     for att in self.videos:
         video = detect_backend(att.attachment_video)
         serialized.append({
             'author': att.author,
             'title': att.title,
             'legend': att.legend,
             'backend': type(video).__name__.replace('Backend', ''),
             'url': video.get_url(),
             'code': video.code,
         })
     return serialized
Example #27
0
def detail(request, movie_id):
    try:
        movie = Movie.objects.get(pk=movie_id)
    except Movie.DoesNotExist:
        raise Http404('Movie does not exist')

# Make request to YouTube API for trailer
    q = movie.title + ' trailer'
    args = {'q': q, 'max_results': '1', 'safeSearch': 'moderate'}

    link = execute_youtube_search(args)

    if link:
        movie.video = detect_backend(link)
    else:
        movie.video = detect_backend(
            'https://www.youtube.com/watch?v=dQw4w9WgXcQ')
        # Defaults to this video if one is not found. If you have
        # time, check it out! It's one of my favorites :)
    context = {'movie': movie, 'trailer': movie.video}

    return render(request, 'movies/detail.html', context)
Example #28
0
 def serializable_videos(self):
     serialized = []
     for att in self.videos:
         video = detect_backend(att.attachment_video)
         serialized.append(
             {
                 "author": att.author,
                 "title": att.title,
                 "legend": att.legend,
                 "backend": type(video).__name__.replace("Backend", ""),
                 "url": video.get_url(),
                 "code": video.code,
             }
         )
     return serialized
Example #29
0
 def test_video_youtube(self):
     video_youtube = common_factories.AttachmentFactory(content_object=self.content, attachment_file='',
                                                        attachment_video='http://www.youtube.com/embed/Jm3anSjly0Y?wmode=opaque')
     video_detected_youtube = detect_backend(video_youtube.attachment_video)
     pk = self.content.pk
     url = '/api/en/{model}s/{pk}.json'.format(model=self.content._meta.model_name, pk=pk)
     response = self.client.get(url)
     result = json.loads(response.content)
     self.assertDictEqual(result['videos'][0],
                          {u'backend': 'Youtube',
                           u'url': 'http://www.youtube.com/embed/Jm3anSjly0Y?wmode=opaque',
                           u'title': video_youtube.title,
                           u'legend': video_youtube.legend,
                           u'author': video_youtube.author,
                           u'code': video_detected_youtube.code})
Example #30
0
def create_thumbnail(model_instance):
    # CREATING IMAGE FROM THUMBNAIL
    print model_instance
    backend = detect_backend(model_instance.url)
    thumbnail_url = backend.get_thumbnail_url()

    img_temp = NamedTemporaryFile(delete=True)
    img_temp.write(urllib2.urlopen(thumbnail_url).read())
    img_temp.flush()

    image = WagtailImage(title=model_instance.title)
    image.file.save(model_instance.title + '.jpg', File(img_temp))

    model_instance.thumbnail = image
    model_instance.thumbnail.tags.add('video-thumbnail')
    model_instance.save()
Example #31
0
    def save(self, *args, **kwargs):
        if self.source_url and not (self.preview_url and self.embed_code):
            try:
                backend = backends.detect_backend(self.source_url)
            except backends.UnknownBackendException:
                pass
            else:
                # Force https URLS
                backend.is_secure = True

                if not self.preview_url:
                    self.preview_url = backend.get_thumbnail_url()
                if not self.embed_code:
                    self.embed_code = backend.get_embed_code('', '')

        super().save(*args, **kwargs)
Example #32
0
    def save(self, *args, **kwargs):
        if self.source_url and not (self.preview_url and self.embed_code):
            try:
                backend = backends.detect_backend(self.source_url)
            except backends.UnknownBackendException:
                pass
            else:
                # Force https URLS
                backend.is_secure = True

                if not self.preview_url:
                    self.preview_url = backend.get_thumbnail_url()
                if not self.embed_code:
                    self.embed_code = backend.get_embed_code('', '')

        super().save(*args, **kwargs)
Example #33
0
 def serializable_videos(self):
     serialized = []
     for att in self.videos:
         video = detect_backend(att.attachment_video)
         try:
             serialized.append({
                 'author': att.author,
                 'title': att.title,
                 'legend': att.legend,
                 'backend': type(video).__name__.replace('Backend', ''),
                 'url': video.get_url(),
                 'code': video.code,
             })
         except VideoDoesntExistException:
             pass
     return serialized
Example #34
0
 def serializable_videos(self):
     serialized = []
     for att in self.videos:
         video = detect_backend(att.attachment_video)
         video.is_secure = True
         try:
             serialized.append({
                 'author': att.author,
                 'title': att.title,
                 'legend': att.legend,
                 'backend': type(video).__name__.replace('Backend', ''),
                 'url': video.get_url(),
                 'code': video.code,
             })
         except VideoDoesntExistException:
             pass
     return serialized
Example #35
0
    def test_video_dailymotion(self):
        video_dailymotion = common_factories.AttachmentFactory(
            content_object=self.content, attachment_file='',
            attachment_video='http://www.dailymotion.com/video/x6e0q24')
        video_detected_dailymotion = detect_backend(video_dailymotion.attachment_video)
        pk = self.content.pk
        url = '/api/en/{model}s/{pk}.json'.format(model=self.content._meta.model_name, pk=pk)
        response = self.client.get(url)
        result = json.loads(response.content)

        self.assertDictEqual(result['videos'][0],
                             {u'backend': 'Dailymotion',
                              u'url': 'http://www.dailymotion.com/embed/video/x6e0q24',
                              u'title': video_dailymotion.title,
                              u'legend': video_dailymotion.legend,
                              u'author': video_dailymotion.author,
                              u'code': video_detected_dailymotion.code})
    def exists_dev_tag(self, video_link):
        client = VimeoClient()
        is_dev = False
        code = detect_backend(video_link).code

        try:
            tags = client.get_video_tags(code)

            for tag in tags:
                if tag.get('name') == settings.RESOURCE_DEVELOPMENT_TAG_NAME:
                    is_dev = True
        except Exception as e:
            logger.error(
                'commands.import_vimeo_resources.get_video_tags.ValueError: {}'
                .format(e))
            is_dev = True

        return is_dev
Example #37
0
def get_embed_video_json(embed_video):
    """
    helper function: given an embed video, return the json to pass back to the
    embed video chooser panel
    """
    if embed_video.thumbnail:
        preview_embed_video = embed_video.thumbnail.get_rendition('max-130x100').url
    else:
        preview_embed_video = detect_backend(embed_video.url).get_thumbnail_url()

    return json.dumps({
        'id': embed_video.id,
        'edit_link': reverse('wagtail_embed_videos:edit', args=(embed_video.id,)),
        'title': embed_video.title,
        'preview': {
            'url': preview_embed_video,
        }
    })
    def validate(self, url):
        # if empty url is not allowed throws an exception
        super().validate(url)

        if not url:
            return

        try:
            backend = detect_backend(url)
            backend.get_code()
        except UnknownBackendException:
            raise forms.ValidationError(_("URL could not be recognized."))
        except UnknownIdException:
            raise forms.ValidationError(
                _("ID of this video could not be "
                  "recognized."))
        except VideoDoesntExistException:
            raise forms.ValidationError(_("This media not found on site."))
        return url
Example #39
0
def create_thumbnail(model_instance):
    # CREATING IMAGE FROM THUMBNAIL
    # print(model_instance)
    backend = detect_backend(model_instance.url)
    thumbnail_url = backend.get_thumbnail_url()

    img_temp = NamedTemporaryFile(delete=True)
    try:
        img_temp.write(urllib2.urlopen(thumbnail_url).read())
    except:
        http = urllib3.PoolManager()
        img_temp.write(http.request("GET", thumbnail_url).data)
    img_temp.flush()

    image = WagtailImage(title=model_instance.title)
    image.file.save(model_instance.title + ".jpg", File(img_temp))

    model_instance.thumbnail = image
    model_instance.thumbnail.tags.add("video-thumbnail")
    model_instance.save()
def create_thumbnail(model_instance):
    # CREATING IMAGE FROM THUMBNAIL
    print(model_instance)
    backend = detect_backend(model_instance.url)
    thumbnail_url = backend.get_thumbnail_url()

    img_temp = NamedTemporaryFile(delete=True)
    try:
        img_temp.write(urllib2.urlopen(thumbnail_url).read())
    except:
        http = urllib3.PoolManager()
        img_temp.write(http.request('GET', thumbnail_url).data)
    img_temp.flush()

    image = WagtailImage(title=model_instance.title)
    image.file.save(model_instance.title + '.jpg', File(img_temp))

    model_instance.thumbnail = image
    model_instance.thumbnail.tags.add('video-thumbnail')
    model_instance.save()
Example #41
0
    def test_custom_backend_url_parser(self):
        # PREPARE DATA
        inputs = [
            "https://vimeo.com/4413241",
            "https://www.youtube.com/watch?v=GPB8ovFD_W4",
            "https://drive.google.com/open?id=1Lw7QrhBpYkZaXS8KATPEktjeND-kgX98",
            "https://www.dropbox.com/s/o6dnqzyhar647qu/gatos.mp4?dl=0"
        ]
        outputs = [
            "https://vimeo.com/4413241",
            "https://www.youtube.com/watch?v=GPB8ovFD_W4",
            "https://docs.google.com/uc?export=download&id=1Lw7QrhBpYkZaXS8KATPEktjeND-kgX98",
            "https://www.dl.dropboxusercontent.com/s/o6dnqzyhar647qu/gatos.mp4"
        ]

        # DO ACTION
        for index, url_video in enumerate(inputs):
            backend = detect_backend(url_video)

            # ASSERTS
            self.assertEqual(outputs[index], backend.get_url_parsed(url_video))
Example #42
0
    def save(self, *args, **kwargs):
        super(VideoLesson, self).save(*args, **kwargs)

        if not self.info:
            backend = detect_backend(self.video)

            if backend.backend == "VimeoBackend":
                info = backend.info
            elif backend.backend == "YoutubeBackend":
                entry = kwargs.get('entry', None)
                if entry:
                    info = self._generate_youtube_info(entry)
                else:
                    info = self._get_youtube_info(backend)
                info.update({"id": backend.code})

            info.update({"backend": backend.backend})
            info.update({"thumbnail": backend.thumbnail})
            self.info = info
            if not self.title:
                self.title = info['title']
            slug = "%s-%s" % (self.id, slugify(self.title))
            slug = slug[:-1] if slug[-1] == "-" else slug
            self.slug = slug
            if not self.duration:
                self.duration = info['duration']
            self.backend_source = backend.backend
            self.thumbnail = backend.thumbnail

            # Assign Meta content
            if not self.meta_description:
                if info['description']:
                    self.meta_description = info['description']
                else:
                    self.meta_description = info['title']

            if not self.meta_title:
                self.meta_title = info['title']

            self.save()
Example #43
0
    def get_backend(backend_or_url, context=None, **options):
        """
        Returns instance of VideoBackend. If context is passed to the method
        and request is secure, than the is_secure mark is set to backend.

        A string or VideoBackend instance can be passed to the method.

        :param backend: Given instance inherited from VideoBackend or url
        :type backend_or_url: VideoBackend | str
        :param context: Django template RequestContext
        :type context: django.template.RequestContext | None
        :rtype: VideoBackend
        """

        backend = (backend_or_url if isinstance(backend_or_url, VideoBackend)
                   else detect_backend(str(backend_or_url)))

        if context and "request" in context:
            backend.is_secure = context["request"].is_secure()
        if options:
            backend.set_options(options)

        return backend
Example #44
0
    def render(self,
               name,
               value="",
               attrs=None,
               size=(420, 315),
               renderer=None):
        """
        :type name: str
        :type attrs: dict
        """

        output = super().render(name, value, attrs, renderer)

        if not value:
            return output

        try:
            backend = detect_backend(value)
            return mark_safe(
                self.output_format.format(video=backend.get_embed_code(*size),
                                          input=output))
        except (UnknownBackendException, VideoDoesntExistException):
            return output
Example #45
0
 def url(self):
     if self.image:
         return self.image.url
     elif self.video_url:
         return detect_backend(self.video_url).url
Example #46
0
from embed_video.backends import VideoBackend
import re
from embed_video.backends import detect_backend

my_video = detect_backend('http://www.youtube.com/watch?v=H4tAOexHdR4')

class CustomBackend(VideoBackend):
    re_detect = re.compile(r'http://myvideo\.com/[0-9]+')
    re_code = re.compile(r'http://myvideo\.com/(?P<code>[0-9]+)')

    allow_https = False
    pattern_url = '{protocol}://play.myvideo.com/c/{code}/'
    pattern_thumbnail_url = '{protocol}://thumb.myvideo.com/c/{code}/'

    template_name = 'news/media.html'
Example #47
0
    def guide_video_thumbnail(self, guide):
        video = detect_backend(guide.video)  # TODO: Need to cache this. Costly query to vimeo's api
        # '100x75.jpg' '200x150.jpg' possible thumbnail sizing

        thumb_string = video.get_thumbnail_url()[:-7] + '100x75.jpg'
        return thumb_string
Example #48
0
 def test_detect(self):
     for url in self.urls:
         backend = detect_backend(url[0])
         self.assertIsInstance(backend, self.instance)
Example #49
0
 def thumbnail_url(self):
     try:
         backend = detect_backend(self.video)
         return backend.get_thumbnail_url()
     except UnknownBackendException:
         return ''
 def get_embed_video_thumbnail(self):
     be = detect_backend(self.video_url)
     return be.get_thumbnail_url()
 def setUp(self):
     self.backend = detect_backend('http://myvideo.com/1530')
Example #52
0
 def video(self):
     return detect_backend(self.video_url) if self.video_url else None