Timeline: update

Wymaga autoryzacji

Aktualizuje element na osi czasu. Zobacz przykład

Ta metoda obsługuje identyfikator URI /upload i akceptuje przesyłane multimedia o następujących cechach:

  • Maksymalny rozmiar pliku: 10 MB
  • Akceptowane typy MIME multimediów: audio/*, image/*, video/*

Żądanie

Żądanie HTTP

Ta metoda umożliwia przesyłanie multimediów za pomocą 2 oddzielnych identyfikatorów URI. Więcej informacji znajdziesz w artykule na temat przesyłania multimediów.

  • Identyfikator URI przesyłanych żądań multimediów:
    PUT https://www.googleapis.com/upload/mirror/v1/timeline/id
  • Identyfikator URI metadanych dotyczących żądań z samymi metadanymi:
    PUT https://www.googleapis.com/mirror/v1/timeline/id

Parametry

Nazwa parametru Wartość Opis
Parametry ścieżki
id string Identyfikator elementu na osi czasu.
Wymagane parametry zapytania
uploadType string Typ żądania przesyłania do identyfikatora URI /upload. Akceptowane wartości to:

Upoważnienie

To żądanie wymaga autoryzacji z co najmniej jednym z poniższych zakresów (więcej informacji o uwierzytelnianiu i autoryzacji).

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

Treść żądania

W treści żądania jako zasób podaj oś czasu z tymi właściwościami. Więcej informacji znajdziesz w dokumencie dotyczącym przesyłania multimediów.

Nazwa usługi Wartość Opis Uwagi
Właściwości opcjonalne
bundleId string Identyfikator pakietu elementu. Usługi mogą określać identyfikator pakietu, aby grupować wiele elementów. Wyświetlają się pod jednym elementem najwyższego poziomu na urządzeniu. zapisywalny
canonicalUrl string Kanoniczny URL wskazuje kanoniczną/wysoką wersję danych reprezentowanych przez element osi czasu. zapisywalny
creator nested object Użytkownik lub grupa, która utworzyła ten element. zapisywalny
displayTime datetime Czas wyświetlania tego elementu na osi czasu, zgodny z RFC 3339. Oś czasu tego użytkownika jest posortowana chronologicznie według czasu wyświetlania, więc określa też miejsce wyświetlania elementu na osi czasu. Jeśli nie ustawisz tej funkcji, jej czas wyświetlania jest domyślnie ustawiony na updated. zapisywalny
html string Treść HTML tego elementu. Jeśli podany jest zarówno element text, jak i html, element html zostanie wyrenderowany na osi czasu.

Dozwolone elementy HTML – możesz ich używać na kartach osi czasu.

  • Nagłówki: h1, h2, h3, h4, h5, h6
  • Obrazy: img
  • Listy: li, ol, ul
  • Semantyka HTML5: article, aside, details, figure, figcaption, footer, header, nav, section, summary, time
  • Struktura: blockquote, br, div, hr, p, span
  • Styl: b, big, center, em, i, u, s, small, strike, strong, style, sub, sup
  • Stoły: table, tbody, td, tfoot, th, thead, tr

Zablokowane elementy HTML: te elementy i ich zawartość są usuwane z ładunków HTML.

  • Nagłówki dokumentów: head, title
  • Umieszczone: audio, embed, object, source, video
  • Ramki: frame, frameset
  • Skrypt: applet, script

Inne elementy: wszystkie elementy, których nie ma na liście, są usuwane, ale ich zawartość zostaje zachowana.

zapisywalny
isBundleCover boolean Określa, czy ten element jest zdjęciem pakietu.

Jeśli element jest oznaczony jako okładka pakietu, będzie punktem wejścia do pakietu elementów, które mają tę samą wartość bundleId co ten element. Będzie ona widoczna tylko na głównej osi czasu – nie w otwartym pakiecie.

Na głównej osi czasu wyświetlają się następujące elementy:
  • Elementy, w których isBundleCover ma wartość true
  • Elementy, które nie mają: bundleId
Wyświetlane są na osi czasu grupy:
  • Elementy, których bundleId ma znaczenie ORAZ isBundleCover, są ustawione na false
zapisywalny
location nested object Lokalizacja geograficzna powiązana z tym elementem. zapisywalny
notification nested object Określa sposób wyświetlania powiadomień dotyczących danego elementu na urządzeniu. Jeśli go zabraknie, nie zostanie wygenerowane żadne powiadomienie. zapisywalny
notification.deliveryTime datetime Godzina doręczenia powiadomienia. zapisywalny
notification.level string Określa, jak ważne jest powiadomienie. Dozwolone wartości to:
  • DEFAULT – powiadomienia dotyczące domyślnego znaczenia. Zostanie odtworzony sygnał dźwiękowy.
zapisywalny
recipients[] list Lista użytkowników lub grup, którym udostępniono ten element. zapisywalny
sourceItemId string Nieprzezroczysty ciąg znaków, którego możesz użyć do mapowania elementu osi czasu na dane w Twojej usłudze. zapisywalny
speakableText string Wersja głosu tego elementu. W połączeniu z pozycją w menu READ_ALOUD użyj tego pola, aby tekst był wyraźniejszy, gdy jest odczytywany na głos, albo podaj więcej informacji o tym, co jest wyświetlane w Google Glass.

Oprogramowanie Glassware powinno też zawierać poleSpeakableType, które będzie wypowiadane przed tym tekstem, w sytuacjach, gdy dodatkowy kontekst będzie przydatny, na przykład gdy użytkownik poprosi, że element zostanie odczytany na głos po powiadomieniu.
zapisywalny
speakableType string Wyraźny opis typu tego elementu. O tym poinformujemy użytkownika przed przeczytaniem treści elementu, w sytuacji, gdy dodatkowy kontekst jest przydatny, na przykład gdy użytkownik zażąda, aby element został odczytany na głos po powiadomieniu.

To powinno być krótkie, proste wyrażenie rzeczowe, np. „E-mail”, „SMS” lub „Codzienne aktualności dotyczące planet”.

Zachęcamy do wypełniania tego pola w przypadku każdego elementu na osi czasu, nawet jeśli ten element nie zawiera tekstu lub tekstu możliwego do odczytania, aby użytkownik mógł poznać typ elementu bez patrzenia na ekran.
zapisywalny
text string Treść tego elementu. zapisywalny
title string Tytuł tego elementu. zapisywalny

Odpowiedź

Jeśli operacja się uda, ta metoda zwróci zasób osi czasu w treści odpowiedzi.

Przykłady

Uwaga: dostępne dla tej metody przykłady kodu nie odzwierciedlają wszystkich obsługiwanych języków programowania. Listę obsługiwanych języków znajdziesz na stronie z bibliotekami klienta.

Java

Używa biblioteki klienta w języku Java.

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;

public class MyClass {
  // ...

  /**
   * Update a timeline item in the user's Glass with an optional notification and attachment.
   * 
   * @param service Authorized Mirror service.
   * @param itemId ID of the timeline item to update.
   * @param newText timeline item's text.
   * @param newNotificationLevel Optional notification level, supported values
   *        are {@code null} and "AUDIO_ONLY".
   * @return Updated timeline item on success, {@code null} otherwise.
   */
  public static TimelineItem updateTimelineItem(Mirror service, String itemId, String newText,
      String newNotificationLevel) {
    try {
      // First retrieve the timeline item from the API.
      TimelineItem timelineItem = service.timeline().get(itemId).execute();
      // Update the timeline item's metadata.
      timelineItem.setText(newText);
      if (newNotificationLevel != null && newNotificationLevel.length() > 0) {
        timelineItem.setNotification(new NotificationConfig().setLevel(newNotificationLevel));
      } else {
        timelineItem.setNotification(null);
      }
      return service.timeline().update(itemId, timelineItem).execute();
    } catch (IOException e) {
      System.err.println("An error occurred: " + e);
      return null;
    }
  }

  // ...
}

.NET

Używa biblioteki klienta.NET.

using System;
using System.IO;

using Google.Apis.Mirror.v1;
using Google.Apis.Mirror.v1.Data;

public class MyClass {
  // ...

  /// <summary>
  /// Update a timeline item in the user's Glass with an optional
  /// notification and attachment.
  /// </summary>
  /// <param name='service'>Authorized Mirror service.</param>
  /// <param name='itemId'>ID of the timeline item to update.</param>
  /// <param name='newText'>Timeline Item's text content.</param>
  /// <param name='newNotificationLevel'>
  /// Optional notification level, supported values are null and
  /// "AUDIO_ONLY".
  /// </param>
  /// <returns>
  /// Updated timeline item on success, null otherwise.
  /// </returns>
  public static TimelineItem UpdateTimelineItem(MirrorService service,
      String itemId, String newText, String newNotificationLevel) {
    try {
      // First retrieve the timeline item from the API.
      TimelineItem timelineItem = service.Timeline.Get(itemId).Fetch();
      // Update the timeline item's metadata.
      timelineItem.Text = newText;
      if (!String.IsNullOrEmpty(newNotificationLevel)) {
        timelineItem.Notification = new NotificationConfig() {
          Level = newNotificationLevel
        };
      } else {
        timelineItem.Notification = null;
      }
      return service.Timeline.Update(timelineItem, itemId).Fetch();
    } catch (Exception e) {
      Console.WriteLine("An error occurred: " + e.Message);
      return null;
    }
  }

  // ...
}

PHP

Używa biblioteki klienta PHP.

/**
 * Update a timeline item in the user's Glass with an optional
 * notification and attachment.
 *
 * @param Google_MirrorSservice $service Authorized Mirror service.
 * @param string $itemId ID of the timeline item to update.
 * @param string $newText timeline item's text (can be HTML content).
 * @param string $newNotificationLevel Optional notification level,
 *               supported values are {@code null} and "AUDIO_ONLY".
 * @return Google_TimelineItem Updated timeline item on success,
 *         null otherwise.
 */
function updateTimelineItem($service, $itemId, $newText, $newNotificationLevel) {
  try {
    $timelineItem = $service->timeline->get($itemId);
    $timelineItem->setText($newText);
    if ($notificationlevel != null) {
      $notification = new Google_NotificationConfig();
      $notification->setLevel($newNotificationLevel);
      $timelineItem->setNotification($notification);
    } else {
      $timelineItem->setNotification(null);
    }
    return $service->timeline->update($itemId, $timelineItem);
  } catch (Exception $e) {
    print 'An error occurred: ' . $e->getMessage();
    return null;
  }
}

Python

Używa biblioteki klienta dla języka Python.

import io

from apiclient import errors
from apiclient.http import MediaIoBaseUpload
# ...

def update_timeline_item(service, item_id, new_text, 
                         new_notification_level=None):
  """Update a timeline item in the user's Glass.

  Args:
    service: Authorized Mirror service.
    item_id: ID of the timeline item to update.
    new_text: Timeline item's text (can be HTML content).
    new_content_type: Optional attachment's content type (supported content
                      types are 'image/*', 'video/*' and 'audio/*').
    new_attachment: Optional attachment as data string.
    new_notification_level: Optional notification level, supported values are
                            None and 'AUDIO_ONLY'.
  Returns:
    Updated timeline item on success, None otherwise.
  """
  try:
    # First retrieve the timeline item from the API.
    timeline_item = service.timeline().get(id=item_id).execute()
    # Update the timeline item's metadata.
    timeline_item['text'] = new_text
    if new_notification_level:
      timeline_item['notification'] = {'level': new_notification_level}
    elif 'notification' in timeline_item:
      timeline_item.pop('notification')
    return service.timeline().update(id=item_id, body=timeline_item).execute()
  except errors.HttpError, error:
    print 'An error occurred: %s' % error
    return None

Ruby

Używa biblioteki klienta Ruby.

##
# Update a timeline item in the user's glass.
#
# @param [Google::APIClient] client
#   Authorized client instance.
# @param [String] item_id
#   ID of the timeline item to update.
# @param [String] new_text
#   Timeline item's new text.
# @param [String] new_notification_level
#   Optional new notification level, supported values are nil and 'AUDIO_ONLY'.
# @return [Google::APIClient::Schema::Mirror::V1::TimelineItem]
#   Updated timeline item instance if successful, nil otherwise.
def update_timeline_item(client, item_id, new_text, new_notification_level)
  mirror = client.discovered_api('mirror', 'v1')
  result = client.execute(
    :api_method => mirror.timeline.get,
    :parameters => { 'id' => item_id })
  if result.success?
    timeline_item = result.data
    timeline_item.text = new_text
    if new_notification_level
      timeline_item.notification = { 'level' => new_notification_level }
    else
      timeline_item.notification = nil
    end
    result = client.execute(
      :api_method => mirror.timeline.update,
      :body_object => timeline_item,
      :parameters => { 'id' => item_id })
    if result.success?
      return result.data
    end
  end
  puts "An error occurred: #{result.data['error']['message']}"
end

Go

Używa biblioteki klienta Go.

import (
	"code.google.com/p/google-api-go-client/mirror/v1"
	"fmt"
)

// UpdateTimelineItem updates a timeline item in the user's timeline with an
// optional notification and attachment.
func UpdateTimelineItem(g *mirror.Service, itemId string, newNotificationLevel string) (
	*mirror.TimelineItem, error) {
	t, err := g.Timeline.Get(itemId).Do()
	if err != nil {
		fmt.Printf("An error occurred: %v\n", err)
		return nil, err
	}
	t.Text = newText
	if newNotificationLevel != "" {
		t.Notification = &mirror.NotificationConfig{Level: newNotificationLevel}
	} else {
		t.Notification = nil
	}
	r, err := g.Timeline.Update(itemId, t).Do()
	if err != nil {
		fmt.Printf("An error occurred: %v\n", err)
		return nil, err
	}
	return r, nil
}

Nieprzetworzony protokół HTTP

Nie korzysta z biblioteki klienta.

PUT /mirror/v1/timeline/timeline item id HTTP/1.1
Host: www.googleapis.com
Authorization: Bearer auth token
Content-Type: application/json
Content-Length: 26

{ "text": "Hello world" }