setup.js 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. var Ci = Components.interfaces;
  5. var Cc = Components.classes;
  6. var Cr = Components.results;
  7. var Cu = Components.utils;
  8. // page consts
  9. const PAIR_PAGE = 0;
  10. const INTRO_PAGE = 1;
  11. const NEW_ACCOUNT_START_PAGE = 2;
  12. const EXISTING_ACCOUNT_CONNECT_PAGE = 3;
  13. const EXISTING_ACCOUNT_LOGIN_PAGE = 4;
  14. const OPTIONS_PAGE = 5;
  15. const OPTIONS_CONFIRM_PAGE = 6;
  16. // Broader than we'd like, but after this changed from api-secure.recaptcha.net
  17. // we had no choice. At least we only do this for the duration of setup.
  18. // See discussion in Bugs 508112 and 653307.
  19. const RECAPTCHA_DOMAIN = "https://www.google.com";
  20. const PIN_PART_LENGTH = 4;
  21. Cu.import("resource://services-sync/main.js");
  22. Cu.import("resource://gre/modules/XPCOMUtils.jsm");
  23. Cu.import("resource://gre/modules/Services.jsm");
  24. Cu.import("resource://gre/modules/PlacesUtils.jsm");
  25. Cu.import("resource://gre/modules/PluralForm.jsm");
  26. function setVisibility(element, visible) {
  27. element.style.visibility = visible ? "visible" : "hidden";
  28. }
  29. var gSyncSetup = {
  30. QueryInterface: XPCOMUtils.generateQI([Ci.nsISupports,
  31. Ci.nsIWebProgressListener,
  32. Ci.nsISupportsWeakReference]),
  33. captchaBrowser: null,
  34. wizard: null,
  35. _disabledSites: [],
  36. status: {
  37. password: false,
  38. email: false,
  39. server: false
  40. },
  41. get _remoteSites() [Weave.Service.serverURL, RECAPTCHA_DOMAIN],
  42. get _usingMainServers() {
  43. if (this._settingUpNew)
  44. return document.getElementById("server").selectedIndex == 0;
  45. return document.getElementById("existingServer").selectedIndex == 0;
  46. },
  47. init: function() {
  48. let obs = [
  49. ["weave:service:change-passphrase", "onResetPassphrase"],
  50. ["weave:service:login:start", "onLoginStart"],
  51. ["weave:service:login:error", "onLoginEnd"],
  52. ["weave:service:login:finish", "onLoginEnd"]];
  53. // Add the observers now and remove them on unload
  54. let self = this;
  55. let addRem = function(add) {
  56. obs.forEach(function([topic, func]) {
  57. //XXXzpao This should use Services.obs.* but Weave's Obs does nice handling
  58. // of `this`. Fix in a followup. (bug 583347)
  59. if (add)
  60. Weave.Svc.Obs.add(topic, self[func], self);
  61. else
  62. Weave.Svc.Obs.remove(topic, self[func], self);
  63. });
  64. };
  65. addRem(true);
  66. window.addEventListener("unload", function() addRem(false), false);
  67. window.setTimeout(function() {
  68. // Force Service to be loaded so that engines are registered.
  69. // See Bug 670082.
  70. Weave.Service;
  71. }, 0);
  72. this.captchaBrowser = document.getElementById("captcha");
  73. this.wizardType = null;
  74. if (window.arguments && window.arguments[0]) {
  75. this.wizardType = window.arguments[0];
  76. }
  77. switch (this.wizardType) {
  78. case null:
  79. this.wizard.pageIndex = INTRO_PAGE;
  80. // Fall through!
  81. case "pair":
  82. this.captchaBrowser.addProgressListener(this);
  83. Weave.Svc.Prefs.set("firstSync", "notReady");
  84. break;
  85. case "reset":
  86. this._resettingSync = true;
  87. this.wizard.pageIndex = OPTIONS_PAGE;
  88. break;
  89. }
  90. this.wizard.getButton("extra1").label =
  91. this._stringBundle.GetStringFromName("button.syncOptions.label");
  92. // Remember these values because the options pages change them temporarily.
  93. this._nextButtonLabel = this.wizard.getButton("next").label;
  94. this._nextButtonAccesskey = this.wizard.getButton("next")
  95. .getAttribute("accesskey");
  96. this._backButtonLabel = this.wizard.getButton("back").label;
  97. this._backButtonAccesskey = this.wizard.getButton("back")
  98. .getAttribute("accesskey");
  99. },
  100. startNewAccountSetup: function() {
  101. if (!Weave.Utils.ensureMPUnlocked())
  102. return false;
  103. this._settingUpNew = true;
  104. this.wizard.pageIndex = NEW_ACCOUNT_START_PAGE;
  105. },
  106. useExistingAccount: function() {
  107. if (!Weave.Utils.ensureMPUnlocked())
  108. return false;
  109. this._settingUpNew = false;
  110. if (this.wizardType == "pair") {
  111. // We're already pairing, so there's no point in pairing again.
  112. // Go straight to the manual login page.
  113. this.wizard.pageIndex = EXISTING_ACCOUNT_LOGIN_PAGE;
  114. } else {
  115. this.wizard.pageIndex = EXISTING_ACCOUNT_CONNECT_PAGE;
  116. }
  117. },
  118. resetPassphrase: function() {
  119. // Apply the existing form fields so that
  120. // Weave.Service.changePassphrase() has the necessary credentials.
  121. Weave.Service.identity.account = document.getElementById("existingAccountName").value;
  122. Weave.Service.identity.basicPassword = document.getElementById("existingPassword").value;
  123. // Generate a new passphrase so that Weave.Service.login() will
  124. // actually do something.
  125. let passphrase = Weave.Utils.generatePassphrase();
  126. Weave.Service.identity.syncKey = passphrase;
  127. // Only open the dialog if username + password are actually correct.
  128. Weave.Service.login();
  129. if ([Weave.LOGIN_FAILED_INVALID_PASSPHRASE,
  130. Weave.LOGIN_FAILED_NO_PASSPHRASE,
  131. Weave.LOGIN_SUCCEEDED].indexOf(Weave.Status.login) == -1) {
  132. return;
  133. }
  134. // Hide any errors about the passphrase, we know it's not right.
  135. let feedback = document.getElementById("existingPassphraseFeedbackRow");
  136. feedback.hidden = true;
  137. let el = document.getElementById("existingPassphrase");
  138. el.value = Weave.Utils.hyphenatePassphrase(passphrase);
  139. // changePassphrase() will sync, make sure we set the "firstSync" pref
  140. // according to the user's pref.
  141. Weave.Svc.Prefs.reset("firstSync");
  142. this.setupInitialSync();
  143. gSyncUtils.resetPassphrase(true);
  144. },
  145. onResetPassphrase: function() {
  146. document.getElementById("existingPassphrase").value =
  147. Weave.Utils.hyphenatePassphrase(Weave.Service.identity.syncKey);
  148. this.checkFields();
  149. this.wizard.advance();
  150. },
  151. onLoginStart: function() {
  152. this.toggleLoginFeedback(false);
  153. },
  154. onLoginEnd: function() {
  155. this.toggleLoginFeedback(true);
  156. },
  157. sendCredentialsAfterSync: function() {
  158. let send = function() {
  159. Services.obs.removeObserver("weave:service:sync:finish", send);
  160. Services.obs.removeObserver("weave:service:sync:error", send);
  161. let credentials = {account: Weave.Service.identity.account,
  162. password: Weave.Service.identity.basicPassword,
  163. synckey: Weave.Service.identity.syncKey,
  164. serverURL: Weave.Service.serverURL};
  165. this._jpakeclient.sendAndComplete(credentials);
  166. }.bind(this);
  167. Services.obs.addObserver("weave:service:sync:finish", send, false);
  168. Services.obs.addObserver("weave:service:sync:error", send, false);
  169. },
  170. toggleLoginFeedback: function(stop) {
  171. document.getElementById("login-throbber").hidden = stop;
  172. let password = document.getElementById("existingPasswordFeedbackRow");
  173. let server = document.getElementById("existingServerFeedbackRow");
  174. let passphrase = document.getElementById("existingPassphraseFeedbackRow");
  175. if (!stop || (Weave.Status.login == Weave.LOGIN_SUCCEEDED)) {
  176. password.hidden = server.hidden = passphrase.hidden = true;
  177. return;
  178. }
  179. let feedback;
  180. switch (Weave.Status.login) {
  181. case Weave.LOGIN_FAILED_NETWORK_ERROR:
  182. case Weave.LOGIN_FAILED_SERVER_ERROR:
  183. feedback = server;
  184. break;
  185. case Weave.LOGIN_FAILED_LOGIN_REJECTED:
  186. case Weave.LOGIN_FAILED_NO_USERNAME:
  187. case Weave.LOGIN_FAILED_NO_PASSWORD:
  188. feedback = password;
  189. break;
  190. case Weave.LOGIN_FAILED_INVALID_PASSPHRASE:
  191. feedback = passphrase;
  192. break;
  193. }
  194. this._setFeedbackMessage(feedback, false, Weave.Status.login);
  195. },
  196. setupInitialSync: function() {
  197. let action = document.getElementById("mergeChoiceRadio").selectedItem.id;
  198. switch (action) {
  199. case "resetClient":
  200. // if we're not resetting sync, we don't need to explicitly
  201. // call resetClient
  202. if (!this._resettingSync)
  203. return;
  204. // otherwise, fall through
  205. case "wipeClient":
  206. case "wipeRemote":
  207. Weave.Svc.Prefs.set("firstSync", action);
  208. break;
  209. }
  210. },
  211. // fun with validation!
  212. checkFields: function() {
  213. this.wizard.canAdvance = this.readyToAdvance();
  214. },
  215. readyToAdvance: function() {
  216. switch (this.wizard.pageIndex) {
  217. case INTRO_PAGE:
  218. return false;
  219. case NEW_ACCOUNT_START_PAGE:
  220. for (let i in this.status) {
  221. if (!this.status[i])
  222. return false;
  223. }
  224. if (this._usingMainServers)
  225. return document.getElementById("tos").checked;
  226. return true;
  227. case EXISTING_ACCOUNT_LOGIN_PAGE:
  228. let hasUser = document.getElementById("existingAccountName").value != "";
  229. let hasPass = document.getElementById("existingPassword").value != "";
  230. let hasKey = document.getElementById("existingPassphrase").value != "";
  231. if (hasUser && hasPass && hasKey) {
  232. if (this._usingMainServers)
  233. return true;
  234. if (this._validateServer(document.getElementById("existingServer"))) {
  235. return true;
  236. }
  237. }
  238. return false;
  239. }
  240. // Default, e.g. wizard's special page -1 etc.
  241. return true;
  242. },
  243. onPINInput: function onPINInput(textbox) {
  244. if (textbox && textbox.value.length == PIN_PART_LENGTH) {
  245. this.nextFocusEl[textbox.id].focus();
  246. }
  247. this.wizard.canAdvance = (this.pin1.value.length == PIN_PART_LENGTH &&
  248. this.pin2.value.length == PIN_PART_LENGTH &&
  249. this.pin3.value.length == PIN_PART_LENGTH);
  250. },
  251. onEmailInput: function() {
  252. // Check account validity when the user stops typing for 1 second.
  253. if (this._checkAccountTimer)
  254. window.clearTimeout(this._checkAccountTimer);
  255. this._checkAccountTimer = window.setTimeout(function() {
  256. gSyncSetup.checkAccount();
  257. }, 1000);
  258. },
  259. checkAccount: function() {
  260. delete this._checkAccountTimer;
  261. let value = Weave.Utils.normalizeAccount(
  262. document.getElementById("weaveEmail").value);
  263. if (!value) {
  264. this.status.email = false;
  265. this.checkFields();
  266. return;
  267. }
  268. let re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  269. let feedback = document.getElementById("emailFeedbackRow");
  270. let valid = re.test(value);
  271. let str = "";
  272. if (!valid) {
  273. str = "invalidEmail.label";
  274. } else {
  275. let availCheck = Weave.Service.checkAccount(value);
  276. valid = availCheck == "available";
  277. if (!valid) {
  278. if (availCheck == "notAvailable")
  279. str = "usernameNotAvailable.label";
  280. else
  281. str = availCheck;
  282. }
  283. }
  284. this._setFeedbackMessage(feedback, valid, str);
  285. this.status.email = valid;
  286. if (valid)
  287. Weave.Service.identity.account = value;
  288. this.checkFields();
  289. },
  290. onPasswordChange: function() {
  291. let password = document.getElementById("weavePassword");
  292. let pwconfirm = document.getElementById("weavePasswordConfirm");
  293. let [valid, errorString] = gSyncUtils.validatePassword(password, pwconfirm);
  294. let feedback = document.getElementById("passwordFeedbackRow");
  295. this._setFeedback(feedback, valid, errorString);
  296. this.status.password = valid;
  297. this.checkFields();
  298. },
  299. onPageShow: function() {
  300. switch (this.wizard.pageIndex) {
  301. case PAIR_PAGE:
  302. this.wizard.getButton("back").hidden = true;
  303. this.wizard.getButton("extra1").hidden = true;
  304. this.onPINInput();
  305. this.pin1.focus();
  306. break;
  307. case INTRO_PAGE:
  308. // We may not need the captcha in the Existing Account branch of the
  309. // wizard. However, we want to preload it to avoid any flickering while
  310. // the Create Account page is shown.
  311. this.loadCaptcha();
  312. this.wizard.getButton("next").hidden = true;
  313. this.wizard.getButton("back").hidden = true;
  314. this.wizard.getButton("extra1").hidden = true;
  315. this.checkFields();
  316. break;
  317. case NEW_ACCOUNT_START_PAGE:
  318. this.wizard.getButton("extra1").hidden = false;
  319. this.wizard.getButton("next").hidden = false;
  320. this.wizard.getButton("back").hidden = false;
  321. this.onServerCommand();
  322. this.wizard.canRewind = true;
  323. this.checkFields();
  324. break;
  325. case EXISTING_ACCOUNT_CONNECT_PAGE:
  326. Weave.Svc.Prefs.set("firstSync", "existingAccount");
  327. this.wizard.getButton("next").hidden = false;
  328. this.wizard.getButton("back").hidden = false;
  329. this.wizard.getButton("extra1").hidden = false;
  330. this.wizard.canAdvance = false;
  331. this.wizard.canRewind = true;
  332. this.startEasySetup();
  333. break;
  334. case EXISTING_ACCOUNT_LOGIN_PAGE:
  335. this.wizard.getButton("next").hidden = false;
  336. this.wizard.getButton("back").hidden = false;
  337. this.wizard.getButton("extra1").hidden = false;
  338. this.wizard.canRewind = true;
  339. this.checkFields();
  340. break;
  341. case OPTIONS_PAGE:
  342. this.wizard.canRewind = false;
  343. this.wizard.canAdvance = true;
  344. if (!this._resettingSync) {
  345. this.wizard.getButton("next").label =
  346. this._stringBundle.GetStringFromName("button.syncOptionsDone.label");
  347. this.wizard.getButton("next").removeAttribute("accesskey");
  348. }
  349. this.wizard.getButton("next").hidden = false;
  350. this.wizard.getButton("back").hidden = true;
  351. this.wizard.getButton("cancel").hidden = !this._resettingSync;
  352. this.wizard.getButton("extra1").hidden = true;
  353. document.getElementById("syncComputerName").value = Weave.Service.clientsEngine.localName;
  354. document.getElementById("syncOptions").collapsed = this._resettingSync;
  355. document.getElementById("mergeOptions").collapsed = this._settingUpNew;
  356. break;
  357. case OPTIONS_CONFIRM_PAGE:
  358. this.wizard.canRewind = true;
  359. this.wizard.canAdvance = true;
  360. this.wizard.getButton("back").label =
  361. this._stringBundle.GetStringFromName("button.syncOptionsCancel.label");
  362. this.wizard.getButton("back").removeAttribute("accesskey");
  363. this.wizard.getButton("back").hidden = this._resettingSync;
  364. this.wizard.getButton("next").hidden = false;
  365. this.wizard.getButton("finish").hidden = true;
  366. break;
  367. }
  368. },
  369. onWizardAdvance: function() {
  370. // Check pageIndex so we don't prompt before the Sync setup wizard appears.
  371. // This is a fallback in case the Master Password gets locked mid-wizard.
  372. if ((this.wizard.pageIndex >= 0) &&
  373. !Weave.Utils.ensureMPUnlocked()) {
  374. return false;
  375. }
  376. switch (this.wizard.pageIndex) {
  377. case PAIR_PAGE:
  378. this.startPairing();
  379. return false;
  380. case NEW_ACCOUNT_START_PAGE:
  381. // If the user selects Next (e.g. by hitting enter) when we haven't
  382. // executed the delayed checks yet, execute them immediately.
  383. if (this._checkAccountTimer) {
  384. this.checkAccount();
  385. }
  386. if (this._checkServerTimer) {
  387. this.checkServer();
  388. }
  389. if (!this.wizard.canAdvance) {
  390. return false;
  391. }
  392. let doc = this.captchaBrowser.contentDocument;
  393. let getField = function getField(field) {
  394. let node = doc.getElementById("recaptcha_" + field + "_field");
  395. return node && node.value;
  396. };
  397. // Display throbber
  398. let feedback = document.getElementById("captchaFeedback");
  399. let image = feedback.firstChild;
  400. let label = image.nextSibling;
  401. image.setAttribute("status", "active");
  402. label.value = this._stringBundle.GetStringFromName("verifying.label");
  403. setVisibility(feedback, true);
  404. let password = document.getElementById("weavePassword").value;
  405. let email = Weave.Utils.normalizeAccount(
  406. document.getElementById("weaveEmail").value);
  407. let challenge = getField("challenge");
  408. let response = getField("response");
  409. let error = Weave.Service.createAccount(email, password,
  410. challenge, response);
  411. if (error == null) {
  412. Weave.Service.identity.account = email;
  413. Weave.Service.identity.basicPassword = password;
  414. Weave.Service.identity.syncKey = Weave.Utils.generatePassphrase();
  415. this._handleNoScript(false);
  416. Weave.Svc.Prefs.set("firstSync", "newAccount");
  417. this.wizardFinish();
  418. return false;
  419. }
  420. image.setAttribute("status", "error");
  421. label.value = Weave.Utils.getErrorString(error);
  422. return false;
  423. case EXISTING_ACCOUNT_LOGIN_PAGE:
  424. Weave.Service.identity.account = Weave.Utils.normalizeAccount(
  425. document.getElementById("existingAccountName").value);
  426. Weave.Service.identity.basicPassword =
  427. document.getElementById("existingPassword").value;
  428. let pp = document.getElementById("existingPassphrase").value;
  429. Weave.Service.identity.syncKey = Weave.Utils.normalizePassphrase(pp);
  430. if (Weave.Service.login()) {
  431. this.wizardFinish();
  432. }
  433. return false;
  434. case OPTIONS_PAGE:
  435. let desc = document.getElementById("mergeChoiceRadio").selectedIndex;
  436. // No confirmation needed on new account setup or merge option
  437. // with existing account.
  438. if (this._settingUpNew || (!this._resettingSync && desc == 0))
  439. return this.returnFromOptions();
  440. return this._handleChoice();
  441. case OPTIONS_CONFIRM_PAGE:
  442. if (this._resettingSync) {
  443. this.wizardFinish();
  444. return false;
  445. }
  446. return this.returnFromOptions();
  447. }
  448. return true;
  449. },
  450. onWizardBack: function() {
  451. switch (this.wizard.pageIndex) {
  452. case NEW_ACCOUNT_START_PAGE:
  453. case EXISTING_ACCOUNT_LOGIN_PAGE:
  454. this.wizard.pageIndex = INTRO_PAGE;
  455. return false;
  456. case EXISTING_ACCOUNT_CONNECT_PAGE:
  457. this.abortEasySetup();
  458. this.wizard.pageIndex = INTRO_PAGE;
  459. return false;
  460. case EXISTING_ACCOUNT_LOGIN_PAGE:
  461. // If we were already pairing on entry, we went straight to the manual
  462. // login page. If subsequently we go back, return to the page that lets
  463. // us choose whether we already have an account.
  464. if (this.wizardType == "pair") {
  465. this.wizard.pageIndex = INTRO_PAGE;
  466. return false;
  467. }
  468. return true;
  469. case OPTIONS_CONFIRM_PAGE:
  470. // Backing up from the confirmation page = resetting first sync to merge.
  471. document.getElementById("mergeChoiceRadio").selectedIndex = 0;
  472. return this.returnFromOptions();
  473. }
  474. return true;
  475. },
  476. wizardFinish: function() {
  477. this.setupInitialSync();
  478. if (this.wizardType == "pair") {
  479. this.completePairing();
  480. }
  481. if (!this._resettingSync) {
  482. function isChecked(element) {
  483. return document.getElementById(element).hasAttribute("checked");
  484. }
  485. let prefs = ["engine.bookmarks", "engine.passwords", "engine.history",
  486. "engine.tabs", "engine.prefs", "engine.addons"];
  487. for (let i = 0;i < prefs.length;i++) {
  488. Weave.Svc.Prefs.set(prefs[i], isChecked(prefs[i]));
  489. }
  490. // XXX: Addons syncing is currently not operational;
  491. // Make doubly-sure to always disable addons syncing pref
  492. Weave.Svc.Prefs.set("engine.addons", false);
  493. this._handleNoScript(false);
  494. if (Weave.Svc.Prefs.get("firstSync", "") == "notReady")
  495. Weave.Svc.Prefs.reset("firstSync");
  496. Weave.Service.persistLogin();
  497. Weave.Svc.Obs.notify("weave:service:setup-complete");
  498. gSyncUtils.openFirstSyncProgressPage();
  499. }
  500. Weave.Utils.nextTick(Weave.Service.sync, Weave.Service);
  501. window.close();
  502. },
  503. onWizardCancel: function() {
  504. if (this._resettingSync)
  505. return;
  506. this.abortEasySetup();
  507. this._handleNoScript(false);
  508. Weave.Service.startOver();
  509. },
  510. onSyncOptions: function() {
  511. this._beforeOptionsPage = this.wizard.pageIndex;
  512. this.wizard.pageIndex = OPTIONS_PAGE;
  513. },
  514. returnFromOptions: function() {
  515. this.wizard.getButton("next").label = this._nextButtonLabel;
  516. this.wizard.getButton("next").setAttribute("accesskey",
  517. this._nextButtonAccesskey);
  518. this.wizard.getButton("back").label = this._backButtonLabel;
  519. this.wizard.getButton("back").setAttribute("accesskey",
  520. this._backButtonAccesskey);
  521. this.wizard.getButton("cancel").hidden = false;
  522. this.wizard.getButton("extra1").hidden = false;
  523. this.wizard.pageIndex = this._beforeOptionsPage;
  524. return false;
  525. },
  526. startPairing: function() {
  527. this.pairDeviceErrorRow.hidden = true;
  528. // When onAbort is called, Weave may already be gone.
  529. const JPAKE_ERROR_USERABORT = Weave.JPAKE_ERROR_USERABORT;
  530. let self = this;
  531. let jpakeclient = this._jpakeclient = new Weave.JPAKEClient({
  532. onPaired: function onPaired() {
  533. self.wizard.pageIndex = INTRO_PAGE;
  534. },
  535. onComplete: function() {
  536. // This method will never be called since SendCredentialsController
  537. // will take over after the wizard completes.
  538. },
  539. onAbort: function(error) {
  540. delete self._jpakeclient;
  541. // Aborted by user, ignore. The window is almost certainly going to close
  542. // or is already closed.
  543. if (error == JPAKE_ERROR_USERABORT) {
  544. return;
  545. }
  546. self.pairDeviceErrorRow.hidden = false;
  547. self.pairDeviceThrobber.hidden = true;
  548. self.pin1.value = self.pin2.value = self.pin3.value = "";
  549. self.pin1.disabled = self.pin2.disabled = self.pin3.disabled = false;
  550. if (self.wizard.pageIndex == PAIR_PAGE) {
  551. self.pin1.focus();
  552. }
  553. }
  554. });
  555. this.pairDeviceThrobber.hidden = false;
  556. this.pin1.disabled = this.pin2.disabled = this.pin3.disabled = true;
  557. this.wizard.canAdvance = false;
  558. let pin = this.pin1.value + this.pin2.value + this.pin3.value;
  559. let expectDelay = true;
  560. jpakeclient.pairWithPIN(pin, expectDelay);
  561. },
  562. completePairing: function() {
  563. if (!this._jpakeclient) {
  564. // The channel was aborted while we were setting up the account
  565. // locally. XXX TODO should we do anything here, e.g. tell
  566. // the user on the last wizard page that it's ok, they just
  567. // have to pair again?
  568. return;
  569. }
  570. let controller = new Weave.SendCredentialsController(this._jpakeclient,
  571. Weave.Service);
  572. this._jpakeclient.controller = controller;
  573. },
  574. startEasySetup: function() {
  575. // Don't do anything if we have a client already (e.g. we went to
  576. // Sync Options and just came back).
  577. if (this._jpakeclient)
  578. return;
  579. // When onAbort is called, Weave may already be gone
  580. const JPAKE_ERROR_USERABORT = Weave.JPAKE_ERROR_USERABORT;
  581. let self = this;
  582. this._jpakeclient = new Weave.JPAKEClient({
  583. displayPIN: function(pin) {
  584. document.getElementById("easySetupPIN1").value = pin.slice(0, 4);
  585. document.getElementById("easySetupPIN2").value = pin.slice(4, 8);
  586. document.getElementById("easySetupPIN3").value = pin.slice(8);
  587. },
  588. onPairingStart: function() {},
  589. onComplete: function(credentials) {
  590. Weave.Service.identity.account = credentials.account;
  591. Weave.Service.identity.basicPassword = credentials.password;
  592. Weave.Service.identity.syncKey = credentials.synckey;
  593. Weave.Service.serverURL = credentials.serverURL;
  594. gSyncSetup.wizardFinish();
  595. },
  596. onAbort: function(error) {
  597. delete self._jpakeclient;
  598. // Ignore if wizard is aborted.
  599. if (error == JPAKE_ERROR_USERABORT)
  600. return;
  601. // Automatically go to manual setup if we couldn't acquire a channel.
  602. if (error == Weave.JPAKE_ERROR_CHANNEL) {
  603. self.wizard.pageIndex = EXISTING_ACCOUNT_LOGIN_PAGE;
  604. return;
  605. }
  606. // Restart on all other errors.
  607. self.startEasySetup();
  608. }
  609. });
  610. this._jpakeclient.receiveNoPIN();
  611. },
  612. abortEasySetup: function() {
  613. document.getElementById("easySetupPIN1").value = "";
  614. document.getElementById("easySetupPIN2").value = "";
  615. document.getElementById("easySetupPIN3").value = "";
  616. if (!this._jpakeclient)
  617. return;
  618. this._jpakeclient.abort();
  619. delete this._jpakeclient;
  620. },
  621. manualSetup: function() {
  622. this.abortEasySetup();
  623. this.wizard.pageIndex = EXISTING_ACCOUNT_LOGIN_PAGE;
  624. },
  625. // _handleNoScript is needed because it blocks the captcha. So we temporarily
  626. // allow the necessary sites so that we can verify the user is in fact a human.
  627. // This was done with the help of Giorgio (NoScript author). See bug 508112.
  628. _handleNoScript: function(addExceptions) {
  629. // if NoScript isn't installed, or is disabled, bail out.
  630. let ns = Cc["@maone.net/noscript-service;1"];
  631. if (ns == null)
  632. return;
  633. ns = ns.getService().wrappedJSObject;
  634. if (addExceptions) {
  635. this._remoteSites.forEach(function(site) {
  636. site = ns.getSite(site);
  637. if (!ns.isJSEnabled(site)) {
  638. this._disabledSites.push(site); // save status
  639. ns.setJSEnabled(site, true); // allow site
  640. }
  641. }, this);
  642. }
  643. else {
  644. this._disabledSites.forEach(function(site) {
  645. ns.setJSEnabled(site, false);
  646. });
  647. this._disabledSites = [];
  648. }
  649. },
  650. onExistingServerCommand: function() {
  651. let control = document.getElementById("existingServer");
  652. if (control.selectedIndex == 0) {
  653. control.removeAttribute("editable");
  654. Weave.Svc.Prefs.reset("serverURL");
  655. } else {
  656. control.setAttribute("editable", "true");
  657. // Force a style flush to ensure that the binding is attached.
  658. control.clientTop;
  659. control.value = "";
  660. control.inputField.focus();
  661. }
  662. document.getElementById("existingServerFeedbackRow").hidden = true;
  663. this.checkFields();
  664. },
  665. onExistingServerInput: function() {
  666. // Check custom server validity when the user stops typing for 1 second.
  667. if (this._existingServerTimer)
  668. window.clearTimeout(this._existingServerTimer);
  669. this._existingServerTimer = window.setTimeout(function() {
  670. gSyncSetup.checkFields();
  671. }, 1000);
  672. },
  673. onServerCommand: function() {
  674. setVisibility(document.getElementById("TOSRow"), this._usingMainServers);
  675. let control = document.getElementById("server");
  676. if (!this._usingMainServers) {
  677. control.setAttribute("editable", "true");
  678. // Force a style flush to ensure that the binding is attached.
  679. control.clientTop;
  680. control.value = "";
  681. control.inputField.focus();
  682. // checkServer() will call checkAccount() and checkFields().
  683. this.checkServer();
  684. return;
  685. }
  686. control.removeAttribute("editable");
  687. Weave.Svc.Prefs.reset("serverURL");
  688. if (this._settingUpNew) {
  689. this.loadCaptcha();
  690. }
  691. this.checkAccount();
  692. this.status.server = true;
  693. document.getElementById("serverFeedbackRow").hidden = true;
  694. this.checkFields();
  695. },
  696. onServerInput: function() {
  697. // Check custom server validity when the user stops typing for 1 second.
  698. if (this._checkServerTimer)
  699. window.clearTimeout(this._checkServerTimer);
  700. this._checkServerTimer = window.setTimeout(function() {
  701. gSyncSetup.checkServer();
  702. }, 1000);
  703. },
  704. checkServer: function() {
  705. delete this._checkServerTimer;
  706. let el = document.getElementById("server");
  707. let valid = false;
  708. let feedback = document.getElementById("serverFeedbackRow");
  709. let str = "";
  710. if (el.value) {
  711. valid = this._validateServer(el);
  712. let str = valid ? "" : "serverInvalid.label";
  713. this._setFeedbackMessage(feedback, valid, str);
  714. }
  715. else
  716. this._setFeedbackMessage(feedback, true);
  717. // Recheck account against the new server.
  718. if (valid)
  719. this.checkAccount();
  720. this.status.server = valid;
  721. this.checkFields();
  722. },
  723. _validateServer: function(element) {
  724. let valid = false;
  725. let val = element.value;
  726. if (!val)
  727. return false;
  728. let uri = Weave.Utils.makeURI(val);
  729. if (!uri)
  730. uri = Weave.Utils.makeURI("https://" + val);
  731. if (uri && this._settingUpNew) {
  732. function isValid(uri) {
  733. Weave.Service.serverURL = uri.spec;
  734. let check = Weave.Service.checkAccount("a");
  735. return (check == "available" || check == "notAvailable");
  736. }
  737. if (uri.schemeIs("http")) {
  738. uri.scheme = "https";
  739. if (isValid(uri))
  740. valid = true;
  741. else
  742. // setting the scheme back to http
  743. uri.scheme = "http";
  744. }
  745. if (!valid)
  746. valid = isValid(uri);
  747. if (valid) {
  748. this.loadCaptcha();
  749. }
  750. }
  751. else if (uri) {
  752. valid = true;
  753. Weave.Service.serverURL = uri.spec;
  754. }
  755. if (valid)
  756. element.value = Weave.Service.serverURL;
  757. else
  758. Weave.Svc.Prefs.reset("serverURL");
  759. return valid;
  760. },
  761. _handleChoice: function() {
  762. let desc = document.getElementById("mergeChoiceRadio").selectedIndex;
  763. document.getElementById("chosenActionDeck").selectedIndex = desc;
  764. switch (desc) {
  765. case 1:
  766. if (this._case1Setup)
  767. break;
  768. let places_db = PlacesUtils.history
  769. .QueryInterface(Ci.nsPIPlacesDatabase)
  770. .DBConnection;
  771. if (Weave.Service.engineManager.get("history").enabled) {
  772. let daysOfHistory = 0;
  773. let stm = places_db.createStatement(
  774. "SELECT ROUND(( " +
  775. "strftime('%s','now','localtime','utc') - " +
  776. "( " +
  777. "SELECT visit_date FROM moz_historyvisits " +
  778. "ORDER BY visit_date ASC LIMIT 1 " +
  779. ")/1000000 " +
  780. ")/86400) AS daysOfHistory ");
  781. if (stm.step())
  782. daysOfHistory = stm.getInt32(0);
  783. // Support %S for historical reasons (see bug 600141)
  784. document.getElementById("historyCount").value =
  785. PluralForm.get(daysOfHistory,
  786. this._stringBundle.GetStringFromName("historyDaysCount.label"))
  787. .replace("%S", daysOfHistory)
  788. .replace("#1", daysOfHistory);
  789. } else {
  790. document.getElementById("historyCount").hidden = true;
  791. }
  792. if (Weave.Service.engineManager.get("bookmarks").enabled) {
  793. let bookmarks = 0;
  794. let stm = places_db.createStatement(
  795. "SELECT count(*) AS bookmarks " +
  796. "FROM moz_bookmarks b " +
  797. "LEFT JOIN moz_bookmarks t ON " +
  798. "b.parent = t.id WHERE b.type = 1 AND t.parent <> :tag");
  799. stm.params.tag = PlacesUtils.tagsFolderId;
  800. if (stm.executeStep())
  801. bookmarks = stm.row.bookmarks;
  802. // Support %S for historical reasons (see bug 600141)
  803. document.getElementById("bookmarkCount").value =
  804. PluralForm.get(bookmarks,
  805. this._stringBundle.GetStringFromName("bookmarksCount.label"))
  806. .replace("%S", bookmarks)
  807. .replace("#1", bookmarks);
  808. } else {
  809. document.getElementById("bookmarkCount").hidden = true;
  810. }
  811. if (Weave.Service.engineManager.get("passwords").enabled) {
  812. let logins = Services.logins.getAllLogins({});
  813. // Support %S for historical reasons (see bug 600141)
  814. document.getElementById("passwordCount").value =
  815. PluralForm.get(logins.length,
  816. this._stringBundle.GetStringFromName("passwordsCount.label"))
  817. .replace("%S", logins.length)
  818. .replace("#1", logins.length);
  819. } else {
  820. document.getElementById("passwordCount").hidden = true;
  821. }
  822. if (!Weave.Service.engineManager.get("prefs").enabled) {
  823. document.getElementById("prefsWipe").hidden = true;
  824. }
  825. let addonsEngine = Weave.Service.engineManager.get("addons");
  826. if (addonsEngine.enabled) {
  827. let ids = addonsEngine._store.getAllIDs();
  828. let blessedcount = 0;
  829. for each (let i in ids) {
  830. if (i) {
  831. blessedcount++;
  832. }
  833. }
  834. // bug 600141 does not apply, as this does not have to support existing strings
  835. document.getElementById("addonCount").value =
  836. PluralForm.get(blessedcount,
  837. this._stringBundle.GetStringFromName("addonsCount.label"))
  838. .replace("#1", blessedcount);
  839. } else {
  840. document.getElementById("addonCount").hidden = true;
  841. }
  842. this._case1Setup = true;
  843. break;
  844. case 2:
  845. if (this._case2Setup)
  846. break;
  847. let count = 0;
  848. function appendNode(label) {
  849. let box = document.getElementById("clientList");
  850. let node = document.createElement("label");
  851. node.setAttribute("value", label);
  852. node.setAttribute("class", "data indent");
  853. box.appendChild(node);
  854. }
  855. for each (let name in Weave.Service.clientsEngine.stats.names) {
  856. // Don't list the current client
  857. if (name == Weave.Service.clientsEngine.localName)
  858. continue;
  859. // Only show the first several client names
  860. if (++count <= 5)
  861. appendNode(name);
  862. }
  863. if (count > 5) {
  864. // Support %S for historical reasons (see bug 600141)
  865. let label =
  866. PluralForm.get(count - 5,
  867. this._stringBundle.GetStringFromName("additionalClientCount.label"))
  868. .replace("%S", count - 5)
  869. .replace("#1", count - 5);
  870. appendNode(label);
  871. }
  872. this._case2Setup = true;
  873. break;
  874. }
  875. return true;
  876. },
  877. // sets class and string on a feedback element
  878. // if no property string is passed in, we clear label/style
  879. _setFeedback: function(element, success, string) {
  880. element.hidden = success || !string;
  881. let classname = success ? "success" : "error";
  882. let image = element.getElementsByAttribute("class", "statusIcon")[0];
  883. image.setAttribute("status", classname);
  884. let label = element.getElementsByAttribute("class", "status")[0];
  885. label.value = string;
  886. },
  887. // shim
  888. _setFeedbackMessage: function(element, success, string) {
  889. let str = "";
  890. if (string) {
  891. try {
  892. str = this._stringBundle.GetStringFromName(string);
  893. } catch(e) {}
  894. if (!str)
  895. str = Weave.Utils.getErrorString(string);
  896. }
  897. this._setFeedback(element, success, str);
  898. },
  899. loadCaptcha: function() {
  900. let captchaURI = Weave.Service.miscAPI + "captcha_html";
  901. // First check for NoScript and whitelist the right sites.
  902. this._handleNoScript(true);
  903. if (this.captchaBrowser.currentURI.spec != captchaURI) {
  904. this.captchaBrowser.loadURI(captchaURI);
  905. }
  906. },
  907. onStateChange: function(webProgress, request, stateFlags, status) {
  908. // We're only looking for the end of the frame load
  909. if ((stateFlags & Ci.nsIWebProgressListener.STATE_STOP) == 0)
  910. return;
  911. if ((stateFlags & Ci.nsIWebProgressListener.STATE_IS_NETWORK) == 0)
  912. return;
  913. if ((stateFlags & Ci.nsIWebProgressListener.STATE_IS_WINDOW) == 0)
  914. return;
  915. // If we didn't find a captcha, assume it's not needed and don't show it.
  916. let responseStatus = request.QueryInterface(Ci.nsIHttpChannel).responseStatus;
  917. setVisibility(this.captchaBrowser, responseStatus != 404);
  918. //XXX TODO we should really log any responseStatus other than 200
  919. },
  920. onProgressChange: function() {},
  921. onStatusChange: function() {},
  922. onSecurityChange: function() {},
  923. onLocationChange: function() {}
  924. };
  925. // Define lazy getters for various XUL elements.
  926. //
  927. // onWizardAdvance() and onPageShow() are run before init(), so we'll even
  928. // define things that will almost certainly be used (like 'wizard') as a lazy
  929. // getter here.
  930. ["wizard",
  931. "pin1",
  932. "pin2",
  933. "pin3",
  934. "pairDeviceErrorRow",
  935. "pairDeviceThrobber"].forEach(function(id) {
  936. XPCOMUtils.defineLazyGetter(gSyncSetup, id, function() {
  937. return document.getElementById(id);
  938. });
  939. });
  940. XPCOMUtils.defineLazyGetter(gSyncSetup, "nextFocusEl", function() {
  941. return {pin1: this.pin2,
  942. pin2: this.pin3,
  943. pin3: this.wizard.getButton("next")};
  944. });
  945. XPCOMUtils.defineLazyGetter(gSyncSetup, "_stringBundle", function() {
  946. return Services.strings.createBundle("chrome://browser/locale/syncSetup.properties");
  947. });