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 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740
|
/* ***** 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 the SyncPlaces extension.
*
* The Initial Developer of the Original Code is Andy Halford.
* Portions created by the Initial Developer are Copyright (C) 2008-2011
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* 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 ***** */
var SyncPlaces = {
Cc: Components.classes,
Ci: Components.interfaces,
jsonBackupFile: "syncplaces_backup.json",
xbelExportFile: "syncplaces_xbel.xml",
xbelJsonFile: "syncplaces.xbel.json",
serverPageFile: "syncplaces_server_page.html",
mergeFile: "syncplaces_merge.json",
JSON: 0,
HASH: 1,
XBEL: 2,
HTML: 3,
PWD : 4,
PWD_HASH: 5,
clearStatusTimeout: 2500,
currentTimeoutID: -1,
sideBarOpen: false,
organizerOpen: false,
//Calc the URI
getURI: function(type, fulluri, realm) {
var protocol = SyncPlacesOptions.prefs.getCharPref("protocol");
var uri = protocol + "://";
var path = "";
switch(type) {
case this.JSON:
path = SyncPlacesOptions.getComplex("path");
break;
case this.HASH:
var json = SyncPlacesOptions.prefs.getCharPref("sync_type") == 'sync_json';
path = SyncPlacesOptions.getComplex(json ? "path" : "xbelpath");
if (!path || SyncPlacesOptions.trim(path).length == 0) return null;
path = SyncPlacesOptions.trim(path) + ".sha1";
break;
case this.HTML:
path = SyncPlacesOptions.getComplex("htmlpath");
break;
case this.XBEL:
path = SyncPlacesOptions.getComplex("xbelpath");
break;
case this.PWD:
path = SyncPlacesOptions.getComplex("passwordpath");
break;
case this.PWD_HASH:
path = SyncPlacesOptions.getComplex("passwordpath");
if (!path || SyncPlacesOptions.trim(path).length == 0) return null;
path = SyncPlacesOptions.trim(path) + ".sha1";
break;
}
if (!path || SyncPlacesOptions.trim(path).length == 0) return null;
if (protocol == 'file') {
path = SyncPlacesOptions.trim(path);
return uri + path;
}
var host = SyncPlacesOptions.getComplex("host");
if (!host || SyncPlacesOptions.trim(host).length == 0) {
return null;
}
host = SyncPlacesOptions.trim(host);
//explicit ftp login details
var userid;
var password;
if (protocol == 'ftp') {
userid = SyncPlacesOptions.getComplex("userid");
password = SyncPlacesOptions.getPassword(userid, false);
}
//Strip out any embedded userid/password from the host
//for any protocol, not just ftp
var login = this.stripEmbeddedLogin(host, userid, password);
host = login.host;
userid = login.userid;
password = login.password;
//Calc the fulluri using details stored in password system
//unless there's an explicit userid for ftp
//Or it's ftp and you're skipping authentication altogether
if (fulluri && !userid &&
(protocol != 'ftp' || !SyncPlacesOptions.prefs.getBoolPref("skip_auth")))
{
try {
var loginManager = this.Cc["@mozilla.org/login-manager;1"]
.getService(this.Ci.nsILoginManager);
if (!realm) realm = "";
var logins = loginManager.findLogins({}, uri + host, null, realm);
//Find user/pass from returned array of nsILoginInfo objects
//use the last one found - ie most recently added
var userid;
var password;
for (var i = 0; i < logins.length; i++) {
userid = logins[i].username;
password = logins[i].password;
}
} catch (exception) {
//Components.utils.reportError(e);
}
}
if (userid && SyncPlacesOptions.trim(userid).length > 0) {
uri += encodeURIComponent(SyncPlacesOptions.trim(userid));
if (password && SyncPlacesOptions.trim(password).length > 0) {
//Dont trim the password in case it begins or ends with a space
uri += ":" + encodeURIComponent(password);
}
uri += "@";
}
uri = uri + host + SyncPlacesOptions.trim(path);
return uri;
},
stripEmbeddedLogin: function(host, userid, password) {
var login = {};
login.host = host;
login.userid = userid;
login.password = password;
var index = host.indexOf('@');
if (index != -1 && index != host.length-1) {
login.host = host.substring(index+1);
//Only use the embedded userid/password if there isn't an explicit one
if ((!userid || !password) && index != 0) {
login.userid = host.substring(0, index);
index = login.userid.indexOf(':');
if (index != -1) {
if (index != login.userid.length-1)
login.password = login.userid.substring(index+1);
if (index != 0)
login.userid = login.userid.substring(0, index);
}
}
}
return login;
},
importBookmarks: function() {
var bundle = Components.classes["@mozilla.org/intl/stringbundle;1"]
.getService(Components.interfaces.nsIStringBundleService)
.createBundle("chrome://syncplaces/locale/syncplaces.properties");
var nsIFilePicker = this.Ci.nsIFilePicker;
var fp = this.Cc["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
fp.init(window, bundle.GetStringFromName('importfile'), nsIFilePicker.modeOpen);
fp.appendFilters(fp.filterXML);
fp.defaultString=this.xbelExportFile;
if (fp.show() != nsIFilePicker.returnCancel) {
//Take a backup first
if (SyncPlaces.saveBookmarks(true, SyncPlaces.JSON, false, null)) {
try {
if (this.restoreBookmarks(this.xbelJsonFile, fp.file, true, true))
this.timedStatus('bookmarks_imported', true, false);
} catch (exception) {
SyncPlacesOptions.alert2(exception, 'cant_import_bookmarks', null, true);
}
}
}
window.setCursor("auto");
},
exportBookmarks: function() {
var bundle = Components.classes["@mozilla.org/intl/stringbundle;1"]
.getService(Components.interfaces.nsIStringBundleService)
.createBundle("chrome://syncplaces/locale/syncplaces.properties");
var nsIFilePicker = this.Ci.nsIFilePicker;
var fp = this.Cc["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
fp.init(window, bundle.GetStringFromName('exportfile'), nsIFilePicker.modeSave);
fp.appendFilters(fp.filterXML);
fp.defaultString=this.xbelExportFile;
if (fp.show() != nsIFilePicker.returnCancel) {
window.setCursor("wait"); //Do this after the file picker otherwise gets ignored
try {
SyncPlacesXBELOut(fp.file, true, true);
this.timedStatus('bookmarks_saved', true, false);
} catch (exception) {
SyncPlacesOptions.alert2(exception, 'cant_save_bookmarks', null, true);
}
}
window.setCursor("auto");
},
//Save bookmarks to local file
//Also save favicons
saveBookmarks: function(showAlert, type, checkSubFolder, backupFile) {
if (showAlert) window.setCursor("wait");
var backupFilePath = null;
try {
if (!backupFile) backupFile = this.jsonBackupFile;
backupFilePath = SyncPlacesIO.getDefaultFolder();
backupFilePath.append(backupFile);
//Create the backup file in the profile folder
if (!backupFilePath.exists()) {
backupFilePath.create(this.Ci.nsILocalFile.NORMAL_FILE_TYPE, 0600);
}
else if (!backupFilePath.isWritable()) {
this.timedStatus('cant_save_bookmarks', showAlert, true);
if (showAlert) window.setCursor("auto");
return null;
}
switch(type) {
case this.JSON:
if (!SyncPlacesBookmarks.backupJSON(backupFilePath, checkSubFolder, showAlert)) {
this.timedStatus('cant_save_bookmarks', showAlert, true);
if (showAlert) window.setCursor("auto");
return null;
}
//Save favicons (ignore failures) whenever take a full backup (manual or before receive)
if (!checkSubFolder) SyncPlacesBookmarks.saveFavicons();
break;
case this.HTML:
var ioService = this.Cc["@mozilla.org/browser/places/import-export-service;1"].getService(this.Ci.nsIPlacesImportExportService);
ioService.exportHTMLToFile(backupFilePath);
break;
case this.XBEL:
SyncPlacesXBELOut(backupFilePath, checkSubFolder, showAlert);
break;
}
} catch (exception) {
SyncPlacesOptions.alert2(exception, 'cant_save_bookmarks', null, showAlert);
if (showAlert) window.setCursor("auto");
return null;
}
if (showAlert) {
this.timedStatus('bookmarks_saved', showAlert, false);
window.setCursor("auto");
}
return backupFilePath;
},
//Restore from a local file (if any)
restoreBookmarks: function(fileToRestore, xbelFilePath, inActions, xbelImport) {
var result = false;
if (inActions) window.setCursor("wait");
this.closeSidebarOrganiser();
//Convert the XBEL file into a JSON file
var xbel = (xbelFilePath != null);
if (!xbel || SyncPlacesXBELIn(xbelFilePath, inActions)) {
//Default to a full restore of the backup file
//It shouldn't allow merge or subfolder
var allowMergeAndSubFolder = true;
if (!fileToRestore) {
fileToRestore = this.jsonBackupFile;
allowMergeAndSubFolder = false;
}
//Restore bookmarks from the bookmarks file
try {
var filePath = SyncPlacesIO.getDefaultFolder();
filePath.append(fileToRestore);
if (filePath.exists()) {
//Calc the adds/dels since last send/receive
var addsDels = {};
addsDels.matchingIds = [];
addsDels.missingNodes = [];
addsDels.oldNodes = [];
if (allowMergeAndSubFolder && SyncPlacesOptions.prefs.getBoolPref("merge") &&
SyncPlacesOptions.prefs.getBoolPref("merge_deletes") && !xbelImport)
{
try {
SyncPlacesMerge.compare(addsDels);
} catch(e) {
if (SyncPlacesOptions.prefs.getBoolPref("debug")) Components.utils.reportError(e);
}
}
//Convert bookmarks to nodes
var nodes = PlacesUtils.unwrapNodes(SyncPlacesIO.readFile(filePath), PlacesUtils.TYPE_X_MOZ_PLACE_CONTAINER);
//Now restore/import etc from these nodes
var stats = {};
stats.added = 0;
stats.addedFolder = 0;
stats.deletes = 0;
stats.folderDeletes = 0;
if (!SyncPlacesUtils.restoreBookmarksFromJSONString(nodes, addsDels, allowMergeAndSubFolder, inActions, xbelImport, stats)) {
this.timedStatus('cant_restore_bookmarks', inActions, true);
}
else {
result = true;
if (fileToRestore == this.jsonBackupFile) this.timedStatus('bookmarks_restored', inActions, false);
//Full restore invalidates the sync settings for mergeDeletes safety
if (!allowMergeAndSubFolder) {
SyncPlacesOptions.invalidateSyncSettings();
SyncPlacesOptions.lastTransferTimes();
}
//Display stats
this.timedStatus(null, inActions, false, stats);
}
}
else {
this.timedStatus('no_backup_to_restore', inActions, true);
}
//Restore any missing favicons
SyncPlacesBookmarks.restoreFavicons();
} catch (exception) {
SyncPlacesOptions.alert2(exception, 'invalid_bookmarks', null, inActions);
}
}
this.openSidebarOrganiser()
if (inActions) window.setCursor("auto");
return result;
},
//Closes the sidebar and bookmarks organiser windows
//Otherwise can hang when lots of bookmarks and these are open
closeSidebarOrganiser: function() {
var wm = this.Cc["@mozilla.org/appshell/window-mediator;1"].getService(this.Ci.nsIWindowMediator);
var browserWindow = wm.getMostRecentWindow("navigator:browser");
this.sideBarOpen = false;
this.organizerOpen = false;
//Is the sideBar open
var sidebar = browserWindow.document.getElementById("sidebar-box");
if (!sidebar.hidden) {
//If displaying bookmarks then close it
if (sidebar.getAttribute("sidebarcommand") == "viewBookmarksSidebar") {
browserWindow.toggleSidebar("viewBookmarksSidebar");
this.sideBarOpen = true; //Set flag so that open it again afterwards
}
}
//Is the organizer open - if so close it
var enumerator = wm.getEnumerator("Places:Organizer");
while(enumerator.hasMoreElements()) {
var win = enumerator.getNext();
win.close();
this.organizerOpen = true;
}
},
//Closes the sidebar and bookmarks organiser windows
//Otherwise can hang when lots of bookmarks and these are open
openSidebarOrganiser: function() {
var wm = this.Cc["@mozilla.org/appshell/window-mediator;1"].getService(this.Ci.nsIWindowMediator);
var browserWindow = wm.getMostRecentWindow("navigator:browser");
//Was the sideBar open?
if (this.sideBarOpen) browserWindow.toggleSidebar("viewBookmarksSidebar");
//Was the organizer open?
//This will hang until library closed
// if (this.organizerOpen) openDialog("chrome://browser/content/places/places.xul", "", "chrome,toolbar=yes,dialog=no,resizable");
//Bring SyncPlaces to the front again
window.focus();
},
timedStatus: function(message, timeout, error, stats) {
function clearStatus() {
document.getElementById("status").value = "";
}
window.clearTimeout(this.currentTimeoutID);
if (error) {
SyncPlacesNetworking.running = false;
//Force transfer window to close when specifically requested for errors
var prefs = SyncPlaces.Cc["@mozilla.org/preferences-service;1"]
.getService(SyncPlaces.Ci.nsIPrefService)
.getBranch("extensions.syncplaces.");
if (!timeout && prefs.getBoolPref("timeout"))
setTimeout(window.close, this.clearStatusTimeout);
}
var status;
var msg;
try {
status = document.getElementById("status");
if (!error && document.getElementById("sp_meter")) {
document.getElementById("sp_meter").mode="determined";
document.getElementById("sp_meter").value = 0;
}
var bundle = Components.classes["@mozilla.org/intl/stringbundle;1"]
.getService(Components.interfaces.nsIStringBundleService)
.createBundle("chrome://syncplaces/locale/syncplaces.properties");
if (!message && stats) {
var placesAdded = bundle.GetStringFromName('places_added') + stats.added;
var foldersAdded = bundle.GetStringFromName('folders_added') + stats.addedFolder;
var placesDeleted = bundle.GetStringFromName('places_deleted') + stats.deletes;
var foldersDeleted = bundle.GetStringFromName('folders_deleted') + stats.folderDeletes;
var passwordsAdded = bundle.GetStringFromName('passwords_added') + stats.pwadded;
//NOTE: TODO: the msg is pointless here as gets displayed on screen for too short a time
msg = "";
if (stats.added) {
SyncPlacesOptions.message(placesAdded);
msg += placesAdded + " ";
}
if (stats.addedFolder) {
SyncPlacesOptions.message(foldersAdded);
msg += foldersAdded + " ";
}
if (stats.deletes) {
SyncPlacesOptions.message(placesDeleted);
msg += placesDeleted + " ";
}
if (stats.folderDeletes) {
SyncPlacesOptions.message(foldersDeleted);
msg += foldersDeleted + " ";
}
if (stats.pwadded) {
SyncPlacesOptions.message(passwordsAdded);
msg += passwordsAdded + " ";
}
}
//Get the message
else
msg = bundle.GetStringFromName(message);
} catch (e) {
}
//If no status then must be windowless
if (!status) {
if (error) {
var params = {inn:{status:message}, out:null};
var dialog = window.openDialog('chrome://syncplaces/content/error.xul', '_blank',
'chrome,resizable,modal,centerscreen', params);
}
//Send message to console (will not work with 3.0 at present, 3.5+ is fine)
if (msg) SyncPlacesOptions.message(msg);
}
//Display the message on screen
else {
if (msg) status.value = msg;
if (timeout)
this.currentTimeoutID = setTimeout(clearStatus, this.clearStatusTimeout);
}
},
//Fired when error.xul is loaded (see above)
onErrorLoad: function() {
if (window.arguments) {
//Display any message
status = document.getElementById("status");
var bundle = Components.classes["@mozilla.org/intl/stringbundle;1"]
.getService(Components.interfaces.nsIStringBundleService)
.createBundle("chrome://syncplaces/locale/syncplaces.properties");
status.value = bundle.GetStringFromName(window.arguments[0].inn.status);
}
},
//Compute SHA1 hash of a string
computeHash: function(str) {
//Ignore dateAdded and lastModified dates
function stripTimestamps(str) {
if (!str) return str;
//General timestamps and livemark expiry's (13 & 16 digit numbers)
str = str.replace(/\d{12,16}/g, "");
//XBEL timestamps
return str.replace(/"\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d.\d\d\d"/g, "");
}
//Ignore the values of IDs
function stripIDs(str) {
if (!str) return str;
//JSON IDs
str = str.replace(/"id":\d{1,9},/g, "");
//XBEL IDs
str = str.replace(/ id="row\d{1,9}"/g, "");
return str;
}
//START HERE
//Strip timestamps first
str = stripTimestamps(str);
//Strip id's - these may not be the same if not using the merge option
str = stripIDs(str);
var converter = this.Cc["@mozilla.org/intl/scriptableunicodeconverter"].createInstance(this.Ci.nsIScriptableUnicodeConverter);
converter.charset = "UTF-8";
var result = {};
var data = converter.convertToByteArray(str, result);
var ch = this.Cc["@mozilla.org/security/hash;1"].createInstance(this.Ci.nsICryptoHash);
ch.init(ch.SHA1);
ch.update(data, data.length);
//Return it as a bin64 string (smaller than hex)
return ch.finish(true);
},
//Display communication error
displayError: function(errorCode, ignore404) {
var foundError = true;
switch (errorCode) {
case 0x804B0001:
this.timedStatus('NS_BINDING_FAILED', false, true);
break;
case 0x804B0002:
this.timedStatus('NS_BINDING_ABORTED', false, true);
break;
case 0x804B000A:
this.timedStatus('NS_ERROR_MALFORMED_URI', false, true);
break;
case 0x804B000D:
this.timedStatus('NS_ERROR_CONNECTION_REFUSED', false, true);
break;
case 0x804B000E:
this.timedStatus('NS_ERROR_NET_TIMEOUT', false, true);
break;
case 0x804B0010:
this.timedStatus('NS_ERROR_OFFLINE', false, true);
break;
case 0x804B0014:
this.timedStatus('NS_ERROR_NET_RESET', false, true);
break;
case 0x804B0015:
this.timedStatus('NS_ERROR_FTP_LOGIN', false, true);
break;
case 0x80520012: //NS_ERROR_FILE_NOT_FOUND
case 0x80004005: //NS_ERROR_FAILURE - general error
//NS_ERROR_INVALID_CONTENT_ENCODING
//when fails to receive a valid gzip file
case 0x804B001B:
case 0x804B0016: //NS_ERROR_FTP_CWD
if (ignore404)
foundError = false;
else
this.timedStatus('NS_ERROR_FTP_CWD', false, true);
break;
case 0x804B0017:
this.timedStatus('NS_ERROR_FTP_PASV', false, true);
break;
case 0x804B0018:
this.timedStatus('NS_ERROR_FTP_PWD', false, true);
break;
case 0x804B001C:
this.timedStatus('NS_ERROR_FTP_LIST', false, true);
break;
case 0x804B001E:
this.timedStatus('NS_ERROR_UNKNOWN_HOST', false, true);
break;
case 0x804B0046:
this.timedStatus('NS_ERROR_DOCUMENT_NOT_CACHED', false, true);
break;
case 0x804B0047:
this.timedStatus('NS_ERROR_NET_INTERRUPT', false, true);
break;
case 0x804B0048:
this.timedStatus('NS_ERROR_PROXY_CONNECTION_REFUSED', false, true);
break;
case 0x805A1FF3:
case 0x805A1FDC:
case 0x805A1FEC:
this.timedStatus('NS_ERROR_UNKNOWN_CERTIFICATE', false, true);
break;
default:
SyncPlacesOptions.alert2(null, 'connection_failed', errorCode.toString(16), false);
break;
}
return foundError;
},
//Check if data contains a web page and display it
//Dont display if auto-send/receive cos there may not be a browser to do so
displayWebPage: function(data, startupShutdown) {
if (!startupShutdown && (data != null) && (data.indexOf("<html") || data.indexOf("<HTML")) ) {
var thisBrowser = null;
try {
thisBrowser = window.opener.getBrowser();
} catch(e) {
var wm = this.Cc["@mozilla.org/appshell/window-mediator;1"].getService(this.Ci.nsIWindowMediator);
var mainWindow = wm.getMostRecentWindow("navigator:browser");
thisBrowser = mainWindow.getBrowser();
}
//Save the data and open a browser to read it
try {
SyncPlacesIO.saveFile(this.serverPageFile, data);
var serverPage = SyncPlacesIO.getDefaultFolder();
serverPage.append(this.serverPageFile);
var ios = this.Cc["@mozilla.org/network/io-service;1"].getService(this.Ci.nsIIOService);
var fileURL = ios.newFileURI(serverPage);
var tab = thisBrowser.addTab(fileURL.spec);
thisBrowser.selectedTab = tab;
} catch(e) {
}
}
},
//Mouse click events
handleEvent: function(event) {
//Left mouse click displays the actions
//Other Mouse (eg Mac: command+click) shows the actions
if (event.button == 0 && !(event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)) {
this.actionsOpen();
//Stop event bubbling up
event.preventDefault();
}
},
//Open actions window
actionsOpen: function(skipWizard) {
var params = null;
if (skipWizard) {
params = {inn:{skipWizard:true}, out:null}; //Skip the wizard when called from options.xul
}
window.openDialog('chrome://syncplaces/content/actions.xul', 'SyncPlaces', 'chrome,resizable,centerscreen', params);
},
//Open options window
optionsOpen: function() {
var params = {inn:{skipWizard:true}, out:null}; //Skip the wizard when called from actions.xul
window.openDialog('chrome://syncplaces/content/options.xul', '_blank', 'chrome,modal,centerscreen', params);
SyncPlacesOptions.lastTransferTimes(); //Update the last_* status just in case
return false; //TO keep the actions.xul window open
},
//Do send from menu
menuSend: function() {
SyncPlacesOptions.prefs.setBoolPref("startManualSend", true);
window.openDialog('chrome://syncplaces/content/transfer.xul', '_blank', 'chrome,resizable,modal,centerscreen', null);
},
//Do receive from menu
menuReceive: function() {
SyncPlacesOptions.prefs.setBoolPref("startManualReceive", true);
window.openDialog('chrome://syncplaces/content/transfer.xul', '_blank', 'chrome,resizable,modal,centerscreen', null);
},
//Are there any syncplaces windows showing?
anySPDialogs: function() {
try {
var wm = this.Cc["@mozilla.org/appshell/window-mediator;1"].getService(this.Ci.nsIWindowMediator);
var enumerator = wm.getEnumerator("syncPlacesType");
return enumerator.hasMoreElements();
} catch (exception) {
return false;
}
},
/* BROWSER LOAD AND UNLOAD */
//Initialise the interface (show/hide icons etc) when first loads a tab (and when first launched)
initialiseSP: function() {
window.removeEventListener("load", SyncPlaces.initialiseSP, false);
var prefs = SyncPlaces.Cc["@mozilla.org/preferences-service;1"]
.getService(SyncPlaces.Ci.nsIPrefService)
.getBranch("extensions.syncplaces.");
//If already synced from spObserver then ignore this method first time
//around otherwise it will mess up the automation
if (prefs.getBoolPref("autoStarted")) {
prefs.setBoolPref("autoStarted", false);
}
//Normal loading
else {
//Show/hide the status bar icon
var statusBar = document.getElementById("syncplaces-status");
if (statusBar) statusBar.hidden = !prefs.getBoolPref("statusbaricon");
//Bookmarks menu
var bmMenu = document.getElementById("syncplaces-bmenu");
if (bmMenu) bmMenu.hidden = !prefs.getBoolPref("bookmarks_menu");
//Tools menu
var toolsMenu = document.getElementById("syncplaces-tmenu");
if (toolsMenu) toolsMenu.hidden = !prefs.getBoolPref("tools_menu");
//If first time for first window (crude detection)
if (!prefs.getBoolPref("started")) {
prefs.setBoolPref("started", true);
//Crude startup detection ...
if (prefs.getCharPref("autostart_detection") == "autostart_crude") {
//Auto-start
if (prefs.getBoolPref("auto_receive") && !SyncPlaces.anySPDialogs()) {
prefs.setBoolPref("startAutoReceive", true);
window.openDialog('chrome://syncplaces/content/transfer.xul', '_blank',
'chrome,resizable,centerscreen', null);
}
}
//Automation
SyncPlacesListener.init();
//Listen for bookmark changes
PlacesUtils.bookmarks.addObserver(SyncPlacesListener, false);
}
}
}
};
window.addEventListener("load", SyncPlaces.initialiseSP, false);
|