def create_event()

in source/controlplaneapi/runtime/app.py [0:0]


def create_event():
    """
    Creates a new event in MRE.

    Body:

    .. code-block:: python

        {
            "Name": string,
            "Program": string,
            "Description": string,
            "Channel": string,
            "ProgramId": string,
            "SourceVideoUrl": string,
            "SourceVideoAuth": object,
            "SourceVideoMetadata": object,
            "BootstrapTimeInMinutes": integer,
            "Profile": string,
            "ContentGroup": string,
            "Start": timestamp,
            "DurationMinutes": integer,
            "Archive": boolean
        }

    Parameters:

        - Name: Name of the Event
        - Program: Name of the Program
        - Description: Event Description 
        - Channel: Identifier of the AWS Elemental MediaLive Channel used for the Event
        - ProgramId: A Unique Identifier for the event being broadcasted.
        - SourceVideoUrl: VOD or Live Urls to help MRE to harvest the streams
        - SourceVideoAuth: A Dict which contains API Authorization payload to help MRE harvest VOD/Live streams
        - SourceVideoMetadata: A Dict of additional Event Metadata for reporting purposes.
        - BootstrapTimeInMinutes: Duration in Minutes which indicates the time it takes for the VOD/Live stream harvester to be initialized
        - Profile: Name of the MRE Profile to make use of for processing the event
        - ContentGroup: Name of the Content Group
        - Start: The Actual start DateTime of the event
        - DurationMinutes: The Total Event Duration
        - Archive: Backup the Source Video if true.

    Returns:

        None

    Raises:
        400 - BadRequestError
        404 - NotFoundError
        409 - ConflictError
        500 - ChaliceViewError
    """
    try:
        event = json.loads(app.current_request.raw_body.decode(), parse_float=Decimal)

        validate(instance=event, schema=API_SCHEMA["create_event"], format_checker=FormatChecker())

        print("Got a valid event schema")

        name = event["Name"]
        program = event["Program"]

        is_vod_event = False

        start_utc_time = datetime.strptime(event["Start"], "%Y-%m-%dT%H:%M:%SZ")
        cur_utc_time = datetime.utcnow()

        event["BootstrapTimeInMinutes"] = event["BootstrapTimeInMinutes"] if "BootstrapTimeInMinutes" in event else 5
        event["Id"] = str(uuid.uuid4())
        event["Status"] = "Queued"
        event["Created"] = cur_utc_time.strftime("%Y-%m-%dT%H:%M:%SZ")
        event["HlsMasterManifest"] = {}
        event["EdlLocation"] = {}
        event["PaginationPartition"] = "PAGINATION_PARTITION"
        event["StartFilter"] = event["Start"]

        event_table = ddb_resource.Table(EVENT_TABLE_NAME)

        if "Channel" in event and event["Channel"]:
            # Check if the event start time is in the past
            if cur_utc_time >= start_utc_time:
                is_vod_event = True

            event["LastKnownMediaLiveConfig"] = add_or_update_medialive_output_group(name, program, event["Profile"],
                                                                                     event["Channel"])

            # Add or Update the CW Alarm for the MediaLive channel
            create_cloudwatch_alarm_for_channel(event["Channel"])

        if "SourceVideoAuth" in event:
            response = sm_client.create_secret(
                Name=f"/MRE/Event/{event['Id']}/SourceVideoAuth",
                SecretString=json.dumps(event["SourceVideoAuth"]),
                Tags=[
                    {
                        "Key": "Project",
                        "Value": "MRE"
                    },
                    {
                        "Key": "Program",
                        "Value": program
                    },
                    {
                        "Key": "Event",
                        "Value": name
                    }
                ]
            )

            event["SourceVideoAuthSecretARN"] = response["ARN"]
            event.pop("SourceVideoAuth", None)

        print(f"Creating the event '{name}' in program '{program}'")

        event_table.put_item(
            Item=event,
            ConditionExpression="attribute_not_exists(#Name) AND attribute_not_exists(#Program)",
            ExpressionAttributeNames={
                "#Name": "Name",
                "#Program": "Program"
            }
        )

    except NotFoundError as e:
        print(f"Got chalice NotFoundError: {str(e)}")
        raise

    except ValidationError as e:
        print(f"Got jsonschema ValidationError: {str(e)}")
        raise BadRequestError(e.message)

    except ConflictError as e:
        print(f"Got chalice ConflictError: {str(e)}")
        raise

    except ClientError as e:
        print(f"Got DynamoDB ClientError: {str(e)}")

        if "LastKnownMediaLiveConfig" in event:
            medialive_client.update_channel(
                ChannelId=event["Channel"],
                Destinations=event["LastKnownMediaLiveConfig"]["Destinations"],
                EncoderSettings=event["LastKnownMediaLiveConfig"]["EncoderSettings"]
            )

        if e.response["Error"]["Code"] == "ConditionalCheckFailedException":
            raise ConflictError(f"Event '{name}' in program '{program}' already exists")
        else:
            raise

    except Exception as e:
        print(f"Unable to create the event '{name}' in program '{program}': {str(e)}")

        if "LastKnownMediaLiveConfig" in event:
            medialive_client.update_channel(
                ChannelId=event["Channel"],
                Destinations=event["LastKnownMediaLiveConfig"]["Destinations"],
                EncoderSettings=event["LastKnownMediaLiveConfig"]["EncoderSettings"]
            )

        raise ChaliceViewError(f"Unable to create the event '{name}' in program '{program}': {str(e)}")

    else:
        print(f"Successfully created the event: {json.dumps(event)}")

        if is_vod_event:
            channel_id = event["Channel"]
            print(f"Starting the MediaLive channel '{channel_id}' as the event is based on a VOD asset")

            try:
                medialive_client.start_channel(
                    ChannelId=channel_id
                )

            except Exception as e:
                print(
                    f"Creation of event '{name}' in program '{program}' is successful but unable to start the MediaLive channel '{channel_id}': {str(e)}")
                raise ChaliceViewError(
                    f"Creation of event '{name}' in program '{program}' is successful but unable to start the MediaLive channel '{channel_id}': {str(e)}")

        return {}