Timeline: insert

Yêu cầu uỷ quyền

Chèn một mục mới vào dòng thời gian. Xem ví dụ.

Phương thức này hỗ trợ URI /upload và chấp nhận nội dung nghe nhìn đã tải lên có các đặc điểm sau:

  • Kích thước tệp tối đa: 10 MB
  • Các loại MIME nội dung đa phương tiện được chấp nhận: image/* , audio/* , video/*

Nếu được cung cấp, nội dung nghe nhìn đã tải lên được chèn dưới dạng tệp đính kèm vào mục dòng thời gian.

Yêu cầu

Yêu cầu HTTP

Phương thức này cung cấp chức năng tải nội dung nghe nhìn lên thông qua hai URI riêng biệt. Để biết thêm thông tin chi tiết, hãy xem tài liệu về tải nội dung nghe nhìn lên.

  • URI tải lên, đối với các yêu cầu tải nội dung nghe nhìn lên:
    POST https://www.googleapis.com/upload/mirror/v1/timeline
  • URI siêu dữ liệu, đối với các yêu cầu chỉ siêu dữ liệu:
    POST https://www.googleapis.com/mirror/v1/timeline

Các tham số

Tên thông số Giá trị Mô tả
Tham số truy vấn bắt buộc
uploadType string Loại yêu cầu tải lên URI /upload. Các giá trị được chấp nhận là:
  • mediaTải lên đơn giản. Chỉ tải nội dung nghe nhìn lên mà không cần siêu dữ liệu.
  • multipartTải nhiều phần lên. Tải cả phương tiện và siêu dữ liệu lên trong một yêu cầu duy nhất.
  • resumableTải lên tiếp nối. Tải tệp lên theo cách tiếp nối, sử dụng một loạt ít nhất hai yêu cầu trong đó yêu cầu đầu tiên chứa siêu dữ liệu.

Ủy quyền

Yêu cầu này yêu cầu uỷ quyền có ít nhất một trong các phạm vi sau (đọc thêm về xác thực và cấp phép).

Phạm vi
https://www.googleapis.com/auth/glass.timeline
https://www.googleapis.com/auth/glass.location

Nội dung yêu cầu

Trong phần nội dung yêu cầu, hãy cung cấp tài nguyên Dòng thời gian với các thuộc tính sau làm siêu dữ liệu. Để biết thêm thông tin, hãy xem tài liệu về việc tải nội dung nghe nhìn lên.

Tên tài sản Giá trị Mô tả Ghi chú
Thuộc tính không bắt buộc
bundleId string Mã nhận dạng gói cho mặt hàng này. Các dịch vụ có thể chỉ định bundleId để nhóm nhiều mục với nhau. Chúng xuất hiện trong một mục cấp cao nhất trên thiết bị. có thể ghi
canonicalUrl string URL chính tắc trỏ đến phiên bản dữ liệu chính tắc/chất lượng cao của dữ liệu do mục trong dòng thời gian biểu thị. có thể ghi
creator nested object Người dùng hoặc nhóm đã tạo mục này. có thể ghi
displayTime datetime Thời gian hiển thị khi mục này được xem trong tiến trình, có định dạng theo RFC 3339. Dòng thời gian của người dùng này được sắp xếp theo thời gian hiển thị, do đó, giá trị này cũng sẽ xác định vị trí mục hiển thị trong dòng thời gian. Nếu dịch vụ không đặt, thời gian hiển thị mặc định là thời gian updated. có thể ghi
html string Nội dung HTML cho mục này. Nếu bạn cung cấp cả texthtml cho một mục, thì html sẽ xuất hiện trong tiến trình.

Các phần tử HTML được phép – Bạn có thể sử dụng các phần tử này trong thẻ dòng thời gian của mình.

  • Tiêu đề: h1, h2, h3, h4, h5, h6
  • Hình ảnh: img
  • Danh sách: li, ol, ul
  • Ngữ nghĩa HTML5: article, aside, details, figure, figcaption, footer, header, nav, section, summary, time
  • Cấu trúc: blockquote, br, div, hr, p, span
  • Kiểu: b, big, center, em, i, u, s, small, strike, strong, style, sub, sup
  • Bảng: table, tbody, td, tfoot, th, thead, tr

Các phần tử HTML bị chặn: Các phần tử này và nội dung của các phần tử này sẽ bị xóa khỏi trọng tải HTML.

  • Tiêu đề tài liệu: head, title
  • Các video nhúng: audio, embed, object, source, video
  • Khung hình: frame, frameset
  • Tập lệnh: applet, script

Các phần tử khác: Mọi phần tử không được liệt kê sẽ bị xóa nhưng nội dung của chúng vẫn được giữ nguyên.

có thể ghi
isBundleCover boolean Liệu mặt hàng này có phải là vỏ bọc theo gói hay không.

Nếu một mục được đánh dấu là bìa gói, thì mục đó sẽ là điểm truy cập vào gói mục có cùng bundleId với mục đó. Dòng thời gian sẽ chỉ hiển thị trên dòng thời gian chính — không nằm trong gói đã mở.

Trên dòng thời gian chính, các mục sẽ xuất hiện là:
  • Đã đặt các mục trong isBundleCover thành true
  • Các mục không có bundleId
Trong dòng thời gian phụ của gói, các mục hiển thị là:
  • Các mục có bundleId được đề cập AND isBundleCover được đặt thành false
có thể ghi
location nested object Vị trí địa lý liên kết với mục này. có thể ghi
notification nested object Kiểm soát cách hiển thị thông báo cho mục này trên thiết bị. Nếu thiếu thông tin này, hệ thống sẽ không tạo thông báo. có thể ghi
notification.deliveryTime datetime Thời gian gửi thông báo. có thể ghi
notification.level string Mô tả mức độ quan trọng của thông báo. Các giá trị được cho phép là:
  • DEFAULT – Thông báo về mức độ quan trọng mặc định. Chuông sẽ được phát để báo cho người dùng.
có thể ghi
recipients[] list Danh sách người dùng hoặc nhóm mà mục này đã được chia sẻ. có thể ghi
sourceItemId string Chuỗi mờ mà bạn có thể sử dụng để ánh xạ mục dòng thời gian với dữ liệu trong dịch vụ của riêng bạn. có thể ghi
speakableText string Phiên bản nói của nội dung của mục này. Cùng với mục menu READ_ALOUD, hãy sử dụng trường này để cung cấp văn bản rõ ràng hơn khi đọc to hoặc để cung cấp thông tin mở rộng cho nội dung hiển thị trực quan trên Glass.

Glassware cũng phải chỉ định trường speakableType. Trường này sẽ được đọc trước văn bản này trong trường hợp có ngữ cảnh bổ sung hữu ích, chẳng hạn như khi người dùng yêu cầu đọc to mục này sau một thông báo.
có thể ghi
speakableType string Mô tả rõ ràng về loại mục này. Hệ thống sẽ thông báo cho người dùng trước khi đọc nội dung của mục trong trường hợp có thêm ngữ cảnh hữu ích, chẳng hạn như khi người dùng yêu cầu đọc to mục đó sau một thông báo.

Đây phải là một cụm danh từ ngắn, đơn giản như "Email", "Tin nhắn văn bản" hoặc "Tin tức cập nhật hằng ngày về hành tinh".

Chúng tôi khuyến khích người dùng điền vào trường này cho mọi mục trên dòng thời gian, ngay cả khi mục đó không chứa speakableText hoặc văn bản để người dùng có thể tìm hiểu loại mục đó mà không cần nhìn vào màn hình.
có thể ghi
text string Nội dung văn bản của mục này. có thể ghi
title string Tiêu đề của mục này. có thể ghi

Phản hồi

Nếu thành công, phương thức này sẽ trả về một Tài nguyên dòng thời gian trong nội dung phản hồi.

Ví dụ

Lưu ý: Các đoạn mã mẫu của phương thức này không phải là ví dụ cho mọi ngôn ngữ lập trình được hỗ trợ (xem trang thông tin về các thư viện dùng cho ứng dụng để biết danh sách các ngôn ngữ được hỗ trợ).

Java

Sử dụng thư viện ứng dụng 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

Sử dụng thư viện ứng dụng .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

Sử dụng thư viện ứng dụngPHP.

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

Sử dụng thư viện ứng dụng 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

Sử dụng thư viện ứng dụng 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

Sử dụng Thư viện ứng dụng 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 thô

Không sử dụng thư viện ứng dụng.

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