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

请求正文

在请求正文中,提供具有以下属性的时间轴资源。如需了解详情,请参阅有关媒体上传的文档。

属性名称 说明 备注
可选属性
bundleId string 此内容的软件包 ID。服务可以指定 bundleId 以将许多项组合在一起。它们显示在设备上的单个顶级项下。 可写入
canonicalUrl string 指向由时间轴项表示的规范/高质量版本的规范网址。 可写入
creator nested object 创建此内容的用户或群组。 可写入
displayTime datetime 当在时间轴中查看此商品时显示的时间,采用 RFC 3339 格式。该用户的时间轴按展示时间排序,这也决定了该内容在时间轴中的显示位置。如果未通过服务设置,则显示时间默认为 updated 时间。 可写入
html string 此内容的 HTML 内容。如果同时为内容提供了 texthtmlhtml 将在时间轴中呈现。

允许使用的 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 的内容集的入口点。它只会显示在主时间轴上,不会显示在打开的集合中

主时间轴上会显示以下内容:
  • 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 此项目类型的可朗读说明。如果附加上下文有用(例如,用户要求在通知后朗读某个项),系统会在读取内容之前通知用户。

这应为简短名词短语,例如“Email”、“Text message”或“Daily Planet News Update”。

建议为每项时间轴项(即使项不包含 SpeakableText 或文本)填写 Glassware 这个字段,这样用户不必查看屏幕也能了解项的类型。
可写入
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--