NonlinearFruit / SermonAudioClient

Cli for uploading sermons
0 stars 0 forks source link

Use v2 api #2

Open NonlinearFruit opened 2 years ago

NonlinearFruit commented 2 years ago

Here are the examples provided. They are in Python. If you need more specific help let me know and I will put you in contact with one of the developers directly.

SermonAudio's v2 sermon create API is unfortunately not well documented outside of our API client library's code (https://pypi.org/project/sermonaudio/), but here are a few samples.

The v2 endpoint is similar to v1, except it has more options.

To create a sermon:

#!/bin/sh

# SAMPLE OF CREATING A SERMON USING THE SERMONAUDIO API V2.

# Your API key.
API_KEY=...put your broadcaster API key here...

TITLE="A Test Sermon"
SHORTITLE=""  # optional
SUBTITLE="Just Testing"
SPEAKER="William Booth"  # will be created if doesn't exist
PREACH_DATE="1999-01-01"
PUBLISH_DATE="2019-06-01"  # can be set in the future
BIBLE="Genesis 1:1"
MORE_INFO="Just a test sermon"
EVENT_TYPE="Sunday Service"  # this is the default
LANG="en"  # this is the default
KEYWORDS="test, just testing, sermon"

ENDPOINT=["https://api.sermonaudio.com/v2/node/sermons"](https://api.sermonaudio.com/v2/node/sermons)

# Our API doesn't care if you post a JSON body as the payload, or POST
# individual fields. Pick whatever is easiest.

curl -v -H "Content-Type: application/x-www-form-urlencoded" \
     -X POST \
     --header "X-API-Key: ${API_KEY}" \
     --data-urlencode "broadcasterID=${BROADCASTERID}" \
     --data-urlencode "fullTitle=${TITLE}" \
     --data-urlencode "displayTitle=${SHORTITLE}" \
     --data-urlencode "subtitle=${SUBTITLE}" \
     --data-urlencode "speakerName=${SPEAKER}" \
     --data-urlencode "preachDate=${PREACH_DATE}" \
     --data-urlencode "publishDate=${PUBLISH_DATE}" \
     --data-urlencode "bibleText=${BIBLE}" \
     --data-urlencode "moreInfoText=${MORE_INFO}" \
     --data-urlencode "eventType=${EVENT_TYPE}" \
     --data-urlencode "languageCode=${LANG}" \
     --data-urlencode "keywords=${KEYWORDS}" \
     --data-urlencode "acceptCopyright=true" \
     $ENDPOINT \
    | python -mjson.tool

To upload media, it's a two-step process where you create an upload for the sermon ID you got when you created the sermon record, and then use the URL you get back from the upload create to do the actual upload. This is harder to do in curl, because you have to get the URL out of the response from creating the object. Since Python is good at processing JSON, I use it. This process puts the sermon media directly into our processing pipeline. Curl also is a little obscure, since if you upload data from a file, you have to use an @ syntax. The process is much easier in Python or any other language that has file processing.

#!/bin/sh

# SAMPLE OF UPLOADING A SERMON USING THE SERMONAUDIO API V2.

# Your broadcaster API key.
API_KEY=...put your broadcaster API key here...

# For the sake of example, the sermon ID you want to upload media for
# is hard-coded.
SERMON_ID=...insert a Sermon ID here...

# The file you want to upload. For the sake of example, it's
# hard-coded too.
MEDIA_DIR=..insert the directory where your file lives...
MEDIA_FILENAME=...insert your filename...
MEDIA_PATH="@${MEDIA_DIR}/${MEDIA_FILENAME}"

ENDPOINT=["https://api.sermonaudio.com/v2/media"](https://api.sermonaudio.com/v2/media)

JSON="{
\"sermonID\": \"${SERMON_ID}\",
\"uploadType\": \"original-audio\",
\"originalFilename\": \"${FILENAME}\"
}
"

# First, post to the media endpoint to create a media upload for the
# sermon. Part of the response will be the URL to which you upload the
# media.
#
# We need to capture the output from posting to the endpoint. In a
# shell script, that's kind of clumsy. I'm using a Python snippet to
# get the field we need out of the JSON response. In a programming
# language, this would be much simpler.

UPLOAD_RESPONSE=$(
    curl -v \
         -H "X-API-Key: ${API_KEY}" \
         -H "Content-Type: application/json" \
         -X POST \
         -d "$JSON" \
         $ENDPOINT
          )

GET_URL_SNIPPET="
import json
import sys
print(json.loads(sys.stdin.read()))['uploadURL']
"

URL=$( echo $UPLOAD_RESPONSE | python -c "$GET_URL_SNIPPET" )

curl -v \
     -H "X-API-Key: ${API_KEY}" \
     -X POST \
     --data-binary "$MEDIA_PATH" \
     $URL

In Python the whole thing amounts to calling create_or_update_sermon() and then upload_audio().

Python sample:

from datetime import date, datetime

import sermonaudio

from sermonaudio.broadcaster.requests import BroadcasterAPIError, Broadcaster
from sermonaudio.models import SermonEventType

sermonaudio.set_api_key("...your key goes here...")

filename = "1910.01.01.X Short Excerpt - William Booth - 117021689.mp3"

new_sermon = None

if __name__ == "__main__":
    try:
        # Create a new sermon...
        new_sermon = Broadcaster.create_or_update_sermon(
            accept_copyright=True,
            full_title="Just Testing",
            speaker_name="William Booth",
            preach_date=date.today(),
            publish_timestamp=datetime.now(),
            event_type=SermonEventType.SUNDAY_AM,
            language_code="en",
            sermon_id=None,
            display_title=None,
            subtitle=None,
            bible_text=None,
            more_info_text=None,
            keywords=None,
        )

        if new_sermon is None:
            print("new sermon is None, so sermon create failed!")
            exit(1)

        print(f"Created sermon: {new_sermon.sermon_id}")

        # ...upload the audio...
        Broadcaster.upload_audio(sermon_id=new_sermon.sermon_id, path=filename)

        # ... and delete the sermon.
        # Broadcaster.delete_sermon(new_sermon.sermon_id)
        # print(f"Sermon {new_sermon.sermon_id} has been deleted!")

    except BroadcasterAPIError as e:
        print(f"That didn't work: {e}")
        sys.exit(1)