videos.py 29.6 KB
Newer Older
1 2 3
"""
Views related to the video upload feature
"""
4
import csv
5
import json
6
import logging
7
from contextlib import closing
8
from datetime import datetime, timedelta
9 10
from uuid import uuid4

11 12
import rfc6266
from boto import s3
13 14
from django.conf import settings
from django.contrib.auth.decorators import login_required
15
from django.contrib.staticfiles.storage import staticfiles_storage
16
from django.core.files.images import get_image_dimensions
17
from django.http import HttpResponse, HttpResponseNotFound
18 19
from django.utils.translation import ugettext as _
from django.utils.translation import ugettext_noop
20
from django.views.decorators.http import require_GET, require_http_methods, require_POST
21 22 23
from edxval.api import (
    SortDirection,
    VideoSortField,
24
    create_or_update_transcript_preferences,
25
    create_video,
26
    get_3rd_party_transcription_plans,
27
    get_transcript_credentials_state_for_org,
28
    get_transcript_preferences,
29
    get_videos_for_course,
30
    remove_transcript_preferences,
31 32 33
    remove_video_for_course,
    update_video_image,
    update_video_status
34
)
35 36
from opaque_keys.edx.keys import CourseKey

37
from contentstore.models import VideoUploadConfig
38 39
from contentstore.utils import reverse_course_url
from edxmako.shortcuts import render_to_response
40 41
from openedx.core.djangoapps.video_config.models import VideoTranscriptEnabledFlag
from openedx.core.djangoapps.waffle_utils import WaffleSwitchNamespace
42
from util.json_request import JsonResponse, expect_json
43 44 45

from .course import get_course_and_check_access

46 47 48 49 50 51
__all__ = [
    'videos_handler',
    'video_encodings_download',
    'video_images_handler',
    'transcript_preferences_handler',
]
52

53 54
LOGGER = logging.getLogger(__name__)

55 56 57 58 59 60
# Waffle switches namespace for videos
WAFFLE_NAMESPACE = 'videos'
WAFFLE_SWITCHES = WaffleSwitchNamespace(name=WAFFLE_NAMESPACE)

# Waffle switch for enabling/disabling video image upload feature
VIDEO_IMAGE_UPLOAD_ENABLED = 'video_image_upload_enabled'
61 62 63 64

# Default expiration, in seconds, of one-time URLs used for uploading videos.
KEY_EXPIRATION_IN_SECONDS = 86400

65 66 67 68 69
VIDEO_SUPPORTED_FILE_FORMATS = {
    '.mp4': 'video/mp4',
    '.mov': 'video/quicktime',
}

70 71
VIDEO_UPLOAD_MAX_FILE_SIZE_GB = 5

72 73 74
# maximum time for video to remain in upload state
MAX_UPLOAD_HOURS = 24

75

76 77 78 79 80 81 82 83
class TranscriptProvider(object):
    """
    3rd Party Transcription Provider Enumeration
    """
    CIELO24 = 'Cielo24'
    THREE_PLAY_MEDIA = '3PlayMedia'


84 85
class StatusDisplayStrings(object):
    """
86 87
    A class to map status strings as stored in VAL to display strings for the
    video upload page
88
    """
89

90
    # Translators: This is the status of an active video upload
91
    _UPLOADING = ugettext_noop("Uploading")
92
    # Translators: This is the status for a video that the servers are currently processing
93
    _IN_PROGRESS = ugettext_noop("In Progress")
94
    # Translators: This is the status for a video that the servers have successfully processed
95
    _COMPLETE = ugettext_noop("Ready")
96 97
    # Translators: This is the status for a video that is uploaded completely
    _UPLOAD_COMPLETED = ugettext_noop("Uploaded")
98
    # Translators: This is the status for a video that the servers have failed to process
99
    _FAILED = ugettext_noop("Failed")
100 101
    # Translators: This is the status for a video that is cancelled during upload by user
    _CANCELLED = ugettext_noop("Cancelled")
102 103 104
    # Translators: This is the status for a video which has failed
    # due to being flagged as a duplicate by an external or internal CMS
    _DUPLICATE = ugettext_noop("Failed Duplicate")
105 106
    # Translators: This is the status for a video which has duplicate token for youtube
    _YOUTUBE_DUPLICATE = ugettext_noop("YouTube Duplicate")
107 108
    # Translators: This is the status for a video for which an invalid
    # processing token was provided in the course settings
109
    _INVALID_TOKEN = ugettext_noop("Invalid Token")
110 111
    # Translators: This is the status for a video that was included in a course import
    _IMPORTED = ugettext_noop("Imported")
112
    # Translators: This is the status for a video that is in an unknown state
113
    _UNKNOWN = ugettext_noop("Unknown")
114 115 116
    # Translators: This is the status for a video that is having its transcription in progress on servers
    _TRANSCRIPTION_IN_PROGRESS = ugettext_noop("Transcription in Progress")
    # Translators: This is the status for a video whose transcription is complete
117
    _TRANSCRIPT_READY = ugettext_noop("Transcript Ready")
118 119 120 121 122 123 124 125

    _STATUS_MAP = {
        "upload": _UPLOADING,
        "ingest": _IN_PROGRESS,
        "transcode_queue": _IN_PROGRESS,
        "transcode_active": _IN_PROGRESS,
        "file_delivered": _COMPLETE,
        "file_complete": _COMPLETE,
126
        "upload_completed": _UPLOAD_COMPLETED,
127 128
        "file_corrupt": _FAILED,
        "pipeline_error": _FAILED,
129 130 131
        "upload_failed": _FAILED,
        "s3_upload_failed": _FAILED,
        "upload_cancelled": _CANCELLED,
132
        "duplicate": _DUPLICATE,
133
        "youtube_duplicate": _YOUTUBE_DUPLICATE,
134 135
        "invalid_token": _INVALID_TOKEN,
        "imported": _IMPORTED,
136
        "transcription_in_progress": _TRANSCRIPTION_IN_PROGRESS,
137
        "transcript_ready": _TRANSCRIPT_READY,
138
    }
139 140 141 142

    @staticmethod
    def get(val_status):
        """Map a VAL status string to a localized display string"""
143
        return _(StatusDisplayStrings._STATUS_MAP.get(val_status, StatusDisplayStrings._UNKNOWN))    # pylint: disable=translation-of-non-string
144 145


146 147
@expect_json
@login_required
148 149
@require_http_methods(("GET", "POST", "DELETE"))
def videos_handler(request, course_key_string, edx_video_id=None):
150 151 152 153
    """
    The restful handler for video uploads.

    GET
154 155
        html: return an HTML page to display previous video uploads and allow
            new ones
156 157 158 159 160 161
        json: return json representing the videos that have been uploaded and
            their statuses
    POST
        json: create a new video upload; the actual files should not be provided
            to this endpoint but rather PUT to the respective upload_url values
            contained in the response
162 163
    DELETE
        soft deletes a video for particular course
164
    """
165
    course = _get_and_validate_course(course_key_string, request.user)
166

167
    if not course:
168 169
        return HttpResponseNotFound()

170 171 172 173 174
    if request.method == "GET":
        if "application/json" in request.META.get("HTTP_ACCEPT", ""):
            return videos_index_json(course)
        else:
            return videos_index_html(course)
175 176 177
    elif request.method == "DELETE":
        remove_video_for_course(course_key_string, edx_video_id)
        return JsonResponse()
178
    else:
179 180 181
        if is_status_update_request(request.json):
            return send_video_status_update(request.json)

182 183 184
        return videos_post(course, request)


185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
def validate_video_image(image_file):
    """
    Validates video image file.

    Arguments:
        image_file: The selected image file.

   Returns:
        error (String or None): If there is error returns error message otherwise None.
    """
    error = None

    if not all(hasattr(image_file, attr) for attr in ['name', 'content_type', 'size']):
        error = _('The image must have name, content type, and size information.')
    elif image_file.content_type not in settings.VIDEO_IMAGE_SUPPORTED_FILE_FORMATS.values():
        error = _('This image file type is not supported. Supported file types are {supported_file_formats}.').format(
            supported_file_formats=settings.VIDEO_IMAGE_SUPPORTED_FILE_FORMATS.keys()
        )
    elif image_file.size > settings.VIDEO_IMAGE_SETTINGS['VIDEO_IMAGE_MAX_BYTES']:
        error = _('This image file must be smaller than {image_max_size}.').format(
            image_max_size=settings.VIDEO_IMAGE_MAX_FILE_SIZE_MB
        )
    elif image_file.size < settings.VIDEO_IMAGE_SETTINGS['VIDEO_IMAGE_MIN_BYTES']:
        error = _('This image file must be larger than {image_min_size}.').format(
            image_min_size=settings.VIDEO_IMAGE_MIN_FILE_SIZE_KB
        )
    else:
        try:
            image_file_width, image_file_height = get_image_dimensions(image_file)
        except TypeError:
215
            return _('There is a problem with this image file. Try to upload a different file.')
216 217
        if image_file_width is None or image_file_height is None:
            return _('There is a problem with this image file. Try to upload a different file.')
218
        image_file_aspect_ratio = abs(image_file_width / float(image_file_height) - settings.VIDEO_IMAGE_ASPECT_RATIO)
219
        if image_file_width < settings.VIDEO_IMAGE_MIN_WIDTH or image_file_height < settings.VIDEO_IMAGE_MIN_HEIGHT:
220 221 222 223
            error = _('Recommended image resolution is {image_file_max_width}x{image_file_max_height}. '
                      'The minimum resolution is {image_file_min_width}x{image_file_min_height}.').format(
                image_file_max_width=settings.VIDEO_IMAGE_MAX_WIDTH,
                image_file_max_height=settings.VIDEO_IMAGE_MAX_HEIGHT,
224 225 226
                image_file_min_width=settings.VIDEO_IMAGE_MIN_WIDTH,
                image_file_min_height=settings.VIDEO_IMAGE_MIN_HEIGHT
            )
227 228 229 230
        elif image_file_aspect_ratio > settings.VIDEO_IMAGE_ASPECT_RATIO_ERROR_MARGIN:
            error = _('This image file must have an aspect ratio of {video_image_aspect_ratio_text}.').format(
                video_image_aspect_ratio_text=settings.VIDEO_IMAGE_ASPECT_RATIO_TEXT
            )
231 232 233 234 235 236 237 238
        else:
            try:
                image_file.name.encode('ascii')
            except UnicodeEncodeError:
                error = _('The image file name can only contain letters, numbers, hyphens (-), and underscores (_).')
    return error


239 240 241 242
@expect_json
@login_required
@require_POST
def video_images_handler(request, course_key_string, edx_video_id=None):
243 244 245 246 247

    # respond with a 404 if image upload is not enabled.
    if not WAFFLE_SWITCHES.is_enabled(VIDEO_IMAGE_UPLOAD_ENABLED):
        return HttpResponseNotFound()

248
    if 'file' not in request.FILES:
249
        return JsonResponse({'error': _(u'An image file is required.')}, status=400)
250 251

    image_file = request.FILES['file']
252 253 254
    error = validate_video_image(image_file)
    if error:
        return JsonResponse({'error': error}, status=400)
255 256

    with closing(image_file):
257
        image_url = update_video_image(edx_video_id, course_key_string, image_file, image_file.name)
258 259 260 261 262 263 264
        LOGGER.info(
            'VIDEOS: Video image uploaded for edx_video_id [%s] in course [%s]', edx_video_id, course_key_string
        )

    return JsonResponse({'image_url': image_url})


265 266
def validate_transcript_preferences(provider, cielo24_fidelity, cielo24_turnaround,
                                    three_play_turnaround, video_source_language, preferred_languages):
267 268 269 270 271 272 273 274
    """
    Validate 3rd Party Transcription Preferences.

    Arguments:
        provider: Transcription provider
        cielo24_fidelity:  Cielo24 transcription fidelity.
        cielo24_turnaround: Cielo24 transcription turnaround.
        three_play_turnaround: 3PlayMedia transcription turnaround.
275
        video_source_language: Source/Speech language of the videos that are going to be submitted to the Providers.
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
        preferred_languages: list of language codes.

    Returns:
        validated preferences or a validation error.
    """
    error, preferences = None, {}

    # validate transcription providers
    transcription_plans = get_3rd_party_transcription_plans()
    if provider in transcription_plans.keys():

        # Further validations for providers
        if provider == TranscriptProvider.CIELO24:

            # Validate transcription fidelity
            if cielo24_fidelity in transcription_plans[provider]['fidelity']:

                # Validate transcription turnaround
                if cielo24_turnaround not in transcription_plans[provider]['turnaround']:
295
                    error = 'Invalid cielo24 turnaround {}.'.format(cielo24_turnaround)
296 297 298 299
                    return error, preferences

                # Validate transcription languages
                supported_languages = transcription_plans[provider]['fidelity'][cielo24_fidelity]['languages']
300 301 302 303
                if video_source_language not in supported_languages:
                    error = 'Unsupported source language {}.'.format(video_source_language)
                    return error, preferences

304
                if not len(preferred_languages) or not (set(preferred_languages) <= set(supported_languages.keys())):
305
                    error = 'Invalid languages {}.'.format(preferred_languages)
306 307 308 309
                    return error, preferences

                # Validated Cielo24 preferences
                preferences = {
310
                    'video_source_language': video_source_language,
311 312
                    'cielo24_fidelity': cielo24_fidelity,
                    'cielo24_turnaround': cielo24_turnaround,
313
                    'preferred_languages': preferred_languages,
314 315
                }
            else:
316
                error = 'Invalid cielo24 fidelity {}.'.format(cielo24_fidelity)
317 318 319 320
        elif provider == TranscriptProvider.THREE_PLAY_MEDIA:

            # Validate transcription turnaround
            if three_play_turnaround not in transcription_plans[provider]['turnaround']:
321
                error = 'Invalid 3play turnaround {}.'.format(three_play_turnaround)
322 323 324
                return error, preferences

            # Validate transcription languages
325 326 327 328 329 330 331 332
            valid_translations_map = transcription_plans[provider]['translations']
            if video_source_language not in valid_translations_map.keys():
                error = 'Unsupported source language {}.'.format(video_source_language)
                return error, preferences

            valid_target_languages = valid_translations_map[video_source_language]
            if not len(preferred_languages) or not (set(preferred_languages) <= set(valid_target_languages)):
                error = 'Invalid languages {}.'.format(preferred_languages)
333 334 335 336 337
                return error, preferences

            # Validated 3PlayMedia preferences
            preferences = {
                'three_play_turnaround': three_play_turnaround,
338 339
                'video_source_language': video_source_language,
                'preferred_languages': preferred_languages,
340 341
            }
    else:
342
        error = 'Invalid provider {}.'.format(provider)
343 344 345 346 347 348

    return error, preferences


@expect_json
@login_required
349
@require_http_methods(('POST', 'DELETE'))
350 351 352 353 354 355 356 357 358 359
def transcript_preferences_handler(request, course_key_string):
    """
    JSON view handler to post the transcript preferences.

    Arguments:
        request: WSGI request object
        course_key_string: string for course key

    Returns: valid json response or 400 with error message
    """
360 361 362 363 364
    course_key = CourseKey.from_string(course_key_string)
    is_video_transcript_enabled = VideoTranscriptEnabledFlag.feature_enabled(course_key)
    if not is_video_transcript_enabled:
        return HttpResponseNotFound()

365 366 367 368 369 370 371 372
    if request.method == 'POST':
        data = request.json
        provider = data.get('provider')
        error, preferences = validate_transcript_preferences(
            provider=provider,
            cielo24_fidelity=data.get('cielo24_fidelity', ''),
            cielo24_turnaround=data.get('cielo24_turnaround', ''),
            three_play_turnaround=data.get('three_play_turnaround', ''),
373
            video_source_language=data.get('video_source_language'),
374 375 376 377 378 379 380 381
            preferred_languages=data.get('preferred_languages', [])
        )
        if error:
            response = JsonResponse({'error': error}, status=400)
        else:
            preferences.update({'provider': provider})
            transcript_preferences = create_or_update_transcript_preferences(course_key_string, **preferences)
            response = JsonResponse({'transcript_preferences': transcript_preferences}, status=200)
382 383

        return response
384 385
    elif request.method == 'DELETE':
        remove_transcript_preferences(course_key_string)
386
        return JsonResponse()
387 388


389 390 391 392 393 394 395
@login_required
@require_GET
def video_encodings_download(request, course_key_string):
    """
    Returns a CSV report containing the encoded video URLs for video uploads
    in the following format:

396 397
    Video ID,Name,Status,Profile1 URL,Profile2 URL
    aaaaaaaa-aaaa-4aaa-aaaa-aaaaaaaaaaaa,video.mp4,Complete,http://example.com/prof1.mp4,http://example.com/prof2.mp4
398 399 400 401 402 403 404 405 406 407 408 409 410
    """
    course = _get_and_validate_course(course_key_string, request.user)

    if not course:
        return HttpResponseNotFound()

    def get_profile_header(profile):
        """Returns the column header string for the given profile's URLs"""
        # Translators: This is the header for a CSV file column
        # containing URLs for video encodings for the named profile
        # (e.g. desktop, mobile high quality, mobile low quality)
        return _("{profile_name} URL").format(profile_name=profile)

411
    profile_whitelist = VideoUploadConfig.get_profile_whitelist()
412 413 414 415 416 417

    videos = list(_get_videos(course))
    name_col = _("Name")
    duration_col = _("Duration")
    added_col = _("Date Added")
    video_id_col = _("Video ID")
418
    status_col = _("Status")
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
    profile_cols = [get_profile_header(profile) for profile in profile_whitelist]

    def make_csv_dict(video):
        """
        Makes a dictionary suitable for writing CSV output. This involves
        extracting the required items from the original video dict and
        converting all keys and values to UTF-8 encoded string objects,
        because the CSV module doesn't play well with unicode objects.
        """
        # Translators: This is listed as the duration for a video that has not
        # yet reached the point in its processing by the servers where its
        # duration is determined.
        duration_val = str(video["duration"]) if video["duration"] > 0 else _("Pending")
        ret = dict(
            [
                (name_col, video["client_video_id"]),
                (duration_col, duration_val),
                (added_col, video["created"].isoformat()),
                (video_id_col, video["edx_video_id"]),
438
                (status_col, video["status"]),
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
            ] +
            [
                (get_profile_header(encoded_video["profile"]), encoded_video["url"])
                for encoded_video in video["encoded_videos"]
                if encoded_video["profile"] in profile_whitelist
            ]
        )
        return {
            key.encode("utf-8"): value.encode("utf-8")
            for key, value in ret.items()
        }

    response = HttpResponse(content_type="text/csv")
    # Translators: This is the suggested filename when downloading the URL
    # listing for videos uploaded through Studio
    filename = _("{course}_video_urls").format(course=course.id.course)
    # See https://tools.ietf.org/html/rfc6266#appendix-D
    response["Content-Disposition"] = rfc6266.build_header(
        filename + ".csv",
        filename_compat="video_urls.csv"
    )
    writer = csv.DictWriter(
        response,
462 463 464 465 466
        [
            col_name.encode("utf-8")
            for col_name
            in [name_col, duration_col, added_col, video_id_col, status_col] + profile_cols
        ],
467 468 469 470
        dialect=csv.excel
    )
    writer.writeheader()
    for video in videos:
471
        writer.writerow(make_csv_dict(video))
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
    return response


def _get_and_validate_course(course_key_string, user):
    """
    Given a course key, return the course if it exists, the given user has
    access to it, and it is properly configured for video uploads
    """
    course_key = CourseKey.from_string(course_key_string)

    # For now, assume all studio users that have access to the course can upload videos.
    # In the future, we plan to add a new org-level role for video uploaders.
    course = get_course_and_check_access(course_key, user)

    if (
            settings.FEATURES["ENABLE_VIDEO_UPLOAD_PIPELINE"] and
            getattr(settings, "VIDEO_UPLOAD_PIPELINE", None) and
            course and
            course.video_pipeline_configured
    ):
        return course
    else:
        return None


497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
def convert_video_status(video):
    """
    Convert status of a video. Status can be converted to one of the following:

        *   FAILED if video is in `upload` state for more than 24 hours
        *   `YouTube Duplicate` if status is `invalid_token`
        *   user-friendly video status
    """
    now = datetime.now(video['created'].tzinfo)
    if video['status'] == 'upload' and (now - video['created']) > timedelta(hours=MAX_UPLOAD_HOURS):
        new_status = 'upload_failed'
        status = StatusDisplayStrings.get(new_status)
        message = 'Video with id [%s] is still in upload after [%s] hours, setting status to [%s]' % (
            video['edx_video_id'], MAX_UPLOAD_HOURS, new_status
        )
        send_video_status_update([
            {
                'edxVideoId': video['edx_video_id'],
                'status': new_status,
                'message': message
            }
        ])
    elif video['status'] == 'invalid_token':
        status = StatusDisplayStrings.get('youtube_duplicate')
    else:
        status = StatusDisplayStrings.get(video['status'])

    return status


527 528
def _get_videos(course):
    """
529
    Retrieves the list of videos from VAL corresponding to this course.
530
    """
531
    videos = list(get_videos_for_course(unicode(course.id), VideoSortField.created, SortDirection.desc))
532 533 534

    # convert VAL's status to studio's Video Upload feature status.
    for video in videos:
535
        video["status"] = convert_video_status(video)
536 537

    return videos
538 539


540 541 542 543 544 545 546
def _get_default_video_image_url():
    """
    Returns default video image url
    """
    return staticfiles_storage.url(settings.VIDEO_IMAGE_DEFAULT_FILENAME)


547 548 549 550
def _get_index_videos(course):
    """
    Returns the information about each video upload required for the video list
    """
551 552 553 554 555 556 557 558 559 560 561
    course_id = unicode(course.id)
    attrs = ['edx_video_id', 'client_video_id', 'created', 'duration', 'status', 'courses']

    def _get_values(video):
        """
        Get data for predefined video attributes.
        """
        values = {}
        for attr in attrs:
            if attr == 'courses':
                course = filter(lambda c: course_id in c, video['courses'])
muhammad-ammar committed
562
                (__, values['course_video_image_url']), = course[0].items()
563 564 565 566 567 568 569 570
            else:
                values[attr] = video[attr]

        return values

    return [
        _get_values(video) for video in _get_videos(course)
    ]
571 572


573 574 575 576
def videos_index_html(course):
    """
    Returns an HTML page to display previous video uploads and allow new ones
    """
577
    is_video_transcript_enabled = VideoTranscriptEnabledFlag.feature_enabled(course.id)
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
    context = {
        'context_course': course,
        'image_upload_url': reverse_course_url('video_images_handler', unicode(course.id)),
        'video_handler_url': reverse_course_url('videos_handler', unicode(course.id)),
        'encodings_download_url': reverse_course_url('video_encodings_download', unicode(course.id)),
        'default_video_image_url': _get_default_video_image_url(),
        'previous_uploads': _get_index_videos(course),
        'concurrent_upload_limit': settings.VIDEO_UPLOAD_PIPELINE.get('CONCURRENT_UPLOAD_LIMIT', 0),
        'video_supported_file_formats': VIDEO_SUPPORTED_FILE_FORMATS.keys(),
        'video_upload_max_file_size': VIDEO_UPLOAD_MAX_FILE_SIZE_GB,
        'video_image_settings': {
            'video_image_upload_enabled': WAFFLE_SWITCHES.is_enabled(VIDEO_IMAGE_UPLOAD_ENABLED),
            'max_size': settings.VIDEO_IMAGE_SETTINGS['VIDEO_IMAGE_MAX_BYTES'],
            'min_size': settings.VIDEO_IMAGE_SETTINGS['VIDEO_IMAGE_MIN_BYTES'],
            'max_width': settings.VIDEO_IMAGE_MAX_WIDTH,
            'max_height': settings.VIDEO_IMAGE_MAX_HEIGHT,
            'supported_file_formats': settings.VIDEO_IMAGE_SUPPORTED_FILE_FORMATS
595 596 597
        },
        'is_video_transcript_enabled': is_video_transcript_enabled,
        'video_transcript_settings': None,
598 599
        'active_transcript_preferences': None,
        'transcript_credentials': None
600 601
    }

602 603
    if is_video_transcript_enabled:
        context['video_transcript_settings'] = {
604 605 606 607
            'transcript_preferences_handler_url': reverse_course_url(
                'transcript_preferences_handler',
                unicode(course.id)
            ),
608 609 610 611
            'transcript_credentials_handler_url': reverse_course_url(
                'transcript_credentials_handler',
                unicode(course.id)
            ),
612
            'transcription_plans': get_3rd_party_transcription_plans(),
613 614
        }
        context['active_transcript_preferences'] = get_transcript_preferences(unicode(course.id))
615 616
        # Cached state for transcript providers' credentials (org-specific)
        context['transcript_credentials'] = get_transcript_credentials_state_for_org(course.id.org)
617 618

    return render_to_response('videos_index.html', context)
619 620


621 622 623 624
def videos_index_json(course):
    """
    Returns JSON in the following format:
    {
625 626 627 628 629 630 631
        'videos': [{
            'edx_video_id': 'aaaaaaaa-aaaa-4aaa-aaaa-aaaaaaaaaaaa',
            'client_video_id': 'video.mp4',
            'created': '1970-01-01T00:00:00Z',
            'duration': 42.5,
            'status': 'upload',
            'course_video_image_url': 'https://video/images/1234.jpg'
632 633 634
        }]
    }
    """
635
    return JsonResponse({"videos": _get_index_videos(course)}, status=200)
636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658


def videos_post(course, request):
    """
    Input (JSON):
    {
        "files": [{
            "file_name": "video.mp4",
            "content_type": "video/mp4"
        }]
    }

    Returns (JSON):
    {
        "files": [{
            "file_name": "video.mp4",
            "upload_url": "http://example.com/put_video"
        }]
    }

    The returned array corresponds exactly to the input array.
    """
    error = None
659 660
    data = request.json
    if 'files' not in data:
661 662
        error = "Request object is not JSON or does not contain 'files'"
    elif any(
663
            'file_name' not in file or 'content_type' not in file
664
            for file in data['files']
665 666
    ):
        error = "Request 'files' entry does not contain 'file_name' and 'content_type'"
667 668
    elif any(
            file['content_type'] not in VIDEO_SUPPORTED_FILE_FORMATS.values()
669
            for file in data['files']
670 671
    ):
        error = "Request 'files' entry contain unsupported content_type"
672 673

    if error:
674
        return JsonResponse({'error': error}, status=400)
675 676

    bucket = storage_service_bucket()
677
    req_files = data['files']
678 679 680
    resp_files = []

    for req_file in req_files:
681
        file_name = req_file['file_name']
682

683 684 685 686 687 688
        try:
            file_name.encode('ascii')
        except UnicodeEncodeError:
            error_msg = 'The file name for %s must contain only ASCII characters.' % file_name
            return JsonResponse({'error': error_msg}, status=400)

689 690
        edx_video_id = unicode(uuid4())
        key = storage_service_key(bucket, file_name=edx_video_id)
691 692 693 694 695 696

        metadata_list = [
            ('client_video_id', file_name),
            ('course_key', unicode(course.id)),
        ]

Qubad786 committed
697 698 699 700 701 702
        # Only include `course_video_upload_token` if its set, as it won't be required if video uploads
        # are enabled by default.
        course_video_upload_token = course.video_upload_pipeline.get('course_video_upload_token')
        if course_video_upload_token:
            metadata_list.append(('course_video_upload_token', course_video_upload_token))

703 704 705 706 707
        is_video_transcript_enabled = VideoTranscriptEnabledFlag.feature_enabled(course.id)
        if is_video_transcript_enabled:
            transcript_preferences = get_transcript_preferences(unicode(course.id))
            if transcript_preferences is not None:
                metadata_list.append(('transcript_preferences', json.dumps(transcript_preferences)))
708 709

        for metadata_name, value in metadata_list:
710 711 712
            key.set_metadata(metadata_name, value)
        upload_url = key.generate_url(
            KEY_EXPIRATION_IN_SECONDS,
713 714
            'PUT',
            headers={'Content-Type': req_file['content_type']}
715 716 717 718
        )

        # persist edx_video_id in VAL
        create_video({
719 720 721 722 723 724
            'edx_video_id': edx_video_id,
            'status': 'upload',
            'client_video_id': file_name,
            'duration': 0,
            'encoded_videos': [],
            'courses': [unicode(course.id)]
725 726
        })

727
        resp_files.append({'file_name': file_name, 'upload_url': upload_url, 'edx_video_id': edx_video_id})
728

729
    return JsonResponse({'files': resp_files}, status=200)
730 731 732 733 734 735 736 737 738 739


def storage_service_bucket():
    """
    Returns an S3 bucket for video uploads.
    """
    conn = s3.connection.S3Connection(
        settings.AWS_ACCESS_KEY_ID,
        settings.AWS_SECRET_ACCESS_KEY
    )
740 741 742 743 744
    # We don't need to validate our bucket, it requires a very permissive IAM permission
    # set since behind the scenes it fires a HEAD request that is equivalent to get_all_keys()
    # meaning it would need ListObjects on the whole bucket, not just the path used in each
    # environment (since we share a single bucket for multiple deployments in some configurations)
    return conn.get_bucket(settings.VIDEO_UPLOAD_PIPELINE["BUCKET"], validate=False)
745 746 747 748 749 750 751 752 753 754 755


def storage_service_key(bucket, file_name):
    """
    Returns an S3 key to the given file in the given bucket.
    """
    key_name = "{}/{}".format(
        settings.VIDEO_UPLOAD_PIPELINE.get("ROOT_PATH", ""),
        file_name
    )
    return s3.key.Key(bucket, key_name)
756 757 758 759 760 761 762 763


def send_video_status_update(updates):
    """
    Update video status in edx-val.
    """
    for update in updates:
        update_video_status(update.get('edxVideoId'), update.get('status'))
764 765 766 767 768 769
        LOGGER.info(
            'VIDEOS: Video status update with id [%s], status [%s] and message [%s]',
            update.get('edxVideoId'),
            update.get('status'),
            update.get('message')
        )
770 771 772 773 774 775 776 777 778

    return JsonResponse()


def is_status_update_request(request_data):
    """
    Returns True if `request_data` contains status update else False.
    """
    return any('status' in update for update in request_data)