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 - 재개 가능한 업로드. 첫 번째 요청에 메타데이터가 포함된 일련의 요청을 2개 이상 사용하여 재개 가능한 방식으로 파일을 업로드합니다.

확인할 내용

이 요청에는 다음 범위 중 최소 하나를 사용하여 인증이 필요합니다. (인증 및 승인에 대해 자세히 알아보기)

범위
https://www.googleapis.com/auth/glass.timeline
https://www.googleapis.com/auth/glass.location

요청 본문

요청 본문에서 다음 속성을 메타데이터로 포함하는 타임라인 리소스를 제공합니다. 자세한 내용은 미디어 업로드 문서를 참조하세요.

숙소 이름 설명 메모
선택 속성
bundleId string 이 항목의 번들 ID입니다. 서비스는 번들 ID를 지정하여 여러 항목을 그룹화할 수 있습니다. 기기의 단일 최상위 항목 아래에 표시됩니다. 쓰기 가능
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과 동일한 번들에 대한 진입점이 됩니다. 열린 번들이 아닌 기본 타임라인에만 표시됩니다.

기본 타임라인에 표시되는 항목은 다음과 같습니다.
  • 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 string 항목 유형에 대한 음성 안내입니다. 이는 추가 문맥이 유용한 경우(예: 사용자가 알림 후 항목을 소리내어 읽도록 요청하는 경우) 항목의 콘텐츠를 읽기 전에 사용자에게 안내됩니다.

'이메일', '문자 메시지' 또는 '일일 플래닛 뉴스 업데이트'와 같은 짧고 간단한 명사구여야 합니다.

사용자가 페이지를 보지 않고도 항목 유형을 학습할 수 있도록, 말합니다. 항목에 SpeakeasyableText 또는 텍스트가 포함되어 있지 않더라도 Glass 소프트웨어는 이 필드를 모든 타임라인 항목에 채우는 것이 좋습니다.
쓰기 가능
text string 이 항목의 텍스트 콘텐츠입니다. 쓰기 가능
title string 이 항목의 제목입니다. 쓰기 가능

응답

요청에 성공할 경우 이 메서드는 응답 본문에 타임라인 리소스를 반환합니다.

참고: 이 메서드에 제공되는 코드 예시가 지원되는 모든 프로그래밍 언어를 나타내는 것은 아닙니다. 지원되는 언어 목록은 클라이언트 라이브러리 페이지를 참조하세요.

자바

자바 클라이언트 라이브러리를 사용합니다.

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