1
/* ***** BEGIN LICENSE BLOCK *****
2
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
4
* The contents of this file are subject to the Mozilla Public License Version
5
* 1.1 (the "License"); you may not use this file except in compliance with
6
* the License. You may obtain a copy of the License at
7
* http://www.mozilla.org/MPL/
9
* Software distributed under the License is distributed on an "AS IS" basis,
10
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
11
* for the specific language governing rights and limitations under the
14
* The Original Code is Weave
16
* The Initial Developer of the Original Code is
17
* the Mozilla Foundation.
18
* Portions created by the Initial Developer are Copyright (C) 2008
19
* the Initial Developer. All Rights Reserved.
22
* Dan Mills <thunder@mozilla.com>
23
* Philipp von Weitershausen <philipp@weitershausen.de>
24
* Richard Newman <rnewman@mozilla.com>
26
* Alternatively, the contents of this file may be used under the terms of
27
* either the GNU General Public License Version 2 or later (the "GPL"), or
28
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
29
* in which case the provisions of the GPL or the LGPL are applicable instead
30
* of those above. If you wish to allow use of your version of this file only
31
* under the terms of either the GPL or the LGPL, and not to allow others to
32
* use your version of this file under the terms of the MPL, indicate your
33
* decision by deleting the provisions above and replace them with the notice
34
* and other provisions required by the GPL or the LGPL. If you do not delete
35
* the provisions above, a recipient may use your version of this file under
36
* the terms of any one of the MPL, the GPL or the LGPL.
38
* ***** END LICENSE BLOCK ***** */
40
const EXPORTED_SYMBOLS = ['HistoryEngine', 'HistoryRec'];
42
const Cc = Components.classes;
43
const Ci = Components.interfaces;
44
const Cu = Components.utils;
45
const Cr = Components.results;
47
const HISTORY_TTL = 5184000; // 60 days
48
const TOPIC_UPDATEPLACES_COMPLETE = "places-updatePlaces-complete";
50
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
51
Cu.import("resource://services-sync/constants.js");
52
Cu.import("resource://services-sync/engines.js");
53
Cu.import("resource://services-sync/record.js");
54
Cu.import("resource://services-sync/util.js");
55
Cu.import("resource://services-sync/log4moz.js");
57
function HistoryRec(collection, id) {
58
CryptoWrapper.call(this, collection, id);
60
HistoryRec.prototype = {
61
__proto__: CryptoWrapper.prototype,
62
_logName: "Record.History",
66
Utils.deferGetSet(HistoryRec, "cleartext", ["histUri", "title", "visits"]);
69
function HistoryEngine() {
70
SyncEngine.call(this, "History");
72
HistoryEngine.prototype = {
73
__proto__: SyncEngine.prototype,
74
_recordObj: HistoryRec,
75
_storeObj: HistoryStore,
76
_trackerObj: HistoryTracker,
77
downloadLimit: MAX_HISTORY_DOWNLOAD,
78
applyIncomingBatchSize: HISTORY_STORE_BATCH_SIZE,
80
_findDupe: function _findDupe(item) {
81
return this._store.GUIDForUri(item.histUri);
85
function HistoryStore(name) {
86
Store.call(this, name);
88
// Explicitly nullify our references to our cached services so we don't leak
89
Svc.Obs.add("places-shutdown", function() {
90
for each ([query, stmt] in Iterator(this._stmts))
96
HistoryStore.prototype = {
97
__proto__: Store.prototype,
102
this.__hsvc = Cc["@mozilla.org/browser/nav-history-service;1"].
103
getService(Ci.nsINavHistoryService).
104
QueryInterface(Ci.nsIGlobalHistory2).
105
QueryInterface(Ci.nsIBrowserHistory).
106
QueryInterface(Ci.nsPIPlacesDatabase);
110
__asyncHistory: null,
111
get _asyncHistory() {
112
if (!this.__asyncHistory) {
113
this.__asyncHistory = Cc["@mozilla.org/browser/history;1"]
114
.getService(Ci.mozIAsyncHistory);
116
return this.__asyncHistory;
120
_getStmt: function(query) {
121
if (query in this._stmts)
122
return this._stmts[query];
124
this._log.trace("Creating SQL statement: " + query);
125
return this._stmts[query] = this._hsvc.DBConnection
126
.createAsyncStatement(query);
130
return this._getStmt(
131
"UPDATE moz_places " +
132
"SET guid = :guid " +
133
"WHERE url = :page_url");
136
// Some helper functions to handle GUIDs
137
setGUID: function setGUID(uri, guid) {
138
uri = uri.spec ? uri.spec : uri;
141
guid = Utils.makeGUID();
143
let stmt = this._setGUIDStm;
144
stmt.params.guid = guid;
145
stmt.params.page_url = uri;
146
Utils.queryAsync(stmt);
151
return this._getStmt(
154
"WHERE url = :page_url");
158
GUIDForUri: function GUIDForUri(uri, create) {
159
let stm = this._guidStm;
160
stm.params.page_url = uri.spec ? uri.spec : uri;
162
// Use the existing GUID if it exists
163
let result = Utils.queryAsync(stm, this._guidCols)[0];
164
if (result && result.guid)
167
// Give the uri a GUID if it doesn't have one
169
return this.setGUID(uri);
173
return this._getStmt(
174
"SELECT visit_type type, visit_date date " +
175
"FROM moz_historyvisits " +
176
"WHERE place_id = (SELECT id FROM moz_places WHERE url = :url) " +
177
"ORDER BY date DESC LIMIT 10");
179
_visitCols: ["date", "type"],
182
return this._getStmt(
183
"SELECT url, title, frecency " +
185
"WHERE guid = :guid");
187
_urlCols: ["url", "title", "frecency"],
190
return this._getStmt(
193
"WHERE last_visit_date > :cutoff_date " +
194
"ORDER BY frecency DESC " +
195
"LIMIT :max_results");
197
_allUrlCols: ["url"],
199
// See bug 320831 for why we use SQL here
200
_getVisits: function HistStore__getVisits(uri) {
201
this._visitStm.params.url = uri;
202
return Utils.queryAsync(this._visitStm, this._visitCols);
205
// See bug 468732 for why we use SQL here
206
_findURLByGUID: function HistStore__findURLByGUID(guid) {
207
this._urlStm.params.guid = guid;
208
return Utils.queryAsync(this._urlStm, this._urlCols)[0];
211
changeItemID: function HStore_changeItemID(oldID, newID) {
212
this.setGUID(this._findURLByGUID(oldID).url, newID);
216
getAllIDs: function HistStore_getAllIDs() {
217
// Only get places visited within the last 30 days (30*24*60*60*1000ms)
218
this._allUrlStm.params.cutoff_date = (Date.now() - 2592000000) * 1000;
219
this._allUrlStm.params.max_results = MAX_HISTORY_UPLOAD;
221
let urls = Utils.queryAsync(this._allUrlStm, this._allUrlCols);
223
return urls.reduce(function(ids, item) {
224
ids[self.GUIDForUri(item.url, true)] = item.url;
229
applyIncomingBatch: function applyIncomingBatch(records) {
232
// Convert incoming records to mozIPlaceInfo objects. Some records can be
233
// ignored or handled directly, so we're rewriting the array in-place.
235
for (i = 0, k = 0; i < records.length; i++) {
236
let record = records[k] = records[i];
239
// This is still synchronous I/O for now.
241
if (record.deleted) {
242
// Consider using nsIBrowserHistory::removePages() here.
244
// No further processing needed. Remove it from the list.
247
shouldApply = this._recordToPlaceInfo(record);
250
failed.push(record.id);
258
records.length = k; // truncate array
261
if (!records.length) {
265
let cb = Utils.makeSyncCallback();
266
let onPlace = function onPlace(result, placeInfo) {
267
if (!Components.isSuccessCode(result)) {
268
failed.push(placeInfo.guid);
271
let onComplete = function onComplete(subject, topic, data) {
272
Svc.Obs.remove(TOPIC_UPDATEPLACES_COMPLETE, onComplete);
275
Svc.Obs.add(TOPIC_UPDATEPLACES_COMPLETE, onComplete);
276
this._asyncHistory.updatePlaces(records, onPlace);
277
Utils.waitForSyncCallback(cb);
282
* Converts a Sync history record to a mozIPlaceInfo.
284
* Throws if an invalid record is encountered (invalid URI, etc.),
285
* returns true if the record is to be applied, false otherwise
286
* (no visits to add, etc.),
288
_recordToPlaceInfo: function _recordToPlaceInfo(record) {
289
// Sort out invalid URIs and ones Places just simply doesn't want.
290
record.uri = Utils.makeURI(record.histUri);
292
this._log.warn("Attempted to process invalid URI, skipping.");
293
throw "Invalid URI in record";
296
if (!Utils.checkGUID(record.id)) {
297
this._log.warn("Encountered record with invalid GUID: " + record.id);
300
record.guid = record.id;
302
if (!this._hsvc.canAddURI(record.uri)) {
303
this._log.trace("Ignoring record " + record.id + " with URI "
304
+ record.uri.spec + ": can't add this URI.");
308
// We dupe visits by date and type. So an incoming visit that has
309
// the same timestamp and type as a local one won't get applied.
310
// To avoid creating new objects, we rewrite the query result so we
311
// can simply check for containment below.
312
let curVisits = this._getVisits(record.histUri);
313
for (let i = 0; i < curVisits.length; i++) {
314
curVisits[i] = curVisits[i].date + "," + curVisits[i].type;
317
// Walk through the visits, make sure we have sound data, and eliminate
318
// dupes. The latter is done by rewriting the array in-place.
320
for (i = 0, k = 0; i < record.visits.length; i++) {
321
let visit = record.visits[k] = record.visits[i];
323
if (!visit.date || typeof visit.date != "number") {
324
this._log.warn("Encountered record with invalid visit date: "
326
throw "Visit has no date!";
328
if (!visit.type || !(visit.type >= Svc.History.TRANSITION_LINK &&
329
visit.type <= Svc.History.TRANSITION_FRAMED_LINK)) {
330
this._log.warn("Encountered record with invalid visit type: "
332
throw "Invalid visit type!";
334
// Dates need to be integers
335
visit.date = Math.round(visit.date);
337
if (curVisits.indexOf(visit.date + "," + visit.type) != -1) {
338
// Visit is a dupe, don't increment 'k' so the element will be
342
visit.visitDate = visit.date;
343
visit.transitionType = visit.type;
346
record.visits.length = k; // truncate array
348
// No update if there aren't any visits to apply.
349
// mozIAsyncHistory::updatePlaces() wants at least one visit.
350
// In any case, the only thing we could change would be the title
351
// and that shouldn't change without a visit.
352
if (!record.visits.length) {
353
this._log.trace("Ignoring record " + record.id + " with URI "
354
+ record.uri.spec + ": no visits to add.");
361
remove: function HistStore_remove(record) {
362
let page = this._findURLByGUID(record.id);
364
this._log.debug("Page already removed: " + record.id);
368
let uri = Utils.makeURI(page.url);
369
Svc.History.removePage(uri);
370
this._log.trace("Removed page: " + [record.id, page.url, page.title]);
373
itemExists: function HistStore_itemExists(id) {
374
if (this._findURLByGUID(id))
379
urlExists: function HistStore_urlExists(url) {
380
if (typeof(url) == "string")
381
url = Utils.makeURI(url);
382
// Don't call isVisited on a null URL to work around crasher bug 492442.
383
return url ? this._hsvc.isVisited(url) : false;
386
createRecord: function createRecord(id, collection) {
387
let foo = this._findURLByGUID(id);
388
let record = new HistoryRec(collection, id);
390
record.histUri = foo.url;
391
record.title = foo.title;
392
record.sortindex = foo.frecency;
393
record.visits = this._getVisits(record.histUri);
396
record.deleted = true;
401
wipe: function HistStore_wipe() {
402
this._hsvc.removeAllPages();
406
function HistoryTracker(name) {
407
Tracker.call(this, name);
408
Svc.Obs.add("weave:engine:start-tracking", this);
409
Svc.Obs.add("weave:engine:stop-tracking", this);
411
HistoryTracker.prototype = {
412
__proto__: Tracker.prototype,
415
observe: function observe(subject, topic, data) {
417
case "weave:engine:start-tracking":
418
if (!this._enabled) {
419
Svc.History.addObserver(this, true);
420
this._enabled = true;
423
case "weave:engine:stop-tracking":
425
Svc.History.removeObserver(this);
426
this._enabled = false;
432
_GUIDForUri: function _GUIDForUri(uri, create) {
433
// Isn't indirection fun...
434
return Engines.get("history")._store.GUIDForUri(uri, create);
437
QueryInterface: XPCOMUtils.generateQI([
438
Ci.nsINavHistoryObserver,
439
Ci.nsINavHistoryObserver_MOZILLA_1_9_1_ADDITIONS,
440
Ci.nsISupportsWeakReference
443
onBeginUpdateBatch: function HT_onBeginUpdateBatch() {},
444
onEndUpdateBatch: function HT_onEndUpdateBatch() {},
445
onPageChanged: function HT_onPageChanged() {},
446
onTitleChanged: function HT_onTitleChanged() {},
448
/* Every add or remove is worth 1 point.
449
* Clearing the whole history is worth 50 points (see below)
451
_upScore: function BMT__upScore() {
455
onVisit: function HT_onVisit(uri, vid, time, session, referrer, trans) {
458
this._log.trace("onVisit: " + uri.spec);
460
Utils.delay(function() {
461
if (self.addChangedID(self._GUIDForUri(uri, true))) {
466
onDeleteVisits: function onDeleteVisits() {
468
onPageExpired: function HT_onPageExpired(uri, time, entry) {
470
onBeforeDeleteURI: function onBeforeDeleteURI(uri) {
473
this._log.trace("onBeforeDeleteURI: " + uri.spec);
475
if (this.addChangedID(this._GUIDForUri(uri, true))) {
479
onDeleteURI: function HT_onDeleteURI(uri) {
481
onClearHistory: function HT_onClearHistory() {
482
this._log.trace("onClearHistory");