예제 #1
0
def rename_transcripts(request):
    """
    Create copies of existing subtitles with new names of HTML5 sources.

    Old subtitles are not deleted now, because we do not have rollback functionality.

    If succeed, Item.sub will be chosen randomly from html5 video sources provided by front-end.
    """
    response = {'status': 'Error', 'subs': ''}

    try:
        __, videos, item = _validate_transcripts_data(request)
    except TranscriptsRequestValidationException as e:
        return error_response(response, e.message)

    old_name = item.sub

    for new_name in videos['html5'].keys():  # copy subtitles for every HTML5 source
        try:
            # updates item.sub with new_name if it is successful.
            copy_or_rename_transcript(new_name, old_name, item, user=request.user)
        except NotFoundError:
            # subtitles file `item.sub` is not presented in the system. Nothing to copy or rename.
            error_response(response, "Can't find transcripts in storage for {}".format(old_name))

    response['status'] = 'Success'
    response['subs'] = item.sub  # item.sub has been changed, it is not equal to old_name.
    log.debug("Updated item.sub to %s", item.sub)
    return JsonResponse(response)
예제 #2
0
 def test_save_unicode_filename(self):
     # Mock a video item
     item = Mock(location=Mock(course_key=self.course.id))
     transcripts_utils.save_subs_to_store(self.subs, self.subs_id,
                                          self.course)
     transcripts_utils.copy_or_rename_transcript(self.subs_copied_id,
                                                 self.subs_id, item)
     self.assertTrue(contentstore().find(self.content_copied_location))
예제 #3
0
def upload_transcripts(request):
    """
    Upload transcripts for current module.

    returns: response dict::

        status: 'Success' and HTTP 200 or 'Error' and HTTP 400.
        subs: Value of uploaded and saved html5 sub field in video item.
    """
    response = {
        'status': 'Unknown server error',
        'subs': '',
    }

    locator = request.POST.get('locator')
    if not locator:
        return error_response(response, 'POST data without "locator" form data.')

    try:
        item = _get_item(request, request.POST)
    except (ItemNotFoundError, InvalidLocationError, InsufficientSpecificationError):
        return error_response(response, "Can't find item by locator.")

    if 'file' not in request.FILES:
        return error_response(response, 'POST data without "file" form data.')

    video_list = request.POST.get('video_list')
    if not video_list:
        return error_response(response, 'POST data without video names.')

    try:
        video_list = json.loads(video_list)
    except ValueError:
        return error_response(response, 'Invalid video_list JSON.')

    source_subs_filedata = request.FILES['file'].read().decode('utf8')
    source_subs_filename = request.FILES['file'].name

    if '.' not in source_subs_filename:
        return error_response(response, "Undefined file extension.")

    basename = os.path.basename(source_subs_filename)
    source_subs_name = os.path.splitext(basename)[0]
    source_subs_ext = os.path.splitext(basename)[1][1:]

    if item.category != 'video':
        return error_response(response, 'Transcripts are supported only for "video" modules.')

    # Allow upload only if any video link is presented
    if video_list:
        sub_attr = source_subs_name

        try:  # Generate and save for 1.0 speed, will create subs_sub_attr.srt.sjson subtitles file in storage.
            generate_subs_from_source({1: sub_attr}, source_subs_ext, source_subs_filedata, item)
        except TranscriptsGenerationException as e:
            return error_response(response, e.message)
        statuses = {}
        for video_dict in video_list:
            video_name = video_dict['video']
            # We are creating transcripts for every video source,
            # for the case that in future, some of video sources can be deleted.
            statuses[video_name] = copy_or_rename_transcript(video_name, sub_attr, item, user=request.user)
            try:
                # updates item.sub with `video_name` if it is successful.
                copy_or_rename_transcript(video_name, sub_attr, item, user=request.user)
                selected_name = video_name  # name to write to item.sub field, chosen at random.
            except NotFoundError:
                # subtitles file `sub_attr` is not presented in the system. Nothing to copy or rename.
                return error_response(response, "Can't find transcripts in storage for {}".format(sub_attr))

        item.sub = selected_name  # write one of  new subtitles names to item.sub attribute.
        item.save_with_metadata(request.user)
        response['subs'] = item.sub
        response['status'] = 'Success'
    else:
        return error_response(response, 'Empty video sources.')

    return JsonResponse(response)
예제 #4
0
def upload_transcripts(request):
    """
    Upload transcripts for current module.

    returns: response dict::

        status: 'Success' and HTTP 200 or 'Error' and HTTP 400.
        subs: Value of uploaded and saved html5 sub field in video item.
    """
    response = {
        'status': 'Unknown server error',
        'subs': '',
    }

    locator = request.POST.get('locator')
    if not locator:
        return error_response(response,
                              'POST data without "locator" form data.')

    try:
        item = _get_item(request, request.POST)
    except (InvalidKeyError, ItemNotFoundError):
        return error_response(response, "Can't find item by locator.")

    if 'transcript-file' not in request.FILES:
        return error_response(response, 'POST data without "file" form data.')

    video_list = request.POST.get('video_list')
    if not video_list:
        return error_response(response, 'POST data without video names.')

    try:
        video_list = json.loads(video_list)
    except ValueError:
        return error_response(response, 'Invalid video_list JSON.')

    source_subs_filedata = request.FILES['transcript-file'].read().decode(
        'utf8')
    source_subs_filename = request.FILES['transcript-file'].name

    if '.' not in source_subs_filename:
        return error_response(response, "Undefined file extension.")

    basename = os.path.basename(source_subs_filename)
    source_subs_name = os.path.splitext(basename)[0]
    source_subs_ext = os.path.splitext(basename)[1][1:]

    if item.category != 'video':
        return error_response(
            response, 'Transcripts are supported only for "video" modules.')

    # Allow upload only if any video link is presented
    if video_list:
        sub_attr = source_subs_name
        try:
            # Generate and save for 1.0 speed, will create subs_sub_attr.srt.sjson subtitles file in storage.
            generate_subs_from_source({1: sub_attr}, source_subs_ext,
                                      source_subs_filedata, item)

            for video_dict in video_list:
                video_name = video_dict['video']
                # We are creating transcripts for every video source, if in future some of video sources would be deleted.
                # Updates item.sub with `video_name` on success.
                copy_or_rename_transcript(video_name,
                                          sub_attr,
                                          item,
                                          user=request.user)

            response['subs'] = item.sub
            response['status'] = 'Success'
        except Exception as ex:
            return error_response(response, ex.message)
    else:
        return error_response(response, 'Empty video sources.')

    return JsonResponse(response)
예제 #5
0
def upload_transcripts(request):
    """
    Upload transcripts for current module.

    returns: response dict::

        status: 'Success' and HTTP 200 or 'Error' and HTTP 400.
        subs: Value of uploaded and saved html5 sub field in video item.
    """
    response = {
        'status': 'Unknown server error',
        'subs': '',
    }

    locator = request.POST.get('locator')
    if not locator:
        return error_response(response, 'POST data without "locator" form data.')

    try:
        item = _get_item(request, request.POST)
    except (ItemNotFoundError, InvalidLocationError, InsufficientSpecificationError):
        return error_response(response, "Can't find item by locator.")

    if 'file' not in request.FILES:
        return error_response(response, 'POST data without "file" form data.')

    video_list = request.POST.get('video_list')
    if not video_list:
        return error_response(response, 'POST data without video names.')

    try:
        video_list = json.loads(video_list)
    except ValueError:
        return error_response(response, 'Invalid video_list JSON.')

    source_subs_filedata = request.FILES['file'].read().decode('utf8')
    source_subs_filename = request.FILES['file'].name

    if '.' not in source_subs_filename:
        return error_response(response, "Undefined file extension.")

    basename = os.path.basename(source_subs_filename)
    source_subs_name = os.path.splitext(basename)[0]
    source_subs_ext = os.path.splitext(basename)[1][1:]

    if item.category != 'video':
        return error_response(response, 'Transcripts are supported only for "video" modules.')

    # Allow upload only if any video link is presented
    if video_list:
        sub_attr = source_subs_name
        try:
            # Generate and save for 1.0 speed, will create subs_sub_attr.srt.sjson subtitles file in storage.
            generate_subs_from_source({1: sub_attr}, source_subs_ext, source_subs_filedata, item)

            for video_dict in video_list:
                video_name = video_dict['video']
                # We are creating transcripts for every video source, if in future some of video sources would be deleted.
                # Updates item.sub with `video_name` on success.
                copy_or_rename_transcript(video_name, sub_attr, item, user=request.user)

            response['subs'] = item.sub
            response['status'] = 'Success'
        except Exception as ex:
            return error_response(response, ex.message)
    else:
        return error_response(response, 'Empty video sources.')

    return JsonResponse(response)
 def test_save_unicode_filename(self):
     # Mock a video item
     item = Mock(location=Mock(course_key=self.course.id))
     transcripts_utils.save_subs_to_store(self.subs, self.subs_id, self.course)
     transcripts_utils.copy_or_rename_transcript(self.subs_copied_id, self.subs_id, item)
     self.assertTrue(contentstore().find(self.content_copied_location))