Example #1
0
 def test_video_type_for_url(self):
     type = video_type_registrar.video_type_for_url('some url')
     self.assertEqual(type, None)
     type = video_type_registrar.video_type_for_url('http://youtube.com/v=UOtJUmiUZ08')
     self.assertTrue(isinstance(type, YoutubeVideoType))
     return
     self.assertRaises(VideoTypeError, video_type_registrar.video_type_for_url,
                       'http://youtube.com/v=100500')
Example #2
0
    def clean_video_url(self):
        video_url = self.cleaned_data['video_url']

        if video_url:
            try:
                video_type = video_type_registrar.video_type_for_url(video_url)
            except VideoTypeError, e:
                raise forms.ValidationError(e)
            if not video_type:
                for d in video_type_registrar.domains:
                    if d in video_url:
                        raise forms.ValidationError(
                            mark_safe(
                                _(u"""Please try again with a link to a video page.
                        <a href="mailto:%s">Contact us</a> if there's a problem."""
                                  ) % settings.FEEDBACK_EMAIL))

                raise forms.ValidationError(
                    mark_safe(
                        _(u"""You must link to a video on a compatible site (like YouTube) or directly to a
                    video file that works with HTML5 browsers. For example: http://mysite.com/myvideo.ogg or http://mysite.com/myipadvideo.m4v
                    <a href="mailto:%s">Contact us</a> if there's a problem."""
                          ) % settings.FEEDBACK_EMAIL))

            else:
                self._video_type = video_type
                # we need to use the cannonical url as the user provided might need
                # redirection (i.e. youtu.be/fdaf/), and django's validator will
                # choke on redirection (urllib2 for python2.6), see https://unisubs.sifterapp.com/projects/12298/issues/427646/comments
                video_url = video_type.video_url(video_type)

                if not url_exists(video_url):
                    raise forms.ValidationError(
                        _(u'This URL appears to be a broken link.'))
Example #3
0
def url_search_results(request):
    urls = []
    for url in request.GET['urls'].split():
        if not url:
            continue
        vt = video_type_registrar.video_type_for_url(url)
        if vt:
            urls.append(vt.convert_to_video_url())
    video_urls = list(
        VideoUrl.objects
        .filter(url__in=urls)
        .select_related('video', 'video__teamvideo')
    )
    found_urls = set(vurl.url for vurl in video_urls)
    not_found = [
        url for url in urls
        if url not in found_urls
    ]
    video_urls.sort(key=lambda vurl: urls.index(vurl.url))
    videos = [vurl.video for vurl in video_urls]
    return render(request, "future/videos/url-search-results.html", {
        'videos': videos,
        'not_found': not_found,
        'move_to_options': teams.permissions.can_move_videos_to(request.user),
    })
Example #4
0
    def clean_url(self):
        url = self.cleaned_data['url']

        try:
            video_type = video_type_registrar.video_type_for_url(url)
        except VideoTypeError, e:
            raise forms.ValidationError(e)
Example #5
0
def youtube_sync(video, language):
    """
    Used on debug page for video.

    Simplified version of what's found in
    ``ThirdPartyAccount.mirror_on_third_party``.  It doesn't bother checking if
    we should be syncing this or not.  Only does the new Youtube/Amara
    integration syncing.
    """
    version = language.get_tip()

    always_push_account = ThirdPartyAccount.objects.always_push_account()

    for vurl in video.videourl_set.all():
        vt = video_type_registrar.video_type_for_url(vurl.url)

        try:
            vt.update_subtitles(version, always_push_account)
            Meter('youtube.push.success').inc()
        except:
            Meter('youtube.push.fail').inc()
            logger.error('Always pushing to youtoube has failed.',
                         extra={
                             'video': video.video_id,
                             'vurl': vurl.pk
                         })
        finally:
            Meter('youtube.push.request').inc()
Example #6
0
    def clean_video_url(self):
        video_url = self.cleaned_data['video_url']
        
        if video_url:
            try:
                video_type = video_type_registrar.video_type_for_url(video_url)
            except VideoTypeError, e:
                raise forms.ValidationError(e)
            if not video_type:
                for d in video_type_registrar.domains:
                    if d in video_url:
                        raise forms.ValidationError(mark_safe(_(u"""Please try again with a link to a video page. 
                        <a href="mailto:%s">Contact us</a> if there's a problem.""") % settings.FEEDBACK_EMAIL))
                    
                raise forms.ValidationError(mark_safe(_(u"""You must link to a video on a compatible site (like YouTube) or directly to a
                    video file that works with HTML5 browsers. For example: http://mysite.com/myvideo.ogg or http://mysite.com/myipadvideo.m4v
                    <a href="mailto:%s">Contact us</a> if there's a problem.""") % settings.FEEDBACK_EMAIL))
                             
            else:
                self._video_type = video_type
                # we need to use the cannonical url as the user provided might need
                # redirection (i.e. youtu.be/fdaf/), and django's validator will
                # choke on redirection (urllib2 for python2.6), see https://unisubs.sifterapp.com/projects/12298/issues/427646/comments
                video_url = video_type.video_url(video_type)

                if not url_exists(video_url) :
                    raise forms.ValidationError(_(u'This URL appears to be a broken link.'))
Example #7
0
def _create_videos(video_data, users):
    videos = []

    for x in video_data:
        shuffle(users)
        video = Video(title=x['title'])
        video.save()
        if len(users) > 0:
            video.user = users[0]
        url = x['url'] + "&blah=%s" % time.time()
        vt = video_type_registrar.video_type_for_url(url)
        if vt is None:
            continue
        video_url, created = VideoUrl.objects.get_or_create(
            video=video, type=vt.abbreviation, url=url)
        video_url.original = True
        video_url.primary = True
        video_url.video = video
        video_url.save()
        # now we loop over languages:
        _add_langs_to_video(video, x['langs'])
        if len(x['langs']) > 0:
            video.is_subtitled = True
        video.save()
        videos.append(video)

    return videos
Example #8
0
    def clean_video_url(self):
        video_url = self.cleaned_data['video_url']

        if video_url:
            try:
                video_type = video_type_registrar.video_type_for_url(video_url)
            except VideoTypeError, e:
                raise forms.ValidationError(e)
            if not video_type:
                contact_link = fmt(
                    _('<a href="mailto:%(email)s">Contact us</a>'),
                    email=settings.FEEDBACK_EMAIL)
                for d in video_type_registrar.domains:
                    if d in video_url:
                        raise forms.ValidationError(mark_safe(fmt(
                            _(u"Please try again with a link to a video page.  "
                              "%(contact_link)s if there's a problem."),
                            contact_link=contact_link)))

                raise forms.ValidationError(mark_safe(fmt(
                    _(u"You must link to a video on a compatible site "
                      "(like YouTube) or directly to a video file that works "
                      "with HTML5 browsers. For example: "
                      "http://mysite.com/myvideo.ogg or "
                      "http://mysite.com/myipadvideo.m4v "
                      "%(contact_link)s if there's a problem"),
                    contact_link=contact_link)))

            else:
                self._video_type = video_type
                # we need to use the cannonical url as the user provided might need
                # redirection (i.e. youtu.be/fdaf/), and django's validator will
                # choke on redirection (urllib2 for python2.6), see https://unisubs.sifterapp.com/projects/12298/issues/427646/comments
                video_url = video_type.convert_to_video_url()
Example #9
0
 def clean_url(self):
     url = self.cleaned_data['url']
     
     try:
         video_type = video_type_registrar.video_type_for_url(url)
     except VideoTypeError, e:
         raise forms.ValidationError(e)
Example #10
0
def _create_videos(video_data, users):
    videos = []
    
    
    for x in video_data:
        shuffle(users)
        video = Video(title=x['title'])
        video.save()
        if len(users) > 0:
            video.user = users[0]
        url = x['url'] + "&blah=%s" % time.time()
        vt =  video_type_registrar.video_type_for_url(url)
        if vt is None:
            continue
        video_url, created  = VideoUrl.objects.get_or_create(video=video, type=vt.abbreviation, url=url)
        video_url.original = True
        video_url.primary = True
        video_url.video = video
        video_url.save()
         # now we loop over languages:
        _add_langs_to_video(video, x['langs'])
        if len(x['langs']) > 0:
            video.is_subtitled = True
        video.save()    
        videos.append(video)
       
   
    return videos
Example #11
0
    def clean_video_url(self):
        video_url = self.cleaned_data['video_url']

        if video_url:
            try:
                video_type = video_type_registrar.video_type_for_url(video_url)
            except VideoTypeError, e:
                raise forms.ValidationError(e)
            if not video_type:
                for d in video_type_registrar.domains:
                    if d in video_url:
                        raise forms.ValidationError(
                            mark_safe(
                                _(u"""Please try again with a link to a video page. 
                        <a href="mailto:%s">Contact us</a> if there's a problem."""
                                  ) % settings.FEEDBACK_EMAIL))

                raise forms.ValidationError(
                    mark_safe(
                        _(u"""You must link to a video on a compatible site (like YouTube) or directly to a
                    video file that works with HTML5 browsers. For example: http://mysite.com/myvideo.ogg or http://mysite.com/myipadvideo.m4v
                    <a href="mailto:%s">Contact us</a> if there's a problem."""
                          ) % settings.FEEDBACK_EMAIL))

            else:
                self._video_type = video_type
Example #12
0
 def _save_alternate_url(self, video, video_url):
     video_type = video_type_registrar.video_type_for_url(video_url)
     video_url_obj, created = VideoUrl.objects.get_or_create(
         url=video_type.convert_to_video_url(),
         defaults=dict(type=video_type.abbreviation,
                       original=True,
                       primary=False,
                       video=video))
Example #13
0
 def get_video_type(self, entry):
     try:
         for mk in entry['media_content']:
             vt = video_type_registrar.video_type_for_url(mk['url'])
             if vt:
                 return vt
     except (KeyError, IndexError):
         pass
Example #14
0
    def clean(self, video_url):
        if not video_url:
            return None

        try:
            video_type = video_type_registrar.video_type_for_url(video_url)
        except VideoTypeError, e:
            raise forms.ValidationError(e)
Example #15
0
 def try_save_link(self, link):
     try:
         video_type = video_type_registrar.video_type_for_url(link)
         if video_type:
             Video.get_or_create_for_url(vt=video_type, user=self.user)
             return True
     except VideoTypeError, e:
         pass
Example #16
0
 def try_save_link(self, link):
     try:
         video_type = video_type_registrar.video_type_for_url(link)
         if video_type:
             Video.get_or_create_for_url(vt=video_type, user=self.user)
             return True
     except VideoTypeError, e:
         pass
Example #17
0
 def get_video_type(self, entry):
     try:
         for mk in entry['media_content']:
             vt = video_type_registrar.video_type_for_url(mk['url'])
             if vt:
                 return vt
     except (KeyError, IndexError):
         pass
Example #18
0
def write_video_type_js(video):
    if not video or not bool(video.get_video_url()):
        return
    try:
        vt = video_type_registrar.video_type_for_url(video.get_video_url())
        if hasattr(vt, "js_url"):
            return '<script type="text/javascript" src="%s"><script/>' % vt.js_url
    except VideoTypeError:
        return
Example #19
0
def write_video_type_js(video):
    if not video or not bool(video.get_video_url()):
        return 
    try:
        vt = video_type_registrar.video_type_for_url(video.get_video_url())
        if hasattr(vt, "js_url"):
            return '<script type="text/javascript" src="%s"><script/>' % vt.js_url
    except VideoTypeError:    
        return  
Example #20
0
 def clean(self, video_url):
     if not video_url:
         if self.required:
             raise forms.ValidationError(self.error_messages['required'])
         return None
     try:
         video_type = video_type_registrar.video_type_for_url(video_url)
     except VideoTypeError, e:
         raise forms.ValidationError(e)
Example #21
0
    def clean(self, value):
        self.vt = None
        self.video = None

        super(UniSubBoundVideoField, self).clean(value)

        video_url = value

        if not video_url:
            return video_url

        host = Site.objects.get_current().domain
        url_start = 'http://' + host

        if video_url.startswith(url_start):
            # UniSub URL
            locale, path = strip_path(video_url[len(url_start):])
            video_url = url_start + path
            try:
                video_url = self.format_url(video_url)
                func, args, kwargs = resolve(video_url.replace(url_start, ''))

                if not 'video_id' in kwargs:
                    raise forms.ValidationError(
                        _('This URL does not contain video id.'))

                try:
                    self.video = Video.objects.get(video_id=kwargs['video_id'])
                except Video.DoesNotExist:
                    raise forms.ValidationError(_('Videos does not exist.'))

            except Http404:
                raise forms.ValidationError(_('Incorrect URL.'))
        else:
            # URL from other site
            try:
                self.vt = video_type_registrar.video_type_for_url(video_url)

                if hasattr(self, 'user'):
                    user = self.user
                else:
                    user = None

                if self.vt:
                    self.video, created = Video.get_or_create_for_url(
                        vt=self.vt, user=user)
            except VideoTypeError, e:
                self.video = None
                raise forms.ValidationError(e)

            if not self.video:
                raise forms.ValidationError(
                    mark_safe(
                        _(u"""Universal Subtitles does not support that website or video format.
If you'd like to us to add support for a new site or format, or if you
think there's been some mistake, <a
href="mailto:%s">contact us</a>!""") % settings.FEEDBACK_EMAIL))
Example #22
0
 def _save_alternate_url(self, video, video_url):
     video_type = video_type_registrar.video_type_for_url(video_url)
     video_url_obj, created = VideoUrl.objects.get_or_create(
         url=video_type.convert_to_video_url(),
         defaults=dict(
             type=video_type.abbreviation,
             original=True,
             primary=False,
             video=video))
Example #23
0
    def get_editor_data(self):
        editor_data = {
            'canSync': bool(self.request.GET.get('canSync', True)),
            'canAddAndRemove': bool(self.request.GET.get('canAddAndRemove', True)),
            # front end needs this to be able to set the correct
            # api headers for saving subs
            'authHeaders': {
                'x-api-username': self.request.user.username,
                'x-apikey': self.request.user.get_api_key()
            },
            'username': self.request.user.username,
            'user_fullname': unicode(self.request.user),
            'video': {
                'id': self.video.video_id,
                'title': self.video.title,
                'description': self.video.description,
                'duration': self.video.duration,
                'primaryVideoURLType': video_type_registrar.video_type_for_url(self.video.get_video_url()).abbreviation,
                'videoURLs': self.get_video_urls(),
                'metadata': self.video.get_metadata(),
            },
            'editingVersion': {
                'languageCode': self.editing_language.language_code,
                'versionNumber': (self.editing_version.version_number
                                  if self.editing_version else None),
            },
            'baseLanguage': self.base_language,
            'languages': [self.editor_data_for_language(lang)
                          for lang in self.languages],
            'languageCode': self.request.LANGUAGE_CODE,
            'oldEditorURL': reverse('subtitles:old-editor', kwargs={
                'video_id': self.video.video_id,
                'language_code': self.editing_language.language_code,
            }),
            'playbackModes': self.get_editor_data_for_playback_modes(),
            'preferences': {
                'showTutorial': self.request.user.show_tutorial,
                'playbackModeId': self.request.user.playback_mode
            },
            'staticURL': settings.STATIC_URL,
            'notesHeading': 'Editor Notes',
            'notesEnabled': True,
            'redirectUrl': self.get_redirect_url(),
            'customCss': self.get_custom_css(),
        }

        editor_data.update(self.workflow.editor_data(
            self.user, self.language_code))

        team_attributes = self.get_team_editor_data()
        if team_attributes:
            editor_data['teamAttributes'] = team_attributes

        return editor_data
Example #24
0
    def create(self, validated_data):
        vt = video_type_registrar.video_type_for_url(validated_data['url'])

        new_url = self.context['video'].videourl_set.create(
            url=validated_data['url'],
            original=validated_data.get('original', False),
            type=vt.abbreviation,
            added_by=self.context['user'],
        )
        if validated_data.get('primary'):
            new_url.make_primary(self.context['user'])
        return new_url
Example #25
0
 def get_video_type(self, entry):
     if 'links' not in entry:
         return
     
     for link in entry['links']:
         try:
             if link['type'].startswith('video'):
                 vt = video_type_registrar.video_type_for_url(link['href'])
                 if vt:
                     return vt                    
         except (KeyError, IndexError, AttributeError):
             pass
Example #26
0
    def clean(self, value):
        self.vt = None
        self.video = None

        super(UniSubBoundVideoField, self).clean(value)

        video_url = value

        if not video_url:
            return video_url

        host = Site.objects.get_current().domain
        url_start = 'http://'+host

        if video_url.startswith(url_start):
            # UniSub URL
            locale, path = strip_path(video_url[len(url_start):])
            video_url = url_start+path
            try:
                video_url = self.format_url(video_url)
                func, args, kwargs = resolve(video_url.replace(url_start, ''))

                if not 'video_id' in kwargs:
                    raise forms.ValidationError(_('This URL does not contain video id.'))

                try:
                    self.video = Video.objects.get(video_id=kwargs['video_id'])
                except Video.DoesNotExist:
                    raise forms.ValidationError(_('Videos does not exist.'))

            except Http404:
                raise forms.ValidationError(_('Incorrect URL.'))
        else:
            # URL from other site
            try:
                self.vt = video_type_registrar.video_type_for_url(video_url)

                if hasattr(self, 'user'):
                    user = self.user
                else:
                    user = None

                if self.vt:
                    self.video, created = Video.get_or_create_for_url(vt=self.vt, user=user)
            except VideoTypeError, e:
                self.video = None
                raise forms.ValidationError(e)

            if not self.video:
                raise forms.ValidationError(mark_safe(_(u"""Universal Subtitles does not support that website or video format.
If you'd like to us to add support for a new site or format, or if you
think there's been some mistake, <a
href="mailto:%s">contact us</a>!""") % settings.FEEDBACK_EMAIL))
Example #27
0
    def get_video_type(self, entry):
        if 'links' not in entry:
            return

        for link in entry['links']:
            try:
                if link['type'].startswith('video'):
                    vt = video_type_registrar.video_type_for_url(link['href'])
                    if vt:
                        return vt
            except (KeyError, IndexError, AttributeError):
                pass
Example #28
0
def associate_extra_url(video_url, video_id):
    cache_key = _video_id_key(video_url)
    value = cache.get(cache_key)
    if value is None:
        from videos.models import VideoUrl, Video

        vt = video_type_registrar.video_type_for_url(video_url)
        video_url, created = VideoUrl.objects.get_or_create(
            url=vt.convert_to_video_url(),
            defaults={"video": Video.objects.get(video_id=video_id), "type": vt.abbreviation, "videoid": video_id},
        )
        cache.set(cache_key, video_url.videoid, TIMEOUT)
Example #29
0
    def clean_url(self):
        url = self.cleaned_data['url']
        
        try:
            video_type = video_type_registrar.video_type_for_url(url)

            video_url = video_type.video_url(video_type)

            if not url_exists(video_url) :
                raise forms.ValidationError(_(u'This URL appears to be a broken link.'))

        except VideoTypeError, e:
            raise forms.ValidationError(e)
Example #30
0
def associate_extra_url(video_url, video_id):
    cache_key = _video_id_key(video_url)
    value = cache.get(cache_key)
    if value is None:
        from videos.models import VideoUrl, Video
        vt = video_type_registrar.video_type_for_url(video_url)
        video_url, created = VideoUrl.objects.get_or_create(
            url=vt.convert_to_video_url(),
            defaults={
                'video': Video.objects.get(video_id=video_id),
                'type': vt.abbreviation,
                'videoid': video_id })
        cache.set(cache_key, video_url.videoid, TIMEOUT)
Example #31
0
 def get_queryset(self):
     query_params = self.request.query_params
     if 'team' not in query_params:
         qs = self.get_videos_for_user()
     else:
         qs = self.get_videos_for_team(query_params)
     if 'video_url' in query_params:
         vt = video_type_registrar.video_type_for_url(
             query_params['video_url'])
         if vt:
             qs = qs.filter(videourl__url=vt.convert_to_video_url())
         else:
             qs = qs.filter(videourl__url=query_params['video_url'])
     return qs
Example #32
0
 def get_queryset(self):
     query_params = self.request.query_params
     if 'team' not in query_params and 'video_url' not in query_params:
         return Video.objects.public().order_by('-id')[:20]
     if 'team' not in query_params:
         qs = self.get_videos_for_user()
     else:
         qs = self.get_videos_for_team(query_params)
     if 'video_url' in query_params:
         vt = video_type_registrar.video_type_for_url(query_params['video_url'])
         if vt:
             qs = qs.filter(videourl__url=vt.convert_to_video_url())
         else:
             qs = qs.filter(videourl__url=query_params['video_url'])
     return qs
Example #33
0
def _add_amara_description_credit_to_youtube_vurl(vurl_pk):
    from accountlinker.models import ThirdPartyAccount

    try:
        vurl = VideoUrl.objects.get(pk=vurl_pk)
    except VideoUrl.DoesNotExist:
        celery_logger.error("vurl not found", extra={'vurl_pk': vurl_pk})
        return

    try:
        vt = video_type_registrar.video_type_for_url(vurl.url)
    except VideoTypeError, e:
        celery_logger.warning("Video type error",
                              extra={"exception_thrown": str(e)})
        return
Example #34
0
 def show_widget(self, request, video_url, is_remote, base_state=None):
     return_value = {
         'video_id' : 'abc',
         'writelock_expiration' : models.WRITELOCK_EXPIRATION,
         'embed_version': settings.EMBED_JS_VERSION,
         'languages': LANGUAGES,
         'metadata_languages': settings.METADATA_LANGUAGES
         }
     if request.user.is_authenticated():
         return_value['username'] = request.user.username
     video_type = video_type_registrar.video_type_for_url(video_url)
     video_urls = [video_url]
     return_value['video_urls'] = video_urls
     return_value['drop_down_contents'] = []
     return_value['my_languages'] = ['en'];
     return return_value
Example #35
0
    def _test_urls(self, urls):
        for url in urls:
            form = VideoForm(data={"video_url":url})
            self.assertTrue(form.is_valid())
            video = form.save()
            video_type = video_type_registrar.video_type_for_url(url)
            # double check we never confuse video_id with video.id with videoid, sigh
            model_url = video.get_video_url()
            if hasattr(video_type, "videoid"):
                self.assertTrue(video_type.videoid  in model_url)
            # check the pk is never on any of the urls parts
            for part in model_url.split("/"):
                self.assertTrue(str(video.pk)  != part)
            self.assertTrue(video.video_id  not in model_url)

            self.assertTrue(Video.objects.filter(videourl__url=model_url).exists())
Example #36
0
 def show_widget(self, request, video_url, is_remote, base_state=None):
     return_value = {
         'video_id' : 'abc',
         'writelock_expiration' : models.WRITELOCK_EXPIRATION,
         'embed_version': settings.EMBED_JS_VERSION,
         'languages': LANGUAGES,
         'metadata_languages': settings.METADATA_LANGUAGES
         }
     if request.user.is_authenticated():
         return_value['username'] = request.user.username
     video_type = video_type_registrar.video_type_for_url(video_url)
     if isinstance(video_type, BlipTvVideoType):
         video_urls = video_type.scrape_best_file_url()
     else:
         video_urls = [video_url]
     return_value['video_urls'] = video_urls
     return_value['drop_down_contents'] = []
     return return_value
Example #37
0
 def show_widget(self, request, video_url, is_remote, base_state=None):
     return_value = {
         "video_id": "abc",
         "writelock_expiration": models.WRITELOCK_EXPIRATION,
         "embed_version": settings.EMBED_JS_VERSION,
         "languages": LANGUAGES,
         "metadata_languages": settings.METADATA_LANGUAGES,
     }
     if request.user.is_authenticated():
         return_value["username"] = request.user.username
     video_type = video_type_registrar.video_type_for_url(video_url)
     if isinstance(video_type, BlipTvVideoType):
         video_urls = video_type.scrape_best_file_url()
     else:
         video_urls = [video_url]
     return_value["video_urls"] = video_urls
     return_value["drop_down_contents"] = self._drop_down_contents(None)
     return return_value
Example #38
0
    def get_or_create_for_url(cls, video_url=None, vt=None, user=None):
        vt = vt or video_type_registrar.video_type_for_url(video_url)
        if not vt:
            return None, False

        try:
            video_url_obj = VideoUrl.objects.get(
                url=vt.convert_to_video_url())
            return video_url_obj.video, False
        except models.ObjectDoesNotExist:
            pass
        
        try:
            video_url_obj = VideoUrl.objects.get(
                type=vt.abbreviation, **vt.create_kwars())
            if user:
                Action.create_video_handler(video_url_obj.video, user)
            return video_url_obj.video, False
        except models.ObjectDoesNotExist:
            obj = Video()
            obj = vt.set_values(obj)
            if obj.title:
                obj.slug = slugify(obj.title)
            obj.user = user
            obj.save()
            
            user and obj.followers.add(user)
            
            Action.create_video_handler(obj, user)
            
            SubtitleLanguage(video=obj, is_original=True, is_forked=True).save()
            #Save video url
            video_url_obj = VideoUrl()
            if vt.video_id:
                video_url_obj.videoid = vt.video_id
            video_url_obj.url = vt.convert_to_video_url()
            video_url_obj.type = vt.abbreviation
            video_url_obj.original = True
            video_url_obj.primary = True
            video_url_obj.added_by = user
            video_url_obj.video = obj
            video_url_obj.save()
            
            return obj, True
Example #39
0
    def get_or_create_for_url(cls, video_url=None, vt=None, user=None):
        vt = vt or video_type_registrar.video_type_for_url(video_url)
        if not vt:
            return None, False

        try:
            video_url_obj = VideoUrl.objects.get(url=vt.convert_to_video_url())
            return video_url_obj.video, False
        except models.ObjectDoesNotExist:
            pass

        try:
            video_url_obj = VideoUrl.objects.get(type=vt.abbreviation,
                                                 **vt.create_kwars())
            if user:
                Action.create_video_handler(video_url_obj.video, user)
            return video_url_obj.video, False
        except models.ObjectDoesNotExist:
            obj = Video()
            obj = vt.set_values(obj)
            if obj.title:
                obj.slug = slugify(obj.title)
            obj.user = user
            obj.save()

            user and obj.followers.add(user)

            Action.create_video_handler(obj, user)

            SubtitleLanguage(video=obj, is_original=True,
                             is_forked=True).save()
            #Save video url
            video_url_obj = VideoUrl()
            if vt.video_id:
                video_url_obj.videoid = vt.video_id
            video_url_obj.url = vt.convert_to_video_url()
            video_url_obj.type = vt.abbreviation
            video_url_obj.original = True
            video_url_obj.primary = True
            video_url_obj.added_by = user
            video_url_obj.video = obj
            video_url_obj.save()

            return obj, True
Example #40
0
 def get_queryset(self):
     query_params = self.request.query_params
     if 'team' not in query_params and 'video_url' not in query_params:
         return Video.objects.public().order_by('-id')[:20]
     if 'team' not in query_params:
         qs = self.get_videos_for_user()
     else:
         qs = self.get_videos_for_team(query_params)
     if isinstance(qs, EmptyQuerySet):
         # If the method returned Videos.none(), then stop now rather than
         # call for_url() (#3049)
         return qs
     if 'video_url' in query_params:
         vt = video_type_registrar.video_type_for_url(
             query_params['video_url'])
         if vt:
             qs = qs.for_url(vt.convert_to_video_url())
         else:
             qs = qs.for_url(query_params['video_url'])
     return qs
Example #41
0
 def clean_video_url(self):
     video_url = self.cleaned_data['video_url']
     
     if video_url:
         try:
             video_type = video_type_registrar.video_type_for_url(video_url)
         except VideoTypeError, e:
             raise forms.ValidationError(e)
         if not video_type:
             for d in video_type_registrar.domains:
                 if d in video_url:
                     raise forms.ValidationError(mark_safe(_(u"""Please try again with a link to a video page. 
                     <a href="mailto:%s">Contact us</a> if there's a problem.""") % settings.FEEDBACK_EMAIL))
                 
             raise forms.ValidationError(mark_safe(_(u"""You must link to a video on a compatible site (like YouTube) or directly to a
                 video file that works with HTML5 browsers. For example: http://mysite.com/myvideo.ogg or http://mysite.com/myipadvideo.m4v
                 <a href="mailto:%s">Contact us</a> if there's a problem.""") % settings.FEEDBACK_EMAIL))
                          
         else:
             self._video_type = video_type
Example #42
0
 def get_video_type(self, entry):
     try:
         return video_type_registrar.video_type_for_url(
             entry['videodownload'])
     except KeyError:
         pass
Example #43
0
def add_team_videos(team_pk, user_pk, videos):
    from .permissions import can_add_videos_bulk
    from teams.models import Team, Project, TeamVideo
    from videos.models import Video
    from videos.types import video_type_registrar
    from auth.models import CustomUser as User
    from utils.subtitles import load_subtitles
    from subtitles.pipeline import add_subtitles
    user = User.objects.get(pk=int(user_pk))
    team = Team.objects.get(pk=int(team_pk))
    num_successful_videos = 0
    messages = []
    if can_add_videos_bulk(user):
        for video_item in videos:
            video_url = video_item['url']
            try:
                video_type = video_type_registrar.video_type_for_url(video_url)
                video_url = video_type.convert_to_video_url()
            except:
                messages.append(
                    fmt(_(u"Unknown video type: %(url)s\n"), url=video_url))
                continue

            def setup_video(video, video_url):
                video.is_public = team.videos_public()
                if video_item.get('title'):
                    video.title = video_item['title']
                if video_item.get('description'):
                    video.description = video_item['description']
                if video_item.get('language'):
                    language = video_item['language'].lower()
                    if language in SUPPORTED_LANGUAGE_CODES:
                        video.primary_audio_language_code = language
                    else:
                        messages.append(
                            fmt(_(
                                u"Badly formated language for %(url)s: %(language)s, ignoring it."
                            ),
                                url=video_url,
                                language=video_item['language']))
                if video_item.get('duration') and not video.duration:
                    try:
                        video.duration = int(video_item['duration'])
                    except:
                        messages.append(
                            fmt(_(
                                u"Badly formated duration for %(url)s: %(duration)s, ignoring it."
                            ),
                                url=video_url,
                                duration=video_item['duration']))
                if video_item.get('project'):
                    project, created = Project.objects.get_or_create(
                        team=team,
                        slug=pan_slugify(video_item['project']),
                        defaults={'name': video_item['project']})
                else:
                    project = team.default_project
                team_video = TeamVideo.objects.create(video=video,
                                                      team=team,
                                                      project=project,
                                                      added_by=user)

            try:
                video, video_url = Video.add(video_type, user, setup_video,
                                             team)
            except Video.DuplicateUrlError, e:
                messages.append(
                    fmt(_(u"Video is already added to team: %(url)s\n"),
                        url=e.video_url))
                continue

            if 'transcript' in video_item and len(
                    video_item['transcript']
            ) > 0 and video.primary_audio_language_code:
                try:
                    sub_type = video_item['transcript'].split(".")[-1]
                    r = requests.get(video_item['transcript'])
                    if r.ok:
                        subs = load_subtitles(
                            video.primary_audio_language_code, r.text,
                            sub_type)
                        version = add_subtitles(
                            video, video.primary_audio_language_code, subs)
                    else:
                        raise Exception("Request not successful")
                except Exception, e:
                    logger.error(
                        "Error while importing transcript file: {}".format(
                            str(e)))
                    messages.append(
                        fmt(_(
                            u"Invalid transcript file or language code for video %(url)s\n"
                        ),
                            url=video_url))
            num_successful_videos += 1
Example #44
0
 def try_get_video_type(self, link):
     try:
         video_type = video_type_registrar.video_type_for_url(link)
     except VideoTypeError, e:
         raise forms.ValidationError(e)
Example #45
0
def add_team_videos(team_pk, user_pk, videos):
    from .permissions import can_add_videos_bulk
    from teams.models import Team, Project, TeamVideo
    from videos.models import Video
    from videos.types import video_type_registrar
    from auth.models import CustomUser as User
    from utils.subtitles import load_subtitles
    from subtitles.pipeline import add_subtitles
    user = User.objects.get(pk=int(user_pk))
    team = Team.objects.get(pk=int(team_pk))
    num_successful_videos = 0
    messages = []
    if can_add_videos_bulk(user):
        for video_item in videos:
            video_url = video_item['url']
            try:
                video_type = video_type_registrar.video_type_for_url(video_url)
                video_url = video_type.convert_to_video_url()
            except:
                messages.append(
                    fmt(_(u"Unknown video type: %(url)s\n"), url=video_url))
                continue
            title = u""
            description = u""
            if len(video_item['description']) > 0:
                description = video_item['description']
            set_values = {'is_public': team.is_visible}
            if len(video_item['title']) > 0:
                set_values['title'] = video_item['title']
            if len(video_item['description']) > 0:
                set_values['description'] = video_item['description']
            video, created = Video.get_or_create_for_url(video_url,
                                                         video_type,
                                                         user,
                                                         set_values=set_values,
                                                         in_task=True)
            if not created and video.get_team_video() is not None:
                messages.append(
                    fmt(_(u"Video is already part of a team: %(url)s\n"),
                        url=video_url))
                continue
            modified_video = False
            if not created:
                video.is_public = team.is_visible
                video.title = video_item['title']
                video.description = video_item['description']
                modified_video = True
            if 'language' in video_item and len(video_item['language']) > 0:
                language = video_item['language'].lower()
                if language in LANGUAGE_CHOICES:
                    video.primary_audio_language_code = language
                    modified_video = True
                else:
                    messages.append(
                        fmt(_(
                            u"Badly formated language for %(url)s: %(language)s, ignoring it."
                        ),
                            url=video_url,
                            language=video_item['language']))
            if 'duration' in video_item and len(video_item['duration']) > 0:
                try:
                    video.duration = int(video_item['duration'])
                    modified_video = True
                except:
                    messages.append(
                        fmt(_(
                            u"Badly formated duration for %(url)s: %(duration)s, ignoring it."
                        ),
                            url=video_url,
                            duration=video_item['duration']))
            if modified_video:
                video.save()
            if 'transcript' in video_item and len(
                    video_item['transcript']
            ) > 0 and video.primary_audio_language_code:
                try:
                    sub_type = video_item['transcript'].split(".")[-1]
                    r = requests.get(video_item['transcript'])
                    if r.ok:
                        subs = load_subtitles(
                            video.primary_audio_language_code, r.text,
                            sub_type)
                        version = add_subtitles(
                            video, video.primary_audio_language_code, subs)
                    else:
                        raise Exception("Request not successful")
                except Exception, e:
                    logger.error(
                        "Error while importing transcript file: {}".format(
                            str(e)))
                    messages.append(
                        fmt(_(
                            u"Invalid transcript file or language code for video %(url)s\n"
                        ),
                            url=video_url))
            if created:
                num_successful_videos += 1
            if 'project' in video_item and len(video_item['project']) > 0:
                project, created = Project.objects.get_or_create(
                    team=team,
                    slug=pan_slugify(video_item['project']),
                    defaults={'name': video_item['project']})
                project_id = project.id
            else:
                project_id = None
            team_video = TeamVideo.objects.create(video=video,
                                                  team=team,
                                                  project_id=project_id)
Example #46
0
 def test_video_type_for_url(self):
     type = video_type_registrar.video_type_for_url('some url')
     self.assertEqual(type, None)
     type = video_type_registrar.video_type_for_url('http://youtube.com/v=UOtJUmiUZ08')
     self.assertTrue(isinstance(type, YoutubeVideoType))
     self.assertRaises(VideoTypeError, video_type_registrar.video_type_for_url, 'http://youtube.com/v=100500')
Example #47
0
 def get_video_type(self, entry):
     try:
         return video_type_registrar.video_type_for_url(entry['videodownload'])
     except KeyError:
         pass