コンテンツ タイプの添付ファイル

これは、Classroom アドオンのチュートリアル シリーズの 4 番目のチュートリアルです。

このチュートリアルでは、Google Classroom API を操作して添付ファイルを作成します。ユーザーが添付ファイルの内容を閲覧するためのルートを提供します。ビューは、クラス内のユーザーのロールによって異なります。このチュートリアルでは、学生による提出を必要としないコンテンツ タイプの添付ファイルについて説明します。

このチュートリアルでは、次のことを行います。

  • 次のアドオン クエリ パラメータを取得して使用します。
    • addOnToken: Attachment Discovery ビューに渡される認証トークン。
    • itemId: アドオンの添付ファイルを受け取る CourseWork、CourseWorkMaterial、Announcement の一意の識別子。
    • itemType: 「courseWork」、「courseWorkMaterials」、「announcement」のいずれか。
    • courseId: 課題が作成される Google Classroom コースの一意の識別子。
    • attachmentId: 作成後に Google Classroom によってアドオンの添付ファイルに割り当てられる一意の識別子。
  • コンテンツ タイプの添付ファイル用の永続ストレージを実装します。
  • 添付ファイルを作成し、教師表示と生徒表示の iframe を提供するためにルートを提供します。
  • Google Classroom アドオン API に次のリクエストを発行します。
    • 新しい添付ファイルを作成します。
    • アドオン コンテキストを取得する。これにより、ログインしているユーザーが生徒か教師かを識別できます。

完了したら、教師としてログインした状態で Google Classroom の UI から課題にコンテンツ タイプの添付ファイルを作成できます。クラスの教師と生徒もコンテンツを閲覧できます

Classroom API を有効にする

このステップから Classroom API を呼び出します。Google Cloud プロジェクトで API を呼び出すには、そのプロジェクトで API を有効にする必要があります。Google Classroom API のライブラリ エントリに移動し、[有効にする] を選択します。

Attachment Discovery View クエリ パラメータを処理する

前述のとおり、Google Classroom は iframe に添付ファイルの検出ビューを読み込むときにクエリ パラメータを渡します。

  • courseId: 現在の Classroom コースの ID。
  • itemId: アドオンの添付ファイルを受け取る CourseWork、CourseWorkMaterial、Announcement の一意の識別子。
  • itemType: 「courseWork」、「courseWorkMaterials」、「announcement」のいずれか。
  • addOnToken: 特定の Classroom アドオンの操作を承認するために使用されるトークン。
  • login_hint: 現在のユーザーの Google ID。

このチュートリアルでは、courseIditemIditemTypeaddOnToken について説明します。Classroom API の呼び出しを発行する際に、これらを保持して渡します。

前のチュートリアルの手順と同様に、渡されたクエリ パラメータ値をセッションに保存します。Classroom でこれらのクエリ パラメータを渡すことができるのは今回のみであるため、添付ファイルの検出ビューを最初に開いたときに、この操作を行うことが重要です。

Python

Attachment Discovery View のルートが含まれている Flask サーバー ファイルに移動します(上記の例の場合は attachment-discovery-routes.py)。アドオンのランディング ルート(この例では /classroom-addon)の先頭で、courseIditemIditemTypeaddOnToken の各クエリ パラメータを取得して保存します。

# Retrieve the itemId, courseId, and addOnToken query parameters.
if flask.request.args.get("itemId"):
    flask.session["itemId"] = flask.request.args.get("itemId")
if flask.request.args.get("itemType"):
    flask.session["itemType"] = flask.request.args.get("itemType")
if flask.request.args.get("courseId"):
    flask.session["courseId"] = flask.request.args.get("courseId")
if flask.request.args.get("addOnToken"):
    flask.session["addOnToken"] = flask.request.args.get("addOnToken")

これらの値は存在する場合にのみセッションに書き込みます。ユーザーが iframe を閉じずに、後で添付ファイルの検出ビューに戻った場合、値が再び渡されることはありません。

コンテンツ タイプの添付ファイル用の永続ストレージを追加する

作成した添付ファイルのローカル レコードが必要です。これにより、Classroom が提供する ID を使用して、教師が選択したコンテンツを検索できます。

Attachment のデータベース スキーマを設定します。こちらの例では、画像とキャプションを含む添付ファイルを示しています。Attachment には次の属性が含まれます。

  • attachment_id: アタッチメントの一意の識別子。Classroom によって割り当てられ、添付ファイルの作成時にレスポンスで返されます。
  • image_filename: 表示する画像のローカル ファイル名。
  • image_caption: 画像とともに表示するキャプション。

Python

前のステップの SQLite と flask_sqlalchemy の実装を拡張します。

ユーザー テーブルを定義したファイルに移動します(上記の例の場合は models.py)。ファイルの下部にある User クラスの下に、次のコードを追加します。

class Attachment(db.Model):
    # The attachmentId is the unique identifier for the attachment.
    attachment_id = db.Column(db.String(120), primary_key=True)

    # The image filename to store.
    image_filename = db.Column(db.String(120))

    # The image caption to store.
    image_caption = db.Column(db.String(120))

新しい Attachment クラスを、アタッチメント処理ルートとともにサーバー ファイルにインポートします。

新しいルートを設定する

このチュートリアルの手順では、まずアプリケーションに新しいページをいくつか設定します。これにより、ユーザーはアドオンを通じてコンテンツを作成、表示できます。

アタッチメント作成ルートを追加する

教師がコンテンツを選択し、添付ファイルの作成リクエストを発行するためのページが必要です。教師が選択できるコンテンツ オプションを表示する /attachment-options ルートを実装します。コンテンツ選択ページと作成確認ページのテンプレートも必要です。提供されている例には、これらのテンプレートが含まれており、Classroom API からのリクエストやレスポンスを表示することもできます。

新しい /attachment-options ページを作成する代わりに、既存の添付ファイルの検出ビューのランディング ページを変更して、コンテンツ オプションを表示することもできます。2 番目のチュートリアルの手順で実装した SSO の動作(アプリの権限の取り消しなど)を維持できるように、この演習用に新しいページを作成することをおすすめします。これらは、アドオンをビルドしてテストする際に有用です。

提供されている例では、教師はキャプション付き画像の小さなセットから選択できます。有名なランドマークの画像が 4 枚用意されており、ファイル名からキャプションが取得されています。

Python

上記の例では、webapp/attachment_routes.py ファイル内にあります。

@app.route("/attachment-options", methods=["GET", "POST"])
def attachment_options():
    """
    Render the attachment options page from the "attachment-options.html"
    template.

    This page displays a grid of images that the user can select using
    checkboxes.
    """

    # A list of the filenames in the static/images directory.
    image_filenames = os.listdir(os.path.join(app.static_folder, "images"))

    # The image_list_form_builder method creates a form that displays a grid
    # of images, checkboxes, and captions with a Submit button. All images
    # passed in image_filenames will be shown, and the captions will be the
    # title-cased filenames.

    # The form must be built dynamically due to limitations in WTForms. The
    # image_list_form_builder method therefore also returns a list of
    # attribute names in the form, which will be used by the HTML template
    # to properly render the form.
    form, var_names = image_list_form_builder(image_filenames)

    # If the form was submitted, validate the input and create the attachments.
    if form.validate_on_submit():

        # Build a dictionary that maps image filenames to captions.
        # There will be one dictionary entry per selected item in the form.
        filename_caption_pairs = construct_filename_caption_dictionary_list(
            form)

        # Check that the user selected at least one image, then proceed to
        # make requests to the Classroom API.
        if len(filename_caption_pairs) > 0:
            return create_attachments(filename_caption_pairs)
        else:
            return flask.render_template(
                "create-attachment.html",
                message="You didn't select any images.",
                form=form,
                var_names=var_names)

    return flask.render_template(
        "attachment-options.html",
        message=("You've reached the attachment options page. "
                "Select one or more images and click 'Create Attachment'."),
        form=form,
        var_names=var_names,
    )

これにより、次のような [Create Attachments] ページが表示されます。

Python のコンテンツ選択ビューの例

教師は複数の画像を選択できます。教師が create_attachments メソッドで選択した画像ごとに 1 つのアタッチメントを作成します。

添付ファイルの作成リクエストを発行する

教師が添付したいコンテンツを特定できたら、Classroom API にリクエストを送信して課題に添付ファイルを作成します。Classroom API からレスポンスを受け取ったら、添付ファイルの詳細をデータベースに保存します。

まず、Classroom サービスのインスタンスを取得します。

Python

上記の例では、webapp/attachment_routes.py ファイル内にあります。

def create_attachments(filename_caption_pairs):
    """
    Create attachments and show an acknowledgement page.

    Args:
        filename_caption_pairs: A dictionary that maps image filenames to
            captions.
    """
    # Get the Google Classroom service.
    classroom_service = googleapiclient.discovery.build(
        serviceName="classroom",
        version="v1",
        credentials=credentials)

courses.courseWork.addOnAttachments エンドポイントに CREATE リクエストを発行します。教師が選択した画像ごとに、まず AddOnAttachment オブジェクトを作成します。

Python

上記の例では、これは create_attachments メソッドの続きです。

# Create a new attachment for each image that was selected.
attachment_count = 0
for key, value in filename_caption_pairs.items():
    attachment_count += 1

    # Create a dictionary with values for the AddOnAttachment object fields.
    attachment = {
        # Specifies the route for a teacher user.
        "teacherViewUri": {
            "uri":
                flask.url_for(
                    "load_content_attachment", _scheme='https', _external=True),
        },
        # Specifies the route for a student user.
        "studentViewUri": {
            "uri":
                flask.url_for(
                    "load_content_attachment", _scheme='https', _external=True)
        },
        # The title of the attachment.
        "title": f"Attachment {attachment_count}",
    }

アタッチメントごとに、少なくとも teacherViewUristudentViewUrititle フィールドを指定する必要があります。teacherViewUristudentViewUri は、それぞれのユーザータイプで添付ファイルを開いたときに読み込まれる URL を表します。

リクエストの本文で AddOnAttachment オブジェクトを適切な addOnAttachments エンドポイントに送信します。各リクエストに courseIditemIditemTypeaddOnToken 識別子を指定します。

Python

上記の例では、これは create_attachments メソッドの続きです。

# Use the itemType to determine which stream item type the teacher created
match flask.session["itemType"]:
    case "announcements":
        parent = classroom_service.courses().announcements()
    case "courseWorkMaterials":
        parent = classroom_service.courses().courseWorkMaterials()
    case _:
        parent = classroom_service.courses().courseWork()

# Issue a request to create the attachment.
resp = parent.addOnAttachments().create(
    courseId=flask.session["courseId"],
    itemId=flask.session["itemId"],
    addOnToken=flask.session["addOnToken"],
    body=attachment).execute()

後で正しいコンテンツを読み込むことができるように、このアタッチメントのエントリをローカル データベースに作成します。Classroom は、作成リクエストに対するレスポンスで一意の id 値を返すため、これをデータベースの主キーとして使用します。また、Classroom は、教師ビューと生徒のビューを開く際に attachmentId クエリ パラメータを渡します。

Python

上記の例では、これは create_attachments メソッドの続きです。

# Store the value by id.
new_attachment = Attachment(
    # The new attachment's unique ID, returned in the CREATE response.
    attachment_id=resp.get("id"),
    image_filename=key,
    image_caption=value)
db.session.add(new_attachment)
db.session.commit()

この時点で、アタッチメントが正常に作成されたことを確認する確認ページにユーザーを転送することを検討してください。

アドオンからの添付ファイルを許可する

ここで、Google Workspace Marketplace SDK の [アプリの構成] ページで、[Allowed Attachment URI Prefixes] フィールドに適切なアドレスを追加しましょう。アドオンは、このページに記載されている URI プレフィックスのいずれかからのみアタッチメントを作成できます。これは中間者攻撃の可能性を減らすためのセキュリティ対策です。

最も簡単な方法は、このフィールドにトップレベル ドメインを指定することです(例: https://example.com)。https://localhost:<your port number>/ は、ローカルマシンをウェブサーバーとして使用している場合に機能します。

教師ビューと生徒ビューのルートを追加する

Google Classroom アドオンを読み込むことのできる iframe は 4 つあります。これまでは、Attachment Discovery View iframe を配信するルートのみが構築されています。次に、教師と生徒用のビューの iframe にも配信するルートを追加します。

生徒の視聴環境のプレビューを表示するには、Teacher View iframe が必要ですが、必要に応じて追加情報や編集機能を含めることができます。

[Student View] は、各生徒がアドオンの添付ファイルを開くと表示されるページです。

この演習では、教師ビューと生徒ビューの両方を提供する単一の /load-content-attachment ルートを作成します。ページの読み込み時に Classroom API メソッドを使用して、ユーザーが教師か生徒かを判断します。

Python

上記の例では、webapp/attachment_routes.py ファイル内にあります。

@app.route("/load-content-attachment")
def load_content_attachment():
    """
    Load the attachment for the user's role."""

    # Since this is a landing page for the Teacher and Student View iframes, we
    # need to preserve the incoming query parameters.
    if flask.request.args.get("itemId"):
        flask.session["itemId"] = flask.request.args.get("itemId")
    if flask.request.args.get("itemType"):
        flask.session["itemType"] = flask.request.args.get("itemType")
    if flask.request.args.get("courseId"):
        flask.session["courseId"] = flask.request.args.get("courseId")
    if flask.request.args.get("attachmentId"):
        flask.session["attachmentId"] = flask.request.args.get("attachmentId")

この時点でユーザーの認証も行う必要があることに留意してください。また、ここで login_hint クエリ パラメータを処理し、必要に応じてユーザーを認可フローにルーティングする必要があります。このフローについて詳しくは、前のチュートリアルで説明したログイン ガイダンスの詳細をご覧ください。

次に、アイテムタイプに一致する getAddOnContext エンドポイントにリクエストを送信します。

Python

上記の例では、load_content_attachment メソッドの続きです。

# Create an instance of the Classroom service.
classroom_service = googleapiclient.discovery.build(
    serviceName="classroom"
    version="v1",
    discoveryServiceUrl=f"https://classroom.googleapis.com/$discovery/rest?labels=ADD_ONS_ALPHA&key={GOOGLE_API_KEY}",
    credentials=credentials)

# Use the itemType to determine which stream item type the teacher created
match flask.session["itemType"]:
    case "announcements":
        parent = classroom_service.courses().announcements()
    case "courseWorkMaterials":
        parent = classroom_service.courses().courseWorkMaterials()
    case _:
        parent = classroom_service.courses().courseWork()

addon_context_response = parent.getAddOnContext(
    courseId=flask.session["courseId"],
    itemId=flask.session["itemId"]).execute()

このメソッドは、クラス内の現在のユーザーの役割に関する情報を返します。ユーザーの役割に応じて、ユーザーに表示されるビューを変更します。studentContext フィールドまたは teacherContext フィールドのいずれか 1 つのみがレスポンス オブジェクトに入力されます。これらを調べて、お客様への対応方法を判断します。

いずれの場合も、attachmentId クエリ パラメータ値を使用して、データベースから取得するアタッチメントを確認します。このクエリ パラメータは、教師または生徒のビューの URI を開く際に提供されます。

Python

上記の例では、load_content_attachment メソッドの続きです。

# Determine which view we are in by testing the returned context type.
user_context = "student" if addon_context_response.get(
    "studentContext") else "teacher"

# Look up the attachment in the database.
attachment = Attachment.query.get(flask.session["attachmentId"])

# Set the text for the next page depending on the user's role.
message_str = f"I see that you're a {user_context}! "
message_str += (
    f"I've loaded the attachment with ID {attachment.attachment_id}. "
    if user_context == "teacher" else
    "Please enjoy this image of a famous landmark!")

# Show the content with the customized message text.
return flask.render_template(
    "show-content-attachment.html",
    message=message_str,
    image_filename=attachment.image_filename,
    image_caption=attachment.image_caption,
    responses=response_strings)

アドオンをテストする

アタッチメントの作成をテストする手順は次のとおりです。

  • 教師のテストユーザーの 1 人として [Google Classroom] にログインします。
  • [授業] タブに移動し、新しい課題を作成します。
  • テキスト領域の下にある [アドオン] ボタンをクリックし、アドオンを選択します。 iframe が開き、Google Workspace Marketplace SDK の [アプリの構成] ページで指定した添付ファイルの設定 URI がアドオンによって読み込まれます。
  • 課題に添付するコンテンツを選択します。
  • 添付ファイルの作成フローが完了したら、iframe を閉じます。

Google Classroom の課題作成 UI に添付ファイル カードが表示されます。カードをクリックして Teacher View iframe を開き、正しい添付ファイルが表示されることを確認します。[Assign] ボタンをクリックします。

生徒の学習環境をテストする手順は次のとおりです。

  • 次に、教師用テストユーザーと同じクラスの生徒向けテストユーザーとして Classroom にログインします。
  • [授業] タブでテスト用の課題を見つけます。
  • 課題を開き、添付ファイル カードをクリックして Student View iframe を開きます。

生徒に正しい添付ファイルが表示されていることを確認します。

お疲れさまでした。次のステップであるアクティビティ タイプのアタッチメントの作成に進む準備が整いました。