Exemplo n.º 1
0
 def render(self, data, media_type=None, renderer_context=None):
     if isinstance(data, SubtitleSet):
         return babelsubs.to(data, self.format)
     else:
         # Fall back to JSON renderer for other responses.  This handles
         # things like permissions errors and 404 errors
         return renderers.JSONRenderer().render(data)
Exemplo n.º 2
0
 def test_subtitles(self):
     # test the subtitles and sub_format fields
     self.context['sub_format'] = 'vtt'
     data = self.serializer.to_representation(self.version)
     assert_equal(data['subtitles'],
                  babelsubs.to(self.version.get_subtitles(), 'vtt'))
     assert_equal(data['sub_format'], 'vtt')
Exemplo n.º 3
0
def download(request, video_id, language_code, filename, format,
             version_number=None):

    video = get_object_or_404(Video, video_id=video_id)
    workflow = video.get_workflow()
    user = _user_for_download_permissions(request)
    if not workflow.user_can_view_video(user):
        raise PermissionDenied()

    language = video.subtitle_language(language_code)
    if language is None:
        raise PermissionDenied()

    public_only = workflow.user_can_view_private_subtitles(user,
                                                           language_code)
    version = language.version(public_only=not public_only,
                               version_number=version_number)

    if not version:
        raise Http404()
    if not format in babelsubs.get_available_formats():
        raise HttpResponseServerError("Format not found")

    subs_text = babelsubs.to(version.get_subtitles(), format,
                             language=version.language_code)
    # since this is a downlaod, we can afford not to escape tags, specially
    # true since speaker change is denoted by '>>' and that would get entirely
    # stripped out
    response = HttpResponse(subs_text, mimetype="text/plain")
    response['Content-Disposition'] = 'attachment'
    return response
Exemplo n.º 4
0
 def test_json_sub_format(self):
     # for the json sub_format, we should return actual JSON data, not a
     # that data encoded as a string
     self.context['sub_format'] = 'json'
     data = self.serializer.to_representation(self.version)
     json_encoding = babelsubs.to(self.version.get_subtitles(), 'json')
     assert_equal(data['subtitles'], json.loads(json_encoding))
Exemplo n.º 5
0
 def test_sub_format(self):
     subtitles = SubtitleSetFactory(num_subs=2)
     version = self.run_create({
         'sub_format': 'vtt',
         'subtitles': babelsubs.to(subtitles, 'vtt'),
     })
     assert_equal(version.get_subtitles(), subtitles)
Exemplo n.º 6
0
    def do_update_subtitles(self, video_url, language, tip):
        kaltura_id = video_url.get_video_type().kaltura_id()
        subtitles = tip.get_subtitles()
        sub_data = babelsubs.to(subtitles, 'srt')

        syncing.kaltura.update_subtitles(self.partner_id, self.secret,
                                         kaltura_id, language.language_code,
                                         sub_data)
Exemplo n.º 7
0
 def check_response_data(self, response, sub_format):
     subtitle_data = babelsubs.to(self.version.get_subtitles(), sub_format)
     if sub_format == 'json':
         subtitle_data = json.loads(subtitle_data)
     assert_equal(response.data['version_number'],
                  self.version.version_number)
     assert_equal(response.data['sub_format'], sub_format)
     assert_equal(response.data['subtitles'], subtitle_data)
     assert_equal(response.data['author'],
                  user_field_data(self.version.author))
     assert_equal(
         response.data['language'], {
             'code': self.version.language_code,
             'name': self.version.get_language_code_display(),
             'dir': 'ltr',
         })
     assert_equal(response.data['title'], self.version.title)
     assert_equal(response.data['description'], self.version.description)
     assert_equal(response.data['metadata'], {})
     assert_equal(response.data['video_title'], self.video.title_display())
     assert_equal(response.data['video_description'],
                  self.video.description)
     assert_equal(
         response.data['actions_uri'],
         reverse('api:subtitle-actions',
                 kwargs={
                     'video_id': self.video.video_id,
                     'language_code': self.version.language_code,
                 },
                 request=APIRequestFactory().get('/')))
     assert_equal(
         response.data['notes_uri'],
         reverse('api:subtitle-notes',
                 kwargs={
                     'video_id': self.video.video_id,
                     'language_code': self.version.language_code,
                 },
                 request=APIRequestFactory().get('/')))
     assert_equal(
         response.data['resource_uri'],
         reverse('api:subtitles',
                 kwargs={
                     'video_id': self.video.video_id,
                     'language_code': self.version.language_code,
                 },
                 request=APIRequestFactory().get('/')))
     assert_equal(
         response.data['site_uri'],
         reverse('videos:subtitleversion_detail',
                 kwargs={
                     'video_id': self.video.video_id,
                     'lang': self.version.language_code,
                     'lang_id': self.version.subtitle_language_id,
                     'version_id': self.version.id,
                 },
                 request=APIRequestFactory().get('/')))
Exemplo n.º 8
0
def _make_subtitle_cms_request(account_id,
                               client_id,
                               client_secret,
                               bc_video_id,
                               language_code,
                               subtitle_version=None):
    access_token = _get_cms_token(client_id, client_secret)
    authentication_header = {"Authorization": "Bearer " + access_token}
    r = requests.get(CMS_BASE_URL + "/accounts/" + account_id + "/videos/" +
                     bc_video_id,
                     headers=authentication_header)
    if r.status_code != 200:
        raise BrightcoveAPIError(
            "Error while retrieving Brightcove text tracks: %s" % r.text)
    tracks = json.loads(r.text)["text_tracks"]
    new_tracks = []
    for track in tracks:
        if language_code != track['srclang']:
            new_tracks.append(track)
    if len(tracks) != len(new_tracks):
        data_clean = {"text_tracks": new_tracks}
        r = requests.patch(CMS_BASE_URL + "/accounts/" + account_id +
                           "/videos/" + bc_video_id,
                           headers=authentication_header,
                           data=json.dumps(data_clean))
        if r.status_code != 200:
            raise BrightcoveAPIError(
                "Error while removing old Brightcove text track: %s" % r.text)
    if subtitle_version is not None:
        subtitle_data = babelsubs.to(subtitle_version.get_subtitles(),
                                     "vtt",
                                     language=subtitle_version.language_code)
        url = set_one_time_data(subtitle_data)
        label = subtitle_version.get_language_code_display()
        data = {
            "text_tracks": [{
                "url": url,
                "srclang": language_code,
                "kind": "captions",
                "label": label
            }]
        }
        r = requests.post(INGEST_BASE_URL + "/accounts/" + account_id +
                          "/videos/" + bc_video_id + "/ingest-requests",
                          headers=authentication_header,
                          data=json.dumps(data))
        if r.status_code != 200:
            raise BrightcoveAPIError(
                "Error while adding new Brightcove text track: %s" % r.text)
Exemplo n.º 9
0
def convert_subtitles(request):
    # FIXME: front end needs to send the DFXP for the subs
    data = {}
    errors = None
    if request.POST:
        if 'subtitles' and 'format' and 'language_code' in request.POST:

            subtitles = request.POST['subtitles']
            format = request.POST['format']
            available_formats = babelsubs.get_available_formats()
            if format not in available_formats:
                errors = {
                    "errors": {
                        'format':
                        'You must pass a suitable format. Available formats are %s'
                        % available_formats
                    }
                }
            subs = babelsubs.storage.SubtitleSet(
                initial_data=subtitles,
                language_code=request.POST.get('language_code'))
            # When we have newly serialized subtitles, put a stringified version of them
            # into this object. This object is what gets dumped into the textarea on the
            # front-end. If there are errors, also dump to result (the error would be displayed
            # to the user in the textarea.
            converted = babelsubs.to(subs, format)

            data['result'] = converted
        else:
            errors = {
                "errors": {
                    'subtitles': 'You need to send subtitles back',
                    'format': 'You must pass a suitable format',
                },
                'result': "Something went wrong, we're terribly sorry."
            }
    else:
        errors = {'result': "Must be a POST request"}
    res = json.dumps(errors or data)
    return HttpResponse(res, content_type='application/javascript')
Exemplo n.º 10
0
def update_subtitles(account, video_id, subtitle_version):
    headers = {"Authorization": ("Bearer " + account.access_token)}
    text_tracks = get_text_tracks(account, video_id)
    subtitles = subtitle_version.get_subtitles()
    encoded_subtitles = babelsubs.to(subtitles, 'vtt').encode('utf-8')
    language_code = convert_language_code(subtitle_version.language_code)
    if text_tracks is not None and 'data' in text_tracks:
        for track in text_tracks['data']:
            if track['language'] == language_code:
                delete_subtitles(account, video_id,
                                 subtitle_version.language_code)
    url = get_texttracks_url(video_id)
    data = {
        "type": "subtitles",
        "language": language_code,
        "name": subtitle_version.get_version_display()
    }
    response = requests.post(VIMEO_API_BASE_URL + url,
                             data=data,
                             headers=headers)
    if response.ok:
        content = response.json()
        if 'link' in content:
            response = requests.put(content['link'],
                                    data=encoded_subtitles,
                                    headers=headers)
            if not response.ok:
                raise APIError(response.text)
    else:
        error = response.json()
        error_text = response.json()['error']
        if 'invalid_parameters' in error:
            for field in error['invalid_parameters']:
                if 'field' in field and \
                   field['field'] == 'language':
                    error_text = "Language code not supported by Vimeo"
                    break
        raise APIError(error_text)
Exemplo n.º 11
0
def download(request,
             video_id,
             language_code,
             filename,
             format,
             version_number=None):

    video = get_object_or_404(Video, video_id=video_id)

    language = video.subtitle_language(language_code)
    if language is None:
        raise Http404

    team_video = video.get_team_video()

    if team_video and not team_video.team.user_is_member(request.user):
        # Non-members can only see public versions
        version = language.version(public_only=True,
                                   version_number=version_number)
    else:
        version = language.version(public_only=False,
                                   version_number=version_number)

    if not version:
        raise Http404
    if not format in babelsubs.get_available_formats():
        raise HttpResponseServerError("Format not found")

    subs_text = babelsubs.to(version.get_subtitles(),
                             format,
                             language=version.language_code)
    # since this is a downlaod, we can afford not to escape tags, specially
    # true since speaker change is denoted by '>>' and that would get entirely
    # stripped out
    response = HttpResponse(subs_text, mimetype="text/plain")
    response['Content-Disposition'] = 'attachment'
    return response
Exemplo n.º 12
0
 def test_kalturaaccount_update_subtitles(self, mock_update_subtitles):
     srt_data = babelsubs.to(self.version.get_subtitles(), 'srt')
     self.account.update_subtitles(self.video_url, self.language,
                                   self.version)
     mock_update_subtitles.assert_called_with(self.partner_id, self.secret,
                                              self.entry_id, 'en', srt_data)
Exemplo n.º 13
0
def _format_subs_for_youtube(subtitle_set):
    return babelsubs.to(subtitle_set, 'vtt').encode('utf-8')
Exemplo n.º 14
0
    def to(self, type):
        from babelsubs import to
        if isinstance(type, list):
            type = type[0]

        return to(self.to_internal(), type, language=self.language)
Exemplo n.º 15
0
 def test_raw_format_with_format_param(self):
     response = self.client.get(self.url + "?format=dfxp")
     assert_equal(response.content,
                  babelsubs.to(self.version.get_subtitles(), 'dfxp'))
Exemplo n.º 16
0
 def test_raw_format(self):
     # if we request a format like text/srt that's a subtile format, then
     # we should just return the subtitle data, nothing else
     response = self.client.get(self.url, HTTP_ACCEPT='text/srt')
     assert_equal(response.content,
                  babelsubs.to(self.version.get_subtitles(), 'srt'))
Exemplo n.º 17
0
    def to(self, type):
        from babelsubs import to
        if isinstance(type, list):
            type = type[0]

        return to(self.to_internal(), type, language=self.language)
Exemplo n.º 18
0
def download_subtitles(request, format):
    video_id = request.GET.get('video_id')
    lang_id = request.GET.get('lang_pk')
    revision = request.GET.get('revision', None)

    if not video_id:
        #if video_id == None, Video.objects.get raise exception. Better show 404
        #because video_id is required
        raise Http404

    video = get_object_or_404(models.Video, video_id=video_id)

    if not lang_id:
        # if no language is passed, assume it's the original one
        language = video.subtitle_language()
        if language is None:
            raise Http404
    else:
        try:
            language = video.newsubtitlelanguage_set.get(pk=lang_id)
        except ObjectDoesNotExist:
            raise Http404

    team_video = video.get_team_video()

    if not team_video:
        # Non-team videos don't require moderation
        version = language and language.version(public_only=False,
                                                version_number=revision)
    else:
        # Members can see all versions
        member = get_member(request.user, team_video.team)
        if member:
            version = language and language.version(public_only=False,
                                                    version_number=revision)
        else:
            version = language and language.version(version_number=revision)

    if not version:
        raise Http404
    if not format in babelsubs.get_available_formats():
        raise HttpResponseServerError("Format not found")

    subs_text = babelsubs.to(version.get_subtitles(),
                             format,
                             language=version.language_code)
    # since this is a downlaod, we can afford not to escape tags, specially true
    # since speaker change is denoted by '>>' and that would get entirely stripped out
    response = HttpResponse(subs_text, content_type="text/plain")
    original_filename = '%s.%s' % (video.lang_filename(
        language.language_code), format)

    if not 'HTTP_USER_AGENT' in request.META or u'WebKit' in request.META[
            'HTTP_USER_AGENT']:
        # Safari 3.0 and Chrome 2.0 accepts UTF-8 encoded string directly.
        filename_header = 'filename=%s' % original_filename.encode('utf-8')
    elif u'MSIE' in request.META['HTTP_USER_AGENT']:
        try:
            original_filename.encode('ascii')
        except UnicodeEncodeError:
            original_filename = 'subtitles.' + format

        filename_header = 'filename=%s' % original_filename
    else:
        # For others like Firefox, we follow RFC2231 (encoding extension in HTTP headers).
        filename_header = 'filename*=UTF-8\'\'%s' % iri_to_uri(
            original_filename.encode('utf-8'))

    response['Content-Disposition'] = 'attachment; ' + filename_header
    return response
Exemplo n.º 19
0
 def get_attribute(self, version):
     return babelsubs.to(version.get_subtitles(),
                         self.context['sub_format'])