~eagles051387/firefox-extensions/bindwood.ubuntu.lp425631

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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
/*
 * Copyright 2009 Canonical Ltd.
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 3, as published
 * by the Free Software Foundation.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranties of
 * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
 * PURPOSE.  See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along
 * with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
/* Lots and lots of debugging information */
var Bindwood = {
    bookmarksService: Components.classes["@mozilla.org/browser/nav-bookmarks-service;1"]
        .getService(Components.interfaces.nsINavBookmarksService),
    uuidService: Components.classes["@mozilla.org/uuid-generator;1"]
        .getService(Components.interfaces.nsIUUIDGenerator),
    annotationService: Components.classes["@mozilla.org/browser/annotation-service;1"]
        .getService(Components.interfaces.nsIAnnotationService),
    consoleService: Components.classes["@mozilla.org/consoleservice;1"]
        .getService(Components.interfaces.nsIConsoleService),
    historyService: Components.classes["@mozilla.org/browser/nav-history-service;1"]
        .getService(Components.interfaces.nsINavHistoryService),
    ioService: Components.classes["@mozilla.org/network/io-service;1"]
        .getService(Components.interfaces.nsIIOService),

    annotationKey: "bindwood/uuid",
    uuidItemIdMap: {},

    generateUUIDString: function() {
        return Bindwood.uuidService.generateUUID().toString();
    },

    annotateItemWithUUID: function(itemId, uuid) {
        var uuid = uuid ? uuid : Bindwood.generateUUIDString();
        Bindwood.annotationService.setItemAnnotation(itemId, Bindwood.annotationKey, uuid, 0, Bindwood.annotationService.EXPIRE_NEVER);
        // Whenever we create a new UUID, stash it and the itemId in
        // our local cache.
        Bindwood.uuidItemIdMap[uuid] = itemId;
        return uuid;
    },

    itemIdForUUID: function(uuid) {
        // First, try to look it up in our local cache, barring that
        // (which shouldn't happen), look it up slowly.
        var itemId = Bindwood.uuidItemIdMap[uuid];

        if (!itemId) {
            var items = Bindwood.annotationService.getItemsWithAnnotation(Bindwood.annotationKey, {});
            for (var i = 0; i < items.length; i++) {
                if (Bindwood.annotationService.getItemAnnotation(items[i], Bindwood.annotationKey) == uuid) {
                    Bindwood.uuidItemIdMap[uuid] = itemId = items[i];
                    break;
                }
            }
        }
        return itemId;
    },

    uuidForItemId: function(itemId) {
        // Try to look up the uuid, and failing that, assign a new one
        // and return it.
        var uuid;
        var found = false;
        try {
            uuid = Bindwood.annotationService.getItemAnnotation(itemId, Bindwood.annotationKey);
            found = true;
        } catch(e) {
            uuid = Bindwood.annotateItemWithUUID(itemId, null);
        }

        return uuid;
    },

    writeMessage: function(aMessage) {
        // convenience method for logging. Way better than alert()s.
        Bindwood.consoleService.logStringMessage("Bindwood: " + aMessage);
    },

    writeError: function(aMessage, e) {
        Bindwood.writeMessage(aMessage + "message: '" + e.message + "', reason: '" + e.reason + "', description: '" + e.description + "', error: '" + e.error + "'");
    },



    init: function() {
        // Start the process and de-register ourself
        // http://forums.mozillazine.org/viewtopic.php?f=19&t=657911&start=0
        // It ensures that we're only running that code on the first window.

        if(Components.classes["@mozilla.org/appshell/window-mediator;1"]
           .getService(Components.interfaces.nsIWindowMediator)
           .getEnumerator("").getNext() == window) {
           Bindwood.writeMessage("Getting a Couch Port");
            Bindwood.getCouchPortNumber(Bindwood.startProcess);
        }
    },

    getCouchPortNumber: function(continueFunction) {
        // find the desktop Couch port number by making a D-Bus call
        // we call D-Bus by shelling out to a bash script which calls
        // it for us, and writes the port number into a temp file

        // find OS temp dir to put the tempfile in
        // https://developer.mozilla.org/index.php?title=File_I%2F%2FO#Getting_special_files
        var tmpdir = Components.classes["@mozilla.org/file/directory_service;1"]
                     .getService(Components.interfaces.nsIProperties)
                     .get("TmpD", Components.interfaces.nsIFile);
        // create a randomly named tempfile in the tempdir
        var tmpfile = Components.classes["@mozilla.org/file/local;1"]
                     .createInstance(Components.interfaces.nsILocalFile);
        tmpfile.initWithPath(tmpdir.path + "/desktopcouch." + Math.random());
        tmpfile.createUnique(tmpfile.NORMAL_FILE_TYPE, 0600);
        Bindwood.writeMessage("Tempfile for Couch port number: " + tmpfile.path);

        // find the D-Bus bash script, which is in our extension folder
        var MY_ID = "bindwood@ubuntu.com";
        var em = Components.classes["@mozilla.org/extensions/manager;1"].
            getService(Components.interfaces.nsIExtensionManager);
        var dbus_script = em.getInstallLocation(MY_ID).getItemFile(MY_ID, "dbus.sh");
        Bindwood.writeMessage("Found path to dbus_script: " + dbus_script.path);
        // create an nsILocalFile for the executable
        var nsifile = Components.classes["@mozilla.org/file/local;1"]
                     .createInstance(Components.interfaces.nsILocalFile);
        nsifile.initWithPath(dbus_script.path);

        // create an nsIProcess2 to execute this bash script
        var process = Components.classes["@mozilla.org/process/util;1"]
                        .createInstance(Components.interfaces.nsIProcess2);
        process.init(nsifile);

        // Run the process, passing the tmpfile path
        var args = [tmpfile.path];
        process.runAsync(args, args.length, {
            observe: function(process, finishState, data) {
                var port = 5984;
                if (finishState == "process-finished") {
                    // read temp file to find port number
                    // https://developer.mozilla.org/en/Code_snippets/File_I%2f%2fO#Reading_from_a_file
                    var data = "";
                    var fstream = Components.classes["@mozilla.org/network/file-input-stream;1"].
                        createInstance(Components.interfaces.nsIFileInputStream);
                    var cstream = Components.classes["@mozilla.org/intl/converter-input-stream;1"].
                        createInstance(Components.interfaces.nsIConverterInputStream);
                    fstream.init(tmpfile, -1, 0, 0);
                    cstream.init(fstream, "UTF-8", 0, 0);
                    let (str = {}) {
                      cstream.readString(-1, str); // read the whole file and put it in str.value
                      data = str.value;
                    }
                    cstream.close(); // this closes fstream
                    data = data.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
                    if (/^[0-9]+$/.test(data)) {
                        port = data;
                    } else {
                        Bindwood.writeMessage("D-Bus port data is not a number (" + data + ")");
                    }
                } else {
                    // fall back to system CouchDB
                    Bindwood.writeMessage("D-Bus port find failed");
                }
                tmpfile.remove(false);
                continueFunction(port);
        }
        });
    },

    startProcess: function(couchPortNumber) {
        Bindwood.writeMessage("Starting process with Couch on port " + couchPortNumber);
        CouchDB.PORT_NUMBER = couchPortNumber;
        try {
            Bindwood.pushBookmarks();
        } catch(e) {
            Bindwood.writeError("Error when calling pushBookmarks: ", e);
        }
        Bindwood.createView();
        Bindwood.pullBookmarks();
    },

    createView: function() {
        var DDID = "_design/views";
        var couch = new CouchDB('bookmarks');
        var current_doc;
        try {
            current_doc = couch.open(DDID);
            if (current_doc !== null) {
                Bindwood.writeMessage("View already exists; leaving it alone");
            } else {
                new_doc = {
                    _id: DDID,
                    views: {
                        display: {
                         map: "function(doc) { " +
                           "var scheme = doc.uri.split(':',1)[0]; " +
                           "var uri; " +
                           "if (scheme == 'http' || scheme == 'https') {" +
                             "uri = doc.uri.split('/')[2];" +
                             "if (uri.length < 30) {" +
                               " uri += '/' + " +
                               "doc.uri.split('/',4)[3].substr(0,30-uri.length) + '...';" +
                             "}" +
                           "} else {" +
                           "uri = scheme + ' URL';" +
                           "}" +
                           "emit(doc.title, uri);" +
                         "}"
                       }
                    }
                };
                try {
                    couch.save(new_doc);
                } catch(e) {
                    Bindwood.writeError("Problem saving view: ", e);
                }
            }
        } catch(e) {
            // some kind of error fetching the existing design doc
            Bindwood.writeError("Problem checking for view: ", e);
        }
    },

    pushBookmarks: function() {
        // Prime the pump, so to speak, by uploading all our local
        // bookmarks to CouchDB (if they're not there already).
        var couch = new CouchDB('bookmarks');
        // Create the DB if it doesn't already exist
        try {
            couch.createDb();
        } catch (e) {
            Bindwood.writeError("Error when creating database in pushBookmarks (file_exists is OK here): ", e);
        }

        Bindwood.pushBookmarksFromList(Bindwood.bookmarksService.toolbarFolder,
            "toolbarFolder", couch);
        Bindwood.pushBookmarksFromList(Bindwood.bookmarksService.bookmarksMenuFolder,
            "bookmarksMenuFolder", couch);
    },

    getBookmarksFromList: function(bookmarksList) {
        var retval = [];
        var options = Bindwood.historyService.getNewQueryOptions();
        var query = Bindwood.historyService.getNewQuery();
        query.setFolders([bookmarksList], 1);
        var result = Bindwood.historyService.executeQuery(query, options);
        var rootNode = result.root;
        rootNode.containerOpen = true;
        for (var i=0; i<rootNode.childCount; i++) {
            var node = rootNode.getChild(i);
            if (Bindwood.bookmarksService.getItemType(node.itemId) !=
                Bindwood.bookmarksService.TYPE_BOOKMARK) {
                continue;
            }

            var title = Bindwood.bookmarksService.getItemTitle(node.itemId);
            try {
                var metadata = Bindwood.bookmarksService.getBookmarkURI(node.itemId);
            } catch(e) {
                Bindwood.writeError("problem fetching metadata for bookmark '" + title + "': ", e);
                continue;
            }
            var uuid = Bindwood.uuidForItemId(node.itemId);
            retval.push({
                title: title,
                metadata: metadata,
                uuid: uuid,
                id: node.itemId});
        }
        rootNode.containerOpen = false;
        return retval;
    },

    pushBookmarksFromList: function(bookmarksList, bookmarksListName, db) {
        var bookmarkData = Bindwood.getBookmarksFromList(bookmarksList);
        for (var i = 0; i < bookmarkData.length; i++) {
            // find this bookmark in CouchDB
            var uuid = Bindwood.uuidForItemId(bookmarkData[i].id);
            var uri =  bookmarkData[i].metadata.spec;
            var title = bookmarkData[i].title;

            var results = db.query(function(doc) {
                if (doc.application_annotations &&
                    doc.application_annotations.Firefox &&
                    doc.application_annotations.Firefox.uuid) {
                    emit(doc.application_annotations.Firefox.uuid, doc);
                }
            }, null, {
                startkey: uuid, endkey: uuid
            });

            if (results.rows.length === 0) {
                // this bookmark is not in CouchDB, so write it
                var record = {
                    record_type: "http://example.com/bookmark",
                    uri: uri,
                    title: title,
                    application_annotations: {
                        Firefox: {
                            uuid: uuid,
                            list: bookmarksListName
                        }
                    }
                };
                try {
                    db.save(record);
                } catch(e) {
                    Bindwood.writeError("Problem saving bookmark to CouchDB; bookmark is " + JSON.stringify(record) + ": ", e);
                }
            } else {
                // bookmark is already in CouchDB, so do nothing
            }
        }
    },

    pullBookmarks: function() {
        var couch = new CouchDB('bookmarks');
        // Fetch all bookmark documents from the database
        // the query function is evaluated by Couch, which doesn't know
        // what Bindwood.RECORD_TYPE is, so we string-encode it first to
        // include the literal value
        try {
            var rows = couch.query(function (doc) {
                if (doc.record_type == "http://example.com/bookmark") {
                    emit(doc._id,doc);
                }
            });
        } catch(e) {
            Bindwood.writeError("Problem fetching all bookmarks from Couch: ", e);
        }
        for (var i = 0; i < rows.rows.length; i++) {
            var recordid = rows.rows[i].id;
            var bm = rows.rows[i].value;
            if (bm.application_annotations &&
                bm.application_annotations.Firefox &&
                bm.application_annotations.Firefox.uuid) {
                // this bookmark has a uuid, so check its values haven't changed
                // find the bookmark with this uuid
                var couch_uuid = bm.application_annotations.Firefox.uuid;
                Bindwood.writeMessage("Row uuid: " + couch_uuid);
                var itemId = Bindwood.itemIdForUUID(couch_uuid);
                if (!itemId) {
                    // This bookmark has a uuid, but it's not one of ours.
                    // We need to work out whether (a) it's the same as one
                    //   of ours but with a different uuid (so we need to
                    //   make the uuids the same), or (b) it's a new one
                    //   that happens to have been created on a different
                    //   machine.
                    try {
                        var uri = Bindwood.ioService.newURI(bm.uri, null, null);
                    } catch(e) {
                        Bindwood.writeError("Problem creating URI (" + bm.uri + ") for bookmark: ", e);
                        continue;
                    }
                    var ids = Bindwood.bookmarksService.getBookmarkIdsForURI(uri, {});
                    if (ids.length > 1) {
                        // punt for now, too many problems.
                    } else if (ids.length) {
                        // Found one local bookmark. Replace its uuid to
                        // be the one from Couch.
                        var itemId = ids[0];
                        var old_uuid = Bindwood.uuidForItemId(itemId);
                        delete Bindwood.uuidItemIdMap[old_uuid];
                        Bindwood.annotateItemWithUUID(itemId, couch_uuid);
                    } else {
                        /// No local bookmarks
                        Bindwood.addLocalBookmark(bm, recordid, couch_uuid);
                    }
                } else {
                    if (bm.deleted) {
                        // This bookmark exists on Couch, but has been
                        // flagged for deletion by another Client. We
                        // want to respect that, and delete it
                        // locally.
                        Bindwood.bookmarksService.removeItem(itemId);
                    } else {
                        var title = Bindwood.bookmarksService.getItemTitle(itemId);
                        var metadata = Bindwood.bookmarksService.getBookmarkURI(itemId);
                        if (title != bm.title) {
                            Bindwood.bookmarksService.setItemTitle(itemId, bm.title);
                        }
                        if (metadata.spec != bm.uri) {
                            try {
                                metadata = Bindwood.ioService.newURI(bm.uri, null, null);
                                Bindwood.bookmarksService.changeBookmarkURI(itemId, metadata);
                            } catch(e) {
                                Bindwood.writeError("Problem creating a new URI for bookmark: ", e);
                            }
                        }
                    }
                }
            } else {
                // This bookmark has no uuid, so create it from fresh
                // in Firefox. Passing in null to addLocalBookmar will
                // generate a new uuid.
                Bindwood.addLocalBookmark(bm, recordid, null);
            }
        }
        // reschedule ourself
        setTimeout(Bindwood.pullBookmarks, 30000);
    },

    addLocalBookmark: function(bm, recordid, uuid) {
        var couch = new CouchDB('bookmarks');
        var list;
        if (bm.application_annotations &&
            bm.application_annotations.Firefox &&
            bm.application_annotations.Firefox.list) {
            switch (bm.application_annotations.Firefox.list) {
            case "toolbarFolder":
                list = Bindwood.bookmarksService.toolbarFolder;
                break;
            case "bookmarksMenuFolder":
                list = Bindwood.bookmarksService.bookmarksMenuFolder;
                break;
            default:
                list = Bindwood.bookmarksService.toolbarFolder;
                break;
            }
        } else {
            list = Bindwood.bookmarksService.toolbarFolder;
        }
        var metadata = Bindwood.ioService.newURI(bm.uri, null, null);

        var itemId = Bindwood.bookmarksService.insertBookmark(list,
            metadata, -1, bm.title);
        // and then write the new uuid back to the record
        var uuid = uuid ? uuid : Bindwood.uuidForItemId(itemId);
        var doc = couch.open(recordid);
        if (!doc.application_annotations) {
            doc.application_annotations = {};
        }
        if (!doc.application_annotations.Firefox) {
            doc.application_annotations.Firefox = {};
        }
        doc.application_annotations.Firefox.uuid = uuid;
        try {
            couch.save(doc);
        } catch(e) {
            Bindwood.writeError("Problem writing record for new bookmark: ",e);
        }
    },

    Observer: {
        // An nsINavBookmarkObserver
        onItemAdded: function(aItemId, aFolder, aIndex) {
            // A bookmark has been added, so we create a blank entry
            // in Couch with our local itemId attached.
            netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead UniversalBrowserWrite");

            var couch = new CouchDB('bookmarks');

            var uuid = Bindwood.uuidForItemId(aItemId);

            var list;
            switch(aFolder) {
                case Bindwood.bookmarksService.toolbarFolder:
                    list = "toolbarFolder";
                    break;
                case Bindwood.bookmarksService.bookmarksMenuFolder:
                    list = "bookmarksMenuFolder";
                    break;
                default:
                    list = "toolbarFolder";
                    break;
            }

            var doc = {
                record_type: "http://example.com/bookmark",
                application_annotations: {
                    Firefox: {
                        uuid: uuid,
                        list: list
                    }
                }
            };

            try {
                var result = couch.save(doc);
            } catch(e) {
                Bindwood.writeError("Problem saving new bookmark to Couch: ", e);
            }
        },
        onBeforeItemRemoved: function(aItemId) {
            // A bookmark has been removed. This is called before it's
            // been removed locally, though we're passed the itemId,
            // which we use to delete from Couch.
            netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead UniversalBrowserWrite");

            var couch = new CouchDB('bookmarks');

            var uuid = Bindwood.uuidForItemId(aItemId);

            var results = couch.query(function(doc) {
                if (doc.application_annotations &&
                    doc.application_annotations.Firefox &&
                    doc.application_annotations.Firefox.uuid) {
                    emit(doc.application_annotations.Firefox.uuid, doc);
                }
            }, null, {
                startkey: uuid, endkey: uuid
            });

            if (results.rows.length === 0) {
                Bindwood.writeMessage("A bookmark was deleted, but this bookmark isn't in CouchDB. This isn't supposed to happen.");
                return;
            }

            var doc = couch.open(results.rows[0].id);
            // Update the doc in Couch to inform other clients that it
            // should be deleted locally.
            doc.deleted = true;

            try {
                var result = couch.save(doc);
                // Also remove from our local cache and remove
                // annotation from service.
                delete Bindwood.uuidItemIdMap[uuid];
            } catch(e) {
                Bindwood.writeError("Problem pushing deleted record to Couch: ", e);
            }
        },
        onItemRemoved: function(aItemId, aFolder, aIndex) {
            Bindwood.annotationService.removeItemAnnotation(aItemId, Bindwood.annotationKey);
        },
        onItemChanged: function(aBookmarkId, aProperty, aIsAnnotationProperty, aValue) {
            // A property of a bookmark has changed. On multiple
            // property updates, this will be called multiple times,
            // once per property (i.e., for title and URI)
            netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead UniversalBrowserWrite");

            var couch = new CouchDB('bookmarks');

            var uuid = Bindwood.uuidForItemId(aBookmarkId);

            var results = couch.query(function(doc) {
                if (doc.application_annotations &&
                    doc.application_annotations.Firefox &&
                    doc.application_annotations.Firefox.uuid) {
                    emit(doc.application_annotations.Firefox.uuid, doc);
                }
            }, null, {
                startkey: uuid, endkey: uuid
            });

            if (results.rows.length === 0) {
                Bindwood.writeMessage("a bookmark has changed, but this bookmark isn't in CouchDB. this isn't supposed to happen.");
                return;
            }

            var doc = couch.open(results.rows[0].id);
            doc[aProperty.toString()] = aValue.toString();

            try {
                var result = couch.save(doc);
            } catch(e) {
                Bindwood.writeError("Problem saving updated bookmark to Couch: ", e);
            }
        },

        onBeginUpdateBatch: function() {},
        onEndUpdateBatch: function() {},
        onItemVisited: function(aBookmarkId, aVisitID, time) {},
        onItemMoved: function(aItemId, aOldParent, aOldIndex, aNewParent, aNewIndex) {},
        QueryInterface: function(iid) {
            if (iid.equals(Components.interfaces.nsINavBookmarkObserver) ||
                iid.equals(Components.interfaces.nsINavBookmarkObserver_MOZILLA_1_9_1_ADDITIONS) ||
                iid.equals(Components.interfaces.nsISupports)) {
                return this;
            }
            throw Cr.NS_ERROR_NO_INTERFACE;
        }
    }
};