1// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5var oauth = ChromeExOAuth.initBackgroundPage({
6  'request_url' : 'https://www.google.com/accounts/OAuthGetRequestToken',
7  'authorize_url' : 'https://www.google.com/accounts/OAuthAuthorizeToken',
8  'access_url' : 'https://www.google.com/accounts/OAuthGetAccessToken',
9  'consumer_key' : 'anonymous',
10  'consumer_secret' : 'anonymous',
11  'scope' : 'http://www.google.com/m8/feeds/',
12  'app_name' : 'Sample - OAuth Contacts'
13});
14
15var contacts = null;
16
17function setIcon() {
18  if (oauth.hasToken()) {
19    chrome.browserAction.setIcon({ 'path' : 'img/icon-19-on.png'});
20  } else {
21    chrome.browserAction.setIcon({ 'path' : 'img/icon-19-off.png'});
22  }
23};
24
25function onContacts(text, xhr) {
26  contacts = [];
27  var data = JSON.parse(text);
28  for (var i = 0, entry; entry = data.feed.entry[i]; i++) {
29    var contact = {
30      'name' : entry['title']['$t'],
31      'id' : entry['id']['$t'],
32      'emails' : []
33    };
34
35    if (entry['gd$email']) {
36      var emails = entry['gd$email'];
37      for (var j = 0, email; email = emails[j]; j++) {
38        contact['emails'].push(email['address']);
39      }
40    }
41
42    if (!contact['name']) {
43      contact['name'] = contact['emails'][0] || "<Unknown>";
44    }
45    contacts.push(contact);
46  }
47
48  chrome.tabs.create({ 'url' : 'contacts.html'});
49};
50
51function getContacts() {
52  oauth.authorize(function() {
53    console.log("on authorize");
54    setIcon();
55    var url = "http://www.google.com/m8/feeds/contacts/default/full";
56    oauth.sendSignedRequest(url, onContacts, {
57      'parameters' : {
58        'alt' : 'json',
59        'max-results' : 100
60      }
61    });
62  });
63};
64
65function logout() {
66  oauth.clearTokens();
67  setIcon();
68};
69
70setIcon();
71chrome.browserAction.onClicked.addListener(getContacts);
72