Timeline: insert

認証が必要です

新しいアイテムをタイムラインに挿入します。 例を見る

このメソッドは、/upload URI に対応し、次の特徴のメディアを受け入れます。

  • 最大ファイルサイズ: 10MB
  • 使用可能なメディア MIME タイプ: image/*audio/*video/*

指定した場合、アップロードしたメディアはタイムライン アイテムに添付ファイルとして挿入されます。

リクエスト

HTTP リクエスト

このメソッドは、2 つの異なる URI を使用してメディア アップロード機能を提供します。詳しくは、メディア アップロードに関するドキュメントをご覧ください。

  • メディア アップロード リクエストのアップロード URI:
    POST https://www.googleapis.com/upload/mirror/v1/timeline
  • メタデータ URI(メタデータのみのリクエスト):
    POST https://www.googleapis.com/mirror/v1/timeline

パラメータ

パラメータ名 説明
必須のクエリ パラメータ
uploadType string /upload URI へのアップロード リクエストのタイプ。 有効な値は次のとおりです。
  • media - シンプルなアップロード。メタデータのないメディアのみをアップロードします。
  • multipart - マルチパート アップロード。1 つのリクエストでメディアとメタデータの両方をアップロードします。
  • resumable - 再開可能なアップロード。再開可能な方法でファイルをアップロードします。2 つ以上の連続するリクエストを使用します。最初のリクエストでメタデータを送信します。

承認

このリクエストは、少なくとも次のうち 1 つのスコープでの承認が必要です(認証と承認の詳細をご確認ください)。

範囲
https://www.googleapis.com/auth/glass.timeline
https://www.googleapis.com/auth/glass.location

リクエスト本文

リクエストの本文には、以下のプロパティをメタデータとしてタイムライン リソースを指定します。詳しくは、メディア アップロードに関するドキュメントをご覧ください。

プロパティ名 説明 備考
省略可能なプロパティ
bundleId string この商品アイテムのバンドル ID。サービスでは bundleId を指定して、多数のアイテムをグループ化できます。デバイス上の 1 つの最上位のアイテムの下に表示されます。 書き込み可能
canonicalUrl string タイムライン アイテムによって表されるデータの正規バージョンまたは高画質バージョンを指す正規 URL。 書き込み可能
creator nested object このアイテムを作成したユーザーまたはグループ。 書き込み可能
displayTime datetime このアイテムをタイムラインで表示したときに表示する時刻を、RFC 3339 の形式で指定します。ユーザーのタイムラインは、表示時間順に時系列の順に表示されます。これにより、タイムライン内でアイテムが表示される場所も決定されます。サービスによって設定されていない場合、表示時間はデフォルトで updated 時間になります。 書き込み可能
html string このアイテムの HTML コンテンツ。アイテムに texthtml の両方が指定されている場合、html がタイムラインにレンダリングされます。

許可されている HTML 要素 - これらの要素はタイムライン カードで使用できます。

  • ヘッダー: h1, h2, h3, h4, h5, h6
  • 画像: img
  • リスト: li, ol, ul
  • HTML5 セマンティクス: article, aside, details, figure, figcaption, footer, header, nav, section, summary, time
  • 構造: blockquote, br, div, hr, p, span
  • スタイル: b, big, center, em, i, u, s, small, strike, strong, style, sub, sup
  • テーブル: table, tbody, td, tfoot, th, thead, tr

ブロックされた HTML 要素: これらの要素とその内容は HTML ペイロードから削除されます。

  • ドキュメント ヘッダー: head, title
  • 埋め込み: audio, embed, object, source, video
  • フレーム: frame, frameset
  • スクリプト: applet, script

その他の要素: リストにない要素は削除されますが、その内容は保持されます。

書き込み可能
isBundleCover boolean この商品が一括販売商品かどうか

一括販売商品として指定された項目は、bundleId と同じ商品を含む一括販売商品へのエントリ ポイントとなります。メイン タイムラインにのみ表示されます。開いたバンドル内には表示されません

メインのタイムラインでは、次の項目が表示されます。
  • isBundleCovertrueに設定されているアイテム
  • bundleId のないアイテム
一括販売のサブタイムラインに表示される項目は次のとおりです。
  • 問題の bundleId isBundleCoverfalse に設定されているアイテム
書き込み可能
location nested object このアイテムに関連付けられている地域。 書き込み可能
notification nested object このアイテムに関する通知をデバイスに表示する方法を制御します。通知がない場合は、通知は生成されません。 書き込み可能
notification.deliveryTime datetime 通知の配信時刻。 書き込み可能
notification.level string 通知の重要度を示します。指定できる値は次のとおりです。
  • DEFAULT - デフォルトの重要度の通知。チャイムが鳴ってユーザーに警告します。
書き込み可能
recipients[] list このアイテムが共有されているユーザーまたはグループのリスト。 書き込み可能
sourceItemId string タイムライン アイテムを独自のサービス内のデータにマッピングするために使用できる不透明な文字列。 書き込み可能
speakableText string このアイテムのコンテンツの読み上げバージョン。READ_ALOUD メニュー項目とともに、このフィールドを使用して、読み上げたときによりクリアなテキストを表示するか、Glass で視覚的に表示されるものに関する詳細情報を提供します。

Glassware では、speechableType フィールドも指定する必要があります。これは、通知後にアイテムが読み上げられることをユーザーがリクエストした場合など、追加のコンテキストが役立つ場合に、このテキストの前に読み上げられます。
書き込み可能
speakableType string このアイテムのタイプに関する説明を表示します。通知の後でアイテムが読み上げられることをユーザーがリクエストした場合など、追加のコンテキストが役立つ場合は、アイテムの内容を読む前にユーザーに通知が届きます。

「メール」、「テキスト メッセージ」、「今日の惑星ニュースの更新」など、短い名詞句にする必要があります。

Glassware では、スピーディなテキストやテキストが含まれていない場合でも、タイムライン アイテムごとにこのフィールドに値を設定することをおすすめします。これにより、ユーザーは画面を見なくてもアイテムのタイプを把握できます。
書き込み可能
text string このアイテムのテキスト コンテンツ。 書き込み可能
title string このアイテムのタイトル。 書き込み可能

レスポンス

成功すると、このメソッドはレスポンスの本文で Timeline リソースを返します。

注: このメソッドで使用可能なコード例では、サポートされているプログラミング言語すべての例を示しているわけではありません(サポートされている言語の一覧については、クライアント ライブラリ ページをご覧ください)。

Java

Java クライアント ライブラリを使用します。

import com.google.api.client.http.InputStreamContent;
import com.google.api.services.mirror.Mirror;
import com.google.api.services.mirror.model.NotificationConfig;
import com.google.api.services.mirror.model.TimelineItem;

import java.io.IOException;
import java.io.InputStream;

public class MyClass {
  // ...

  /**
   * Insert a new timeline item in the user's glass with an optional
   * notification and attachment.
   * 
   * @param service Authorized Mirror service.
   * @param text timeline item's text.
   * @param contentType Optional attachment's content type (supported content
   *        types are "image/*", "video/*" and "audio/*").
   * @param attachment Optional attachment stream.
   * @param notificationLevel Optional notification level, supported values are
   *        {@code null} and "AUDIO_ONLY".
   * @return Inserted timeline item on success, {@code null} otherwise.
   */
  public static TimelineItem insertTimelineItem(Mirror service, String text, String contentType,
      InputStream attachment, String notificationLevel) {
    TimelineItem timelineItem = new TimelineItem();
    timelineItem.setText(text);
    if (notificationLevel != null && notificationLevel.length() > 0) {
      timelineItem.setNotification(new NotificationConfig().setLevel(notificationLevel));
    }
    try {
      if (contentType != null && contentType.length() > 0 && attachment != null) {
        // Insert both metadata and attachment.
        InputStreamContent mediaContent = new InputStreamContent(contentType, attachment);
        return service.timeline().insert(timelineItem, mediaContent).execute();
      } else {
        // Insert metadata only.
        return service.timeline().insert(timelineItem).execute();
      }
    } catch (IOException e) {
      System.err.println("An error occurred: " + e);
      return null;
    }
  }

  // ...
}

.NET

.NET クライアント ライブラリを使用します。

using System;
using System.IO;

using Google.Apis.Mirror.v1;
using Google.Apis.Mirror.v1.Data;

public class MyClass {
  // ...

  /// <summary>
  /// Insert a new timeline item in the user's glass with an optional
  /// notification and attachment.
  /// </summary>
  /// <param name='service'>Authorized Mirror service.</param>
  /// <param name='text'>Timeline Item's text.</param>
  /// <param name='contentType'>
  /// Optional attachment's content type (supported content types are
  /// "image/*", "video/*" and "audio/*").
  /// </param>
  /// <param name='attachment'>Optional attachment stream</param>
  /// <param name='notificationLevel'>
  /// Optional notification level, supported values are null and
  /// "AUDIO_ONLY".
  /// </param>
  /// <returns>
  /// Inserted timeline item on success, null otherwise.
  /// </returns>
  public static TimelineItem InsertTimelineItem(MirrorService service,
      String text, String contentType, Stream attachment,
      String notificationLevel) {
    TimelineItem timelineItem = new TimelineItem();
    timelineItem.Text = text;
    if (!String.IsNullOrEmpty(notificationLevel)) {
      timelineItem.Notification = new NotificationConfig() {
        Level = notificationLevel
      };
    }
    try {
      if (!String.IsNullOrEmpty(contentType) && attachment != null) {
        // Insert both metadata and media.
        TimelineResource.InsertMediaUpload request = service.Timeline.Insert(
            timelineItem, attachment, contentType);
        request.Upload();
        return request.ResponseBody;
      } else {
        // Insert metadata only.
        return service.Timeline.Insert(timelineItem).Fetch();
      }
    } catch (Exception e) {
      Console.WriteLine("An error occurred: " + e.Message);
      return null;
    }
  }

  // ...
}

PHP

PHP クライアント ライブラリを使用します。

/**
 * Insert a new timeline item in the user's glass with an optional
 * notification and attachment.
 *
 * @param Google_MirrorService $service Authorized Mirror service.
 * @param string $text timeline item's text.
 * @param string $contentType Optional attachment's content type (supported
 *                            content types are "image/*", "video/*"
 *                            and "audio/*").
 * @param string $attachment Optional attachment content.
 * @param string $notificationLevel Optional notification level,
 *                                  supported values are {@code null}
 *                                  and "AUDIO_ONLY".
 * @return Google_TimelineItem Inserted timeline item on success, otherwise.
 */
function insertTimelineItem($service, $text, $contentType, $attachment,
                            $notificationLevel) {
  try {
    $timelineItem = new Google_TimelineItem();
    $timelineItem->setText($text);
    if ($notificationlevel != null) {
      $notification = new Google_NotificationConfig();
      $notification->setLevel($notificationLevel);
      $timelineItem->setNotification($notification);
    }
    $optParams = array();
    if ($contentType != null && $attachment != null) {
      $optParams['data'] = $attachment;
      $optParams['mimeType'] = $contentType;
    }
    return $service->timeline->insert($timelineItem, $optParams);
  } catch (Exception $e) {
    print 'An error occurred: ' . $e->getMessage();
    return null;
  }
}

Python

Python クライアント ライブラリを使用します。

import io

from apiclient import errors
from apiclient.http import MediaIoBaseUpload
# ...

def insert_timeline_item(service, text, content_type=None, attachment=None,
                         notification_level=None):
  """Insert a new timeline item in the user's glass.

  Args:
    service: Authorized Mirror service.
    text: timeline item's text.
    content_type: Optional attachment's content type (supported content types
                  are 'image/*', 'video/*' and 'audio/*').
    attachment: Optional attachment as data string.
    notification_level: Optional notification level, supported values are None
                        and 'AUDIO_ONLY'.

  Returns:
    Inserted timeline item on success, None otherwise.
  """
  timeline_item = {'text': text}
  media_body = None
  if notification_level:
    timeline_item['notification'] = {'level': notification_level}
  if content_type and attachment:
    media_body = MediaIoBaseUpload(
        io.BytesIO(attachment), mimetype=content_type, resumable=True)
  try:
    return service.timeline().insert(
        body=timeline_item, media_body=media_body).execute()
  except errors.HttpError, error:
    print 'An error occurred: %s' % error

Ruby

Ruby クライアント ライブラリを使用します。

##
# Insert a new Timeline Item in the user's glass.
#
# @param [Google::APIClient] client
#   Authorized client instance.
# @param [String] text
#   Timeline item's text.
# @param [String] content_type
#   Optional attachment's content type (supported content types are 'image/*',
#   'video/*' and 'audio/*').
# @param [String] filename
#   Optional attachment's filename.
# @param [String] notification_level
#   Optional notification level, supported values are nil and 'AUDIO_ONLY'.
# @return [Google::APIClient::Schema::Mirror::V1::TimelineItem]
#   Timeline item instance if successful, nil otherwise.
def insert_timeline_item(client, text, content_type, filename,
                         notification_level)
  mirror = client.discovered_api('mirror', 'v1')
  timeline_item = mirror.timeline.insert.request_schema.new({ 'text' => text })
  if notification_level
    timeline_item.notification = { 'level' => notification_level }
  end
  result = nil
  if filename
    media = Google::APIClient::UploadIO.new(filename, content_type)
    result = client.execute(
      :api_method => mirror.timeline.insert,
      :body_object => timeline_item,
      :media => media,
      :parameters => {
        'uploadType' => 'multipart',
        'alt' => 'json'})
  else
    result = client.execute(
      :api_method => mirror.timeline.insert,
      :body_object => timeline_item)
  end
  if result.success?
    return result.data
  else
    puts "An error occurred: #{result.data['error']['message']}"
  end
end

Go

Go クライアント ライブラリを使用します。

import (
	"code.google.com/p/google-api-go-client/mirror/v1"
	"fmt"
	"io"
)

// InsertTimelineItem inserts a new timeline item in the user's glass with an
// optional notification and attachment.
func InsertTimelineItem(g *mirror.Service, text string, attachment io.Reader,
	notificationLevel string) (*mirror.TimelineItem, error) {
	t := &mirror.TimelineItem{Text: text}
	if notificationLevel != "" {
		t.Notification = &mirror.NotificationConfig{Level: notificationLevel}
	}
	req := g.Timeline.Insert(t)
	if attachment != nil {
		// Add attachment to the timeline item.
		req.Media(attachment)
	}
	r, err := req.Do()
	if err != nil {
		fmt.Printf("An error occurred: %v\n", err)
		return nil, err
	}
	return r, nil
}

未加工の HTTP

クライアント ライブラリは使用しません。

## A very simple timeline item

POST /mirror/v1/timeline HTTP/1.1
Host: www.googleapis.com
Authorization: Bearer auth token
Content-Type: application/json
Content-Length: 26

{ "text": "Hello world" }

## A more complete timeline item with an attachment

POST /mirror/v1/timeline HTTP/1.1
Host: www.googleapis.com
Authorization: Bearer auth token
Content-Type: multipart/related; boundary="mymultipartboundary"
Content-Length: length

--mymultipartboundary
Content-Type: application/json; charset=UTF-8

{
 "text": "Hello world",
 "menuItems": [
   { "action": "REPLY" },
   {
     "action": "CUSTOM",
     "id": "complete"
     "values": [{
       "displayName": "Complete",
       "iconUrl": "http://example.com/icons/complete.png"
     }]
   }
}
--mymultipartboundary
Content-Type: image/jpeg
Content-Transfer-Encoding: binary

binary image data
--mymultipartboundary--