~ubuntu-branches/ubuntu/trusty/ubufox/trusty-proposed

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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
/* -*- Mode: javascript; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** 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 ubufox.
 *
 * The Initial Developer of the Original Code is
 * Canonical Ltd.
 * Portions created by the Initial Developer are Copyright (C) 2008
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   Alexander Sack <asac@jwsdot.com> - Canonical Ltd.
 *   Arzhel Younsi <xionox@gmail.com>
 *   Chris Coulson <chris.coulson@canonical.com>
 *
 * 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 ***** */

const { classes: Cc, interfaces: Ci, utils: Cu } = Components;

Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/FileUtils.jsm");
Cu.import("resource://gre/modules/ctypes.jsm");
Cu.import("resource://ubufox/modules/utils.jsm");
Cu.import("resource://ubufox/libs/gio.jsm");
Cu.import("resource://ubufox/libs/gobject.jsm");
Cu.import("resource://ubufox/libs/glib.jsm");

const NS_XPCOM_CURRENT_PROCESS_DIR        = "XCurProcD";
const NS_GRE_DIR                          = "GreD";
const NS_USER_PLUGINS_DIR                 = "UserPlugins";
const NS_APP_PLUGINS_DIR                  = "APlugns";
const NS_SYSTEM_PLUGINS_DIR               = "SysPlugins";
const XRE_SYS_LOCAL_EXTENSION_PARENT_DIR  = "XRESysLExtPD";
const XRE_SYS_SHARE_EXTENSION_PARENT_DIR  = "XRESysSExtPD";
const XRE_EXTENSIONS_DIR_LIST             = "XREExtDL";

addLogger(this, "update-notifier");

function UpdateNotifier() {
  LOG("Starting");
  this.wrappedJSObject = this;

  var listeners = [];
  var watches = {};
  var timers = {};
  var dispatched = [];
  var plugins = {};

  /**
   * Add a listener to receive update notifications
   * Calling this inside a notification may produce undefined results
   *
   * @param  aListener
   *         The listener object
   */
  this.addListener = function UN_addListener(aListener) {
    if (!aListener) {
      throw new Error("A listener must be specified");
    }

    if (typeof(aListener) != "object") {
      throw new Error("Invalid listener");
    }

    if (listeners.indexOf(aListener) != -1) {
      throw new Error("Trying to register an observer more than once");
    }

    listeners.push(aListener);

    for (let event in dispatched) {
      try {
        if (event in aListener) {
          aListener[event].apply(aListener, dispatched[event]);
        }
      } catch(e) {
        ERROR("Listener threw", e);
      }
    }
  };

  /**
   * Remove a listener and don't receive any more notifications.
   * Calling this inside a notification may produce undefined results
   *
   * @param  aListener
   *         The listener to remove
   */
  this.removeListener = function UN_removeListener(aListener) {
    let index = listeners.indexOf(aListener);
    if (index == -1) {
      throw new Error("Trying to remove an observer that was never registered");
    }

    listeners.splice(index, 1);
  };

  function dispatchNotification(aEvent) {
    if (dispatched.indexOf(aEvent) != -1) {
      return;
    }

    dispatched.push(aEvent);

    listeners.forEach(function(listener) {
      try {
        if (aEvent in listener) {
          listener[aEvent].apply(listener);
        }
      } catch(e) {
        ERROR("Listener threw", e);
      }
    });
  }

  function handleAppUpdated() {
    LOG("Application change detected");
    dispatchNotification("onAppUpdated");
  }

  function handlePluginsChanged() {
    LOG("Plugin change detected");
    let ph = Cc["@mozilla.org/plugin/host;1"].getService(Ci.nsIPluginHost);

    try {
      ph.reloadPlugins(false);
    } catch(e) {
      LOG("nsIPluginHost.reloadPlugins failed. No changes?");
      return;
    }

    // Here's how this works:
    // - We iterate over the updated list of plugin tags from the plugin host
    // - For each plugin tag, we check if we have old data for that plugin,
    //   looking up by path
    // - We then pass over and new plugin data that hasn't been paired with
    //   old data, and see if it matches any old data by name. This is to handle
    //   plugin upgrades where the install path changes. We do this in
    //   a separate pass in case there is more than one plugin with the same
    //   name. In this case, we can still get a match if only one of those
    //   is updated.
    // - Obviously, if a plugin update changes its path and name, we detect
    //   that as a new install
    // - For each plugin, we compare the newest mtime with the recorded mtime
    //   from the old plugin data (if it exists). If the old data exists and the
    //   mtime is different, then the plugin was updated
    let newPlugins = {};
    ph.getPluginTags().forEach(function(pluginTag) {
      LOG("Processing plugin \"" + pluginTag.name + "\" at " +
          pluginTag.fullpath);

      if (pluginTag.fullpath in plugins) {
        var oldPluginData = plugins[pluginTag.fullpath];
        delete plugins[pluginTag.fullpath];
      }

      if (oldPluginData) {
        LOG("Found old data for plugin with the same path (\"" +
            oldPluginData.name + "\", lastModifiedTime " +
            oldPluginData.lastModifiedTime + ")");
      }

      if (!(pluginTag.fullpath in newPlugins)) {
        let plugin = {
          "pluginData": {
            "path": pluginTag.fullpath,
            "name": pluginTag.name
          },
          "oldPluginData": oldPluginData
        };

        newPlugins[pluginTag.fullpath] = plugin;

        try {
          plugin.pluginData.lastModifiedTime = (new FileUtils.File(pluginTag.fullpath))
                                                             .lastModifiedTime;
          LOG("Updated lastModifiedTime: " + plugin.pluginData
                                                   .lastModifiedTime);
        } catch(e) {
          LOG("Plugin at path " + pluginTag.fullpath + " was not found");
          delete newPlugins[pluginTag.fullpath];
        }
      }
    });

    let pluginPathsByName = {};
    for (let path in plugins) {
      pluginPathsByName[plugins[path].name] = path;
    }

    // Try to match new data to old data by name, for plugins
    // where the install path changed
    for each (let plugin in newPlugins) {
      if (plugin.oldPluginData) {
        continue;
      }

      if (plugin.pluginData.name in pluginPathsByName) {
        let path = pluginPathsByName[plugin.pluginData.name];
        plugin.oldPluginData = plugins[path];
        delete plugins[path];

        LOG("Found old data for plugin \"" + plugin.pluginData.name +
            "\". Old path: " + path + ", old lastModifiedTime: " +
            plugin.oldPluginData.lastModifiedTime + ", new path: " +
            plugin.pluginData.path);
      }
    }

    Object.keys(plugins).forEach(function(path) {
      LOG("Plugin \"" + plugins[path].name + "\" at " +
          plugins[path].path + " was removed");
      delete plugins[path];
    });

    let foundUpdated = false;
    for each (let plugin in newPlugins) {
      if (plugin.oldPluginData &&
          plugin.oldPluginData.lastModifiedTime !=
          plugin.pluginData.lastModifiedTime) {
        LOG("Plugin \"" + plugin.pluginData.name + "\" at " +
            plugin.pluginData.path + " was updated");
        foundUpdated = true;     
      } else if (!plugin.oldPluginData) {
        LOG("Plugin \"" + plugin.pluginData.name + "\" at " +
            plugin.pluginData.path + " was newly installed");
      } else {
        LOG("Plugin \"" + plugin.pluginData.name + "\" at " +
            plugin.pluginData.path + " is unchanged");
      }

      plugins[plugin.pluginData.path] = plugin.pluginData;
    }

    if (foundUpdated) {
      dispatchNotification("onPluginsUpdated");
    }
  }

  function handleAddonsChanged() {
    // We don't know how to handle addon changes yet
  }

  function handler(aFile, aEventType, aIsDir) {
    if (aEventType == gio.GFileMonitorEventEnums.G_FILE_MONITOR_EVENT_CHANGED ||
        aEventType == gio.GFileMonitorEventEnums.G_FILE_MONITOR_EVENT_DELETED ||
        aEventType == gio.GFileMonitorEventEnums.G_FILE_MONITOR_EVENT_CREATED ||
        aEventType == gio.GFileMonitorEventEnums.G_FILE_MONITOR_EVENT_ATTRIBUTE_CHANGED) {
      let path = gio.g_file_get_path(aFile);
      let type;
      if (!(path in watches) && aIsDir) {
        type = watches[(new FileUtils.File(path)).parent.path].type;
      } else {
        type = watches[path].type;
      }

      if (!type) {
        ERROR("Got event for a path not in our watch list: " + path);
        return;
      }

      // Wait for the location to settle before dispatching the notification
      if (!(type in timers)) {
        timers[type] = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
        timers[type].initWithCallback(function() {
          delete timers[type];
          ((new Object({"app"    : handleAppUpdated,
                        "plugins": handlePluginsChanged,
                        "addons" : handleAddonsChanged}))[type])();
        }, 10000, Ci.nsITimer.TYPE_ONE_SHOT);
      } else {
        timers[type].delay = 10000;
      }
    }
  }

  function watchOneFile(aFile, aType) {
    if (!aFile.exists() || !aFile.isFile()) {
      return;
    }

    aFile.normalize();

    let file = gio.g_file_new_for_path(aFile.path);
    if (file.isNull()) {
      ERROR("OOM: Failed to get GFile for path " + aFile.path);
      return;
    }

    let mon = gio.g_file_monitor_file(file,
                                      gio.GFileMonitorFlagsFlags.G_FILE_MONITOR_NONE,
                                      null, null);
    gobject.g_object_unref(file);
    if (mon.isNull()) {
      ERROR("Failed to create monitor for path " + aFile.path);
      return;
    }

    let id = gobject.g_signal_connect(mon, "changed",
                                      function(aMonitor, aFile, aOtherFile,
                                               aEventType) {
      handler(aFile, aEventType, false);    
    });
    watches[aFile.path] = {monitor: mon, sig_id: id, type: aType};
    LOG("Watching " + aFile.path);
  }

  function watchOneDir(aKey, aPaths, aType) {
    let nsifile;
    if (aKey instanceof Ci.nsIFile) {
      nsifile = aKey;
      aPaths.forEach(function(path) {
        nsifile.append(path);
      });
    } else {
      nsifile = FileUtils.getDir(aKey, aPaths);
    }
    if (!nsifile.exists() || !nsifile.isDirectory()) {
      return;
    }

    nsifile.normalize();

    if (nsifile.path in watches) {
      return;
    }

    let file = gio.g_file_new_for_path(nsifile.path);
    if (file.isNull()) {
      ERROR("OOM: Failed to get GFile for path " + nsifile.path);
      return;
    }

    let mon = gio.g_file_monitor_directory(file,
                                           gio.GFileMonitorFlagsFlags.G_FILE_MONITOR_NONE,
                                           null, null);
    gobject.g_object_unref(file);
    if (mon.isNull()) {
      ERROR("Failed to create monitor for path " + nsifile.path);
      return;
    }

    let id = gobject.g_signal_connect(mon, "changed",
                                      function(aMonitor, aFile, aOtherFile,
                                               aEventType) {
      handler(aFile, aEventType, true);
    });
    watches[nsifile.path] = {monitor: mon, sig_id: id, type: aType};
    LOG("Watching " + nsifile.path);
  }

  function watchList(aKey, aType, aFilterList) {
    let e = Services.dirsvc.get(aKey, Ci.nsISimpleEnumerator);
    let files = [];
    while (e.hasMoreElements()) {
      files.push(e.getNext().QueryInterface(Ci.nsIFile));
    }

    if (aFilterList) {
      files = files.filter(function(aValue, aIndex, aArray) {
        if (aFilterList.indexOf(aValue.parent.path) != -1) {
          return true;
        }

        return false;
      });
    }

    files.forEach(function(file) {
      if (!(file.exists())) {
        return;
      }

      if (file.isDirectory()) {
        watchOneDir(file, [], aType);
      } else {
        watchOneFile(file, aType);
      }
    });
  }

  Services.obs.addObserver(function(aSubject, aTopic, aData) {
    if (aSubject == "xpcom-shutdown") {
      Services.obs.removeObserver(arguments.callee, "xpcom-shutdown", false);
      for (let path in watches) {
        gobject.g_signal_handler_disconnect(watches[path].monitor,
                                            watches[path].sig_id);
        gobject.g_object_unref(watches[path].monitor);
      }
    }
  }, "xpcom-shutdown", false);

  var idle = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
  idle.initWithCallback(function() {
    let kungFuDeathGrip = idle;
    watchOneDir(NS_XPCOM_CURRENT_PROCESS_DIR, [], "app");
    watchOneDir(NS_GRE_DIR, [], "app");
    watchOneDir(NS_APP_PLUGINS_DIR, [], "plugins");
    watchOneDir(NS_SYSTEM_PLUGINS_DIR, [], "plugins");
    //watchOneDir(XRE_SYS_LOCAL_EXTENSION_PARENT_DIR,
    //            [Services.appinfo.ID], "addons");
    //watchOneDir(XRE_SYS_SHARE_EXTENSION_PARENT_DIR,
    //            [Services.appinfo.ID], "addons");
    //watchOneDir(NS_XPCOM_CURRENT_PROCESS_DIR,
    //            ["extensions"], "addons");
    //watchList(XRE_EXTENSIONS_DIR_LIST, "addons",
    //          [FileUtils.getDir(XRE_SYS_LOCAL_EXTENSION_PARENT_DIR,
    //                            [Services.appinfo.ID]).path,
    //           FileUtils.getDir(XRE_SYS_SHARE_EXTENSION_PARENT_DIR,
    //                            [Services.appinfo.ID]).path,
    //           FileUtils.getDir(NS_XPCOM_CURRENT_PROCESS_DIR,
    //                            ["extensions"]).path]);

    idle.initWithCallback(function() {
      let kungFuDeathGrip = idle;
      // Would use the AddonManager here, but it doesn't expose full paths.
      // We use a delay here to avoid starting the plugin host at startup
      // if it isn't otherwise needed
      LOG("Initializing plugin data");
      Cc["@mozilla.org/plugin/host;1"].getService(Ci.nsIPluginHost)
                                      .getPluginTags()
                                      .forEach(function(aPluginTag) {
        try {
          plugins[aPluginTag.fullpath] = {
            "path": aPluginTag.fullpath,
            "name": aPluginTag.name,
            "lastModifiedTime": (new FileUtils.File(aPluginTag.fullpath))
                                              .lastModifiedTime
          };
          LOG("Found plugin \"" + aPluginTag.name + "\" at " +
              aPluginTag.fullpath + ", lastModifiedTime: " +
              plugins[aPluginTag.fullpath].lastModifiedTime);
        } catch(e) {
          delete plugins[aPluginTag.fullpath];
          LOG("Plugin \"" + aPluginTag.name + "\" doesn't exist at " +
              aPluginTag.fullpath);
        }
      });
    }, 8000, Ci.nsITimer.TYPE_ONE_SHOT);

  }, 0, Ci.nsITimer.TYPE_ONE_SHOT);
}

UpdateNotifier.prototype = {
  classDescription: "Update Notifier",
  classID: Components.ID("{799a4700-2085-40e8-853a-05dcf8e95e41}"),
  contractID: "@ubuntu.com/update-notifier;1",
  QueryInterface: XPCOMUtils.generateQI([Ci.nsISupports])
};

const NSGetFactory = XPCOMUtils.generateNSGetFactory([UpdateNotifier]);