File size: 10,860 Bytes
0936134
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Network Location Provider for GLS.
 *
 * The Initial Developer of the Original Code is
 * Mozilla Foundation.
 * Portions created by the Initial Developer are Copyright (C) 2011
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   Doug Turner <dougt@dougt.org>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */


// Do not use this API without permission from Google.
// See http://www.google.com/support/enterprise/bin/request.py?contact_type=gme&utm_campaign=en-us-ptr-mz
// for more information.

Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
Components.utils.import("resource://gre/modules/Services.jsm");

const Ci = Components.interfaces;
const Cc = Components.classes;

let gLoggingEnabled = false;
let gTestingEnabled = false;

function LOG(aMsg) {
  if (gLoggingEnabled)
  {
    aMsg = "*** WIFI GEO: " + aMsg + "\n";
    Cc["@mozilla.org/consoleservice;1"].getService(Ci.nsIConsoleService).logStringMessage(aMsg);
    dump(aMsg);
  }
}

function WifiGeoCoordsObject(lat, lon, acc, alt, altacc) {
  this.latitude = lat;
  this.longitude = lon;
  this.accuracy = acc;
  this.altitude = alt;
  this.altitudeAccuracy = altacc;
}

WifiGeoCoordsObject.prototype = {

  QueryInterface:  XPCOMUtils.generateQI([Ci.nsIDOMGeoPositionCoords]),

  classInfo: XPCOMUtils.generateCI({interfaces: [Ci.nsIDOMGeoPositionCoords],
                                    flags: Ci.nsIClassInfo.DOM_OBJECT,
                                    classDescription: "wifi geo position coords object"}),
};

function WifiGeoPositionObject(lat, lng, acc) {
  this.coords = new WifiGeoCoordsObject(lat, lng, acc, 0, 0);
  this.address = null;
  this.timestamp = Date.now();
}

WifiGeoPositionObject.prototype = {

  QueryInterface:   XPCOMUtils.generateQI([Ci.nsIDOMGeoPosition]),

  // Class Info is required to be able to pass objects back into the DOM.
  classInfo: XPCOMUtils.generateCI({interfaces: [Ci.nsIDOMGeoPosition],
                                    flags: Ci.nsIClassInfo.DOM_OBJECT,
                                    classDescription: "wifi geo location position object"}),
};

function WifiGeoPositionProvider() {
  try {
    gLoggingEnabled = Services.prefs.getBoolPref("geo.wifi.logging.enabled");
  } catch (e) {}

  try {
    gTestingEnabled = Services.prefs.getBoolPref("geo.wifi.testing");
  } catch (e) {}

  wifiService = null;
  timer = null;
  hasSeenWiFi = false;
  started = false;
}

WifiGeoPositionProvider.prototype = {
  classID:          Components.ID("{77DA64D3-7458-4920-9491-86CC9914F904}"),
  QueryInterface:   XPCOMUtils.generateQI([Ci.nsIGeolocationProvider,
                                           Ci.nsIWifiListener,
                                           Ci.nsITimerCallback]),
  startup:  function() {
    if (this.started)
      return;
    this.started = true;
    this.hasSeenWiFi = false;

    LOG("startup called.  testing mode is" + gTestingEnabled);

    // if we don't see anything in 5 seconds, kick of one IP geo lookup.
    // if we are testing, just hammer this callback so that we are more or less
    // always sending data.  It doesn't matter if we have an access point or not.
    this.timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
    if (!gTestingEnabled)
      this.timer.initWithCallback(this, 5000, this.timer.TYPE_ONE_SHOT);
    else
      this.timer.initWithCallback(this, 200, this.timer.TYPE_REPEATING_SLACK);
  },

  watch: function(c) {
    LOG("watch called");
    if (!this.wifiService) {
      this.wifiService = Cc["@mozilla.org/wifi/monitor;1"].getService(Components.interfaces.nsIWifiMonitor);
      this.wifiService.startWatching(this);
    }
  },

  shutdown: function() { 
    LOG("shutdown called");
    if(this.wifiService) {
      this.wifiService.stopWatching(this);
      this.wifiService = null;
    }
    if (this.timer != null) {
      this.timer.cancel();
      this.timer = null;
    }

    // Although we aren't using cookies, we should err on the side of not
    // saving any access tokens if the user asked us not to save cookies or
    // has changed the lifetimePolicy.  The access token in these cases is
    // used and valid for the life of this object (eg. between startup and
    // shutdown).
    if (Services.prefs.getIntPref("network.cookie.lifetimePolicy") != 0)
      Services.prefs.deleteBranch("geo.wifi.access_token.");
    this.started = false;
  },

  getAccessTokenForURL: function(url)
  {
    // check to see if we have an access token:
    let accessToken = "";
    try {
      let accessTokenPrefName = "geo.wifi.access_token." + url;
      accessToken = Services.prefs.getCharPref(accessTokenPrefName);

      // check to see if it has expired
      let accessTokenDate = Services.prefs.getIntPref(accessTokenPrefName + ".time");
      
      let accessTokenInterval = 1209600;  // seconds in 2 weeks
      try {
        accessTokenInterval = Services.prefs.getIntPref("geo.wifi.access_token.recycle_interval");
      } catch (e) {}
            
      if ((Date.now() / 1000) - accessTokenDate > accessTokenInterval)
        accessToken = "";
    }
    catch (e) {
      accessToken = "";
    }
    return accessToken;
  },

  onChange: function(accessPoints) {
    LOG("onChange called");
    this.hasSeenWiFi = true;

    let providerUrlBase = "https://maps.googleapis.com/maps/api/browserlocation/json";
    try {
        providerUrlBase = Services.prefs.getCharPref("geo.wifi.uri");      
    } catch (x) {};
    let providerUrl;

    let query = providerUrlBase.indexOf("?");
    if (query == -1)
      providerUrl = providerUrlBase + "?"
    else
      providerUrl = providerUrlBase + "&";
    providerUrl = providerUrl + "browser=firefox&sensor=true";
    

    let accessToken = this.getAccessTokenForURL(providerUrlBase);
    if (accessToken !== "")
      providerUrl = providerUrl + "&access_token="+accessToken;

    function sort(a, b) {
      return b.signal - a.signal;
    };

    function encode(ap) {
      // make sure that the ssid doesn't contain any | chars.
      ap.ssid = ap.ssid.replace("|", "\\|");
      // gls service parses the | as fields
      return "&wifi=mac:"+ap.mac+"|ssid:"+ap.ssid+"|ss:"+ap.signal;
    };

    if (accessPoints) {
        providerUrl = providerUrl + accessPoints.sort(sort).map(encode).join("");
    }

    providerUrl = encodeURI(providerUrl);

    // max length is 2k.  make sure we are under that
    let x = providerUrl.length - 2000;
    if (x >= 0) {
	// we need to trim
	let doomed = providerUrl.lastIndexOf("&", 2000);
	LOG("Doomed:"+doomed);
	providerUrl = providerUrl.substring(0, doomed);
    }
    
    LOG("************************************* Sending request:\n" + providerUrl + "\n");

    // send our request to a wifi geolocation network provider:
    let xhr = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"]
                        .createInstance(Ci.nsIXMLHttpRequest);

    // This is a background load
    xhr.mozBackgroundRequest = true;
    xhr.open("GET", providerUrl, false);
    xhr.channel.loadFlags = Ci.nsIChannel.LOAD_ANONYMOUS;
    xhr.addEventListener("error", function(req) {
        LOG("onerror: " + req);
    }, false);
    xhr.addEventListener("load", function (req) {  
        LOG("service returned: " + req.target.responseText);
        response = JSON.parse(req.target.responseText);
        /*
          {
            "status": "OK",
            "accuracy": 150.0,
            "location": {
              "lat": -33.85702,
              "lng": 151.21494
            },
            "access_token": "quijibo"
          }
        */

        if (response.status != "OK")
          return;

        if (response.location) {
          let newLocation = new WifiGeoPositionObject(response.location.lat,
                                                      response.location.lng,
                                                      response.accuracy);

          let update = Cc["@mozilla.org/geolocation/service;1"].getService(Ci.nsIGeolocationUpdate);
          update.update(newLocation);
        }

        // Check to see if we have a new access token
        let newAccessToken = response.access_token;
        if (newAccessToken !== undefined)
        {
          let accessToken = "";
          let accessTokenPrefName = "geo.wifi.access_token." + providerUrlBase;
          try { accessToken = Services.prefs.getCharPref(accessTokenPrefName); } catch (e) {}

          if (accessToken != newAccessToken) {
            // no match, lets cache
              LOG("New Access Token: " + newAccessToken + "\n" + accessTokenPrefName);
              try {
                Services.prefs.setIntPref(accessTokenPrefName + ".time", nowInSeconds());
                Services.prefs.setCharPref(accessTokenPrefName, newAccessToken);
              } catch (x) {
                  // XXX temporary hack for bug 575346 to allow geolocation to function
              }
          }
        }
    }, false);

    LOG("************************************* ------>>>> sending.");
    xhr.send(null);
  },

  onError: function (code) {
    LOG("wifi error: " + code);
  },

  notify: function (timer) {
    if (gTestingEnabled) {
      // if we are testing, timer is repeating
      this.onChange(null);
    }
    else {
      if (!this.hasSeenWiFi)
        this.onChange(null);
      this.timer = null;
    }
  },
};

let NSGetFactory = XPCOMUtils.generateNSGetFactory([WifiGeoPositionProvider]);