Timeline: insert

Autorisierung erforderlich

Fügt ein neues Element in die Zeitachse ein. Beispiel ansehen

Diese Methode unterstützt einen /upload-URI und akzeptiert hochgeladene Medien mit den folgenden Eigenschaften:

  • Maximale Dateigröße:10 MB
  • Zulässige Medien-MIME-Typen: image/* , audio/* , video/*

Wenn angegeben, werden die hochgeladenen Medien als Anhang an das Zeitachsenelement eingefügt.

Anfrage

HTTP-Anfrage

Diese Methode bietet Funktionen zum Hochladen von Medien über zwei separate URIs. Weitere Informationen finden Sie im Dokument zum Medien-Upload.

  • Upload-URI für Anfragen zum Hochladen von Medien:
    POST https://www.googleapis.com/upload/mirror/v1/timeline
  • Metadaten-URI für reine Metadatenanfragen:
    POST https://www.googleapis.com/mirror/v1/timeline

Parameter

Parametername Wert Beschreibung
Erforderliche Abfrageparameter
uploadType string Die Art der Uploadanfrage an den /upload-URI. Zulässige Werte sind: <ph type="x-smartling-placeholder">
    </ph>
  • media: Einfacher Upload. Laden Sie nur die Medien ohne Metadaten hoch.
  • multipartMehrteiliger Upload. Laden Sie sowohl die Medien als auch die zugehörigen Metadaten in einer Anfrage hoch.
  • resumableFortsetzbarer Upload. Laden Sie die Datei fortsetzbar mit einer Reihe von mindestens zwei Anfragen hoch, wobei die erste Anfrage die Metadaten enthält.

Autorisierung

Diese Anfrage benötigt eine Autorisierung mit mindestens einem der folgenden Bereiche (weitere Informationen zu Authentifizierung und Autorisierung).

Bereich
https://www.googleapis.com/auth/glass.timeline
https://www.googleapis.com/auth/glass.location

Anfragetext

Geben Sie im Anfragetext eine Zeitachsenressource mit den folgenden Eigenschaften als Metadaten an. Weitere Informationen finden Sie im Dokument zum Medien-Upload.

Property-Name Wert Beschreibung Hinweise
Optionale Attribute
bundleId string Die Paket-ID für diesen Artikel. Dienste können eine Bundle-ID angeben, um mehrere Elemente zu gruppieren. Sie werden auf dem Gerät unter einem einzelnen Element auf der obersten Ebene angezeigt. Bearbeitbar
canonicalUrl string Eine kanonische URL, die auf die kanonische bzw. hochwertige Version der Daten verweist, die vom Zeitachsenelement dargestellt werden. Bearbeitbar
creator nested object Der Nutzer oder die Gruppe, die dieses Element erstellt hat. Bearbeitbar
displayTime datetime Die Zeit, die angezeigt werden soll, wenn dieses Element in der Zeitachse angezeigt wird, formatiert gemäß RFC 3339. Die Zeitachse dieses Nutzers ist nach Anzeigezeit chronologisch sortiert. Dadurch wird auch festgelegt, wo das Element in der Zeitachse angezeigt wird. Wenn der Dienst nicht festgelegt wurde, wird standardmäßig die Anzeigezeit updated verwendet. Bearbeitbar
html string HTML-Inhalt für dieses Element. Wenn für ein Element sowohl text als auch html angegeben werden, wird html auf der Zeitachse gerendert.

Zulässige HTML-Elemente: Sie können diese Elemente in Ihren Zeitachsenkarten verwenden.

  • Überschriften: h1, h2, h3, h4, h5, h6
  • Bilder: img
  • Listen: li, ol, ul
  • HTML5-Semantik: article, aside, details, figure, figcaption, footer, header, nav, section, summary, time
  • Strukturell: blockquote, br, div, hr, p, span
  • Stil: b, big, center, em, i, u, s, small, strike, strong, style, sub, sup
  • Tabellen: table, tbody, td, tfoot, th, thead, tr

Blockierte HTML-Elemente: Diese Elemente und ihr Inhalt werden aus HTML-Nutzlasten entfernt.

  • Dokumentüberschriften: head, title
  • Einbettungen: audio, embed, object, source, video
  • Rahmen: frame, frameset
  • Scripting: applet, script

Andere Elemente: Nicht aufgeführte Elemente werden entfernt, ihr Inhalt bleibt jedoch erhalten.

Bearbeitbar
isBundleCover boolean Gibt an, ob es sich bei diesem Artikel um eine Set-Abdeckung handelt.

Wenn ein Artikel als Set-Cover markiert ist, ist er der Einstiegspunkt für das Set mit Artikeln, die dieselbe bundleId haben wie dieser Artikel. Sie wird nur auf der Hauptzeitachse angezeigt, nicht im geöffneten Set.

Auf der Hauptzeitachse werden folgende Elemente angezeigt:
  • Elemente, für die „isBundleCover“ auf „true“ festgelegt ist
  • Artikel ohne bundleId
In einer Paket-Unterzeitachse werden folgende Elemente angezeigt:
  • Artikel, bei denen die betreffende bundleId UND isBundleCover auf false festgelegt ist
Bearbeitbar
location nested object Der mit diesem Element verknüpfte geografische Standort. Bearbeitbar
notification nested object Steuert, wie Benachrichtigungen für dieses Element auf dem Gerät angezeigt werden. Fehlt diese Angabe, wird keine Benachrichtigung generiert. Bearbeitbar
notification.deliveryTime datetime Der Zeitpunkt, zu dem die Benachrichtigung zugestellt werden soll. Bearbeitbar
notification.level string Beschreibt, wie wichtig die Benachrichtigung ist. Zulässige Werte:
  • DEFAULT: Benachrichtigungen von standardmäßiger Wichtigkeit. Nutzer werden durch einen Glockenton gewarnt.
Bearbeitbar
recipients[] list Eine Liste der Nutzer oder Gruppen, für die dieses Element freigegeben wurde. Bearbeitbar
sourceItemId string Undurchsichtiger String, mit dem Sie ein Zeitachsenelement Daten in Ihrem eigenen Dienst zuordnen können. Bearbeitbar
speakableText string Die vorlesbare Version des Inhalts dieses Elements. Verwenden Sie dieses Feld zusammen mit dem Menüpunkt READ_ALOUD für Text, der beim Vorlesen klarer ist, oder um ausführlichere Informationen zu den in Glass angezeigten Inhalten bereitzustellen.

Glassware sollte außerdem das Feld „SpeakableType“ angeben, das vor diesem Text vorgelesen wird, wenn der zusätzliche Kontext nützlich ist, z. B. wenn der Nutzer das Vorlesen des Elements nach einer Benachrichtigung anfordert.
Bearbeitbar
speakableType string Eine vorlesbare Beschreibung des Elementtyps. Dies wird dem Nutzer vor dem Lesen des Inhalts angezeigt, wenn der zusätzliche Kontext nützlich ist, z. B. wenn der Nutzer das Vorlesen des Artikels nach einer Benachrichtigung anfordert.

Dies sollte eine kurze, einfache Nominalphrase wie „Email“, „SMS“ oder „Daily Planet News Update“ sein.

Glassware wird empfohlen, dieses Feld für jedes Zeitachsenelement auszufüllen, auch wenn das Element keinen readableText oder Text enthält. So können Nutzer den Typ des Elements kennenlernen, ohne auf den Bildschirm sehen zu müssen.
Bearbeitbar
text string Textinhalt dieses Elements. Bearbeitbar
title string Der Titel dieses Elements. Bearbeitbar

Antwort

Wenn der Vorgang erfolgreich ist, wird mit dieser Methode eine Zeitachsenressource im Antworttext zurückgegeben.

Beispiele

Hinweis: Bei den für diese Methode verfügbaren Codebeispielen sind nicht alle unterstützten Programmiersprachen vertreten. Eine Liste der unterstützten Sprachen finden Sie auf der Seite für Clientbibliotheken.

Java

Verwendet die Java-Clientbibliothek.

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

Verwendet die .NET-Clientbibliothek.

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

Verwendet die PHP-Clientbibliothek.

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

Verwendet die Python-Clientbibliothek.

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

Verwendet die Ruby-Clientbibliothek.

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

Ok

Verwendet die Go-Clientbibliothek.

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

Verwendet keine Clientbibliothek.

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