Timeline: update

Wymaga autoryzacji

Aktualizuje element osi czasu. Zobacz przykład

Ta metoda obsługuje identyfikator URI /upload i akceptuje przesłane multimedia o tych cechach:

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

Żądanie

Żądanie HTTP

Ta metoda udostępnia funkcję przesyłania multimediów za pomocą 2 osobnych identyfikatorów URI. Więcej informacji znajdziesz w dokumencie na temat przesyłania multimediów.

  • Identyfikator URI przesyłania dla żądań przesłania multimediów:
    PUT https://www.googleapis.com/upload/mirror/v1/timeline/id
  • Identyfikator URI metadanych w przypadku żądań samych metadanych:
    PUT https://www.googleapis.com/mirror/v1/timeline/id

Parametry

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

Autoryzacja

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

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

Treść żądania

W treści żądania podaj zasób osi czasu z metadanymi o następujących właściwościach. Więcej informacji znajdziesz w dokumencie na temat przesyłania multimediów.

Nazwa usługi Wartość Opis Uwagi
Właściwości opcjonalne
bundleId string Identyfikator pakietu danego produktu. Usługi mogą mieć określony identyfikator pakietu, aby zgrupować wiele elementów. Są one wyświetlane na urządzeniu pod jednym elementem najwyższego poziomu. z możliwością zapisu
canonicalUrl string Kanoniczny adres URL wskazujący kanoniczną lub wysoką jakość danych reprezentowanych przez element osi czasu. z możliwością zapisu
creator nested object Użytkownik lub grupa, która utworzyła ten element. z możliwością zapisu
displayTime datetime Godzina, która powinna być wyświetlana, gdy ten element jest wyświetlany na osi czasu, sformatowany zgodnie ze standardem RFC 3339. Oś czasu tego użytkownika jest posortowana chronologicznie według czasu wyświetlania, dlatego ma to również wpływ na miejsce wyświetlania produktu na osi czasu. Jeśli usługa nie ustawi tego czasu, domyślnym czasem wyświetlania będzie updated. z możliwością zapisu
html string Zawartość HTML tego elementu. Jeśli w przypadku danego elementu podasz zarówno text, jak i html, na osi czasu zostanie wyświetlona wartość html.

Dozwolone elementy HTML – możesz używać tych elementów 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
  • Tabele: 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ść pozostaje bez zmian.

z możliwością zapisu
isBundleCover boolean Określa, czy ten produkt jest okładką pakietu.

Jeśli element jest oznaczony jako okładka pakietu, będzie to punkt wejścia do pakietu elementów mających ten sam atrybut bundleId co ten element. Będzie wyświetlany tylko na głównej osi czasu, a nie w otwartym pakiecie.

Na głównej osi czasu wyświetlane są:
  • Elementy, w których atrybut isBundleCover ma wartość true.
  • Produkty, które nie mają atrybutu bundleId
Na osi czasu pakietu wyświetlane są:
  • Elementy, w których parametr bundleId jest określony ORAZ isBundleCover jest ustawiony na false
z możliwością zapisu
location nested object Położenie geograficzne powiązane z tym elementem. z możliwością zapisu
notification nested object Określa sposób wyświetlania na urządzeniu powiadomień dotyczących tego elementu. W przypadku jego braku powiadomienie nie zostanie wygenerowane. z możliwością zapisu
notification.deliveryTime datetime Godzina dostarczenia powiadomienia. z możliwością zapisu
notification.level string Określa, jak ważne jest powiadomienie. Dozwolone wartości to:
  • DEFAULT – powiadomienia o domyślnej ważności. Usłyszysz sygnał dźwiękowy, który będzie ostrzegać użytkowników.
z możliwością zapisu
recipients[] list Lista użytkowników lub grup, którym udostępniono ten element. z możliwością zapisu
sourceItemId string Nieprzezroczysty ciąg znaków, którego możesz używać do mapowania elementu osi czasu na dane w Twojej usłudze. z możliwością zapisu
speakableText string Wypowiadająca się na głos wersja zawartości tego elementu. W tym polu oprócz pozycji menu READ_ALOUD możesz podać tekst, który będzie wyraźniejszy podczas czytania na głos, lub podać rozszerzone informacje o tym, co jest wyświetlane na ekranie Google Glass.

Glassware powinien też zawierać pole speechableType, które będzie odczytywane przed tym tekstem w przypadkach, gdy dodatkowy kontekst jest przydatny, na przykład gdy użytkownik zażąda odczytania elementu na głos po powiadomieniu.
z możliwością zapisu
speakableType string Mówiony opis typu elementu. Jest to sygnalizowane użytkownikowi przed przeczytaniem treści produktu w przypadkach, gdy przydatny jest dodatkowy kontekst, np. gdy użytkownik poprosi o przeczytanie elementu na głos po powiadomieniu.

To powinno być krótkie, proste wyrażenie, np. „E-mail”, „SMS” lub „Codzienne aktualności na temat planety”.

Zalecamy, aby w przypadku wszystkich elementów osi czasu wypełnić to pole dla oprogramowania Glassware, nawet jeśli nie zawiera on tekstu SayableText ani tekstu, dzięki czemu użytkownik może poznać typ elementu bez patrzenia na ekran.
z możliwością zapisu
text string Zawartość tekstowa tego elementu. z możliwością zapisu
title string Tytuł tego produktu. z możliwością zapisu

Odpowiedź

Jeśli operacja się uda, metoda zwróci zasób na 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 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 w Pythonie.

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

Przeczytaj

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 kod 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" }