Timeline: insert

需要授權

在時間軸中插入新項目。 參閲範例

這個方法支援 /upload URI,並接受具備下列特性的上傳的媒體:

  • 檔案大小上限:10MB
  • 系統接受的媒體 MIME 類型: image/* , audio/* , video/*

如果提供的話,系統會將上傳的媒體做為時間軸項目附件插入。

要求

HTTP 要求

此方法可透過兩個獨立的 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 - 多部分上傳。透過單一要求上傳媒體及其中繼資料。
  • resumable - 支援繼續上傳。使用可恢復的方式上傳檔案,使用至少兩個請求 (第一個要求包含中繼資料) 的請求。

授權

此要求需要至少具備下列其中一個範圍的授權 (進一步瞭解驗證和授權)。

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

要求主體

在要求內容中,請提供具有以下屬性的時間軸資源做為中繼資料。如需更多資訊,請參閱媒體上傳文件。

資源名稱 說明 Notes
選填屬性
bundleId string 此商品的套裝組合編號。服務可以指定 BundleId 來將多個項目分組。這些項目會顯示在裝置上的單一頂層項目下方。 可寫入
canonicalUrl string 標準網址,可指向時間軸項目所代表資料的標準/高品質版本。 可寫入
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 這個項目是否為套裝組合的封面。
。這項資訊只會在主要時間軸上顯示,而不會顯示在公開的套件中

主要時間軸顯示的是:
  • isBundleCover的項目已設為true
  • 沒有 bundleId 的項目
在套裝組合子時間軸中,顯示的項目為:
  • 具有相關bundleId項目的 isBundleCover 已設為 false 的項目
可寫入
location nested object 與這個項目相關聯的地理位置。 可寫入
notification nested object 控制這個項目在裝置上顯示方式。如果缺少此資訊,系統就不會產生通知。 可寫入
notification.deliveryTime datetime 通知的傳送時間。 可寫入
notification.level string 說明通知的重要性。有效值如下:
  • DEFAULT - 預設重要性的通知。系統會發出鈴聲,提醒使用者。
可寫入
recipients[] list 共用此項目的使用者或群組清單。 可寫入
sourceItemId string 不透明字串可用於將時間軸項目對應至自有服務中的資料。 可寫入
speakableText string 這個項目的口說版本。除了使用 READ_ALOUD 選單項目之外,您也可以使用這個欄位來提供文字,讓文字更清楚易讀,或針對 Glass 的視覺顯示提供額外資訊。

Glassware 也應指定「SpeakableType」欄位,如果額外的背景資訊有所幫助,例如這段文字會在使用者於通知後要求系統朗讀項目時發出通知。
可寫入
speakableType string 此項目類型的口說方式說明。在使用者要讀取項目內容前,系統會先向使用者說明這類情況,如果其他情況有所幫助,例如使用者在要求通知後,系統就會朗讀該項目。



建議 Google Glass 軟體在各個時間軸項目中填入這個欄位,即使該項目不包含口頭文字或文字,使用者也能在不看螢幕的情況下學習項目類型。
可寫入
text string 此項目的文字內容。 可寫入
title string 此商品的名稱。 可寫入

回應

如果成功,此方法會在回應主體中傳回時間軸資源

範例

注意:這個方法適用的程式語言眾多,我們只在此提供部分程式碼範例,完整的支援語言清單請參閱用戶端程式庫頁面

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--