Janvi
Janvi

Reputation: 125

Why i am getting empty array in Users.history:list API

I am trying to get history of changes done in gmail account using Users:History API with historyId. But somehow it is returns data after some seconds or minutes of changes done.

Code

function listHistory($service, $userId, $startHistoryId) {
  $opt_param = array('startHistoryId' => $startHistoryId);
  $pageToken = NULL;
  $histories = array();

  do {
    try {
      if ($pageToken) {
        $opt_param['pageToken'] = $pageToken;
      }
      $historyResponse = $service->users_history->listUsersHistory($userId, $opt_param);
      if ($historyResponse->getHistory()) {
        $histories = array_merge($histories, $historyResponse->getHistory());
        $pageToken = $historyResponse->getNextPageToken();
      }
    } catch (Exception $e) {
      print 'An error occurred: ' . $e->getMessage();
    }
  } while ($pageToken);


  return $histories;
}

Ref: https://developers.google.com/gmail/api/v1/reference/users/history/list

Upvotes: 2

Views: 1083

Answers (2)

Gopal Joshi
Gopal Joshi

Reputation: 2358

You need to store historyId somewhere in Push notification and create a cron job that will fetch (using Users.history.list API) history of specific account with historyId you stored until it does not return response.

Upvotes: 0

payne
payne

Reputation: 14187

You will get an empty result for a given startHistoryId if there have been no changes to the user's email box since the particular point in time identified by that history ID. That's the correct behavior.

And if you wait (second or minutes, as you suggest) and call again using the same starting history ID, and get results, those are the changes (new messages, etc.) that happened in the intervening time period.

And if you don't want to wait, and you have access to the Gmail account for testing, you can send a message to the account (or delete a message in the account) and you should see the corresponding changes when you call Users.history.list next.

For historyId values provided by push notifications, note the IDs provided are the new (current) history IDs. See: https://developers.google.com/gmail/api/guides/push

The HTTP POST body is JSON and the actual Gmail notification payload is in the message.data field. That message.data field is a base64url-encoded string that decodes to a JSON object containing the email address and the new mailbox history ID for the user:

{"emailAddress": "[email protected]", "historyId": "9876543210"} You can then use history.list() to get the change details for the user since their last known historyId, as per the sync guide.

(emphasis added). To get the updates, you have to use the previous history ID. Google has no way of knowing the latest history your application has tracked, so it's up to you to keep track of the history ID since you last did a history.list() operation.

Upvotes: 6

Related Questions