File: nsHightail.js

package info (click to toggle)
thunderbird 1%3A52.9.1-1~deb9u1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 1,709,148 kB
  • sloc: cpp: 5,081,792; ansic: 2,051,951; python: 458,733; java: 241,615; xml: 193,600; asm: 178,649; sh: 81,881; makefile: 24,702; perl: 16,874; objc: 4,389; yacc: 1,816; ada: 1,697; lex: 1,257; pascal: 1,251; cs: 879; exp: 499; php: 436; lisp: 258; awk: 152; sed: 51; ruby: 47; csh: 27
file content (1219 lines) | stat: -rw-r--r-- 43,242 bytes parent folder | download | duplicates (3)
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
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

/* This file implements the nsIMsgCloudFileProvider interface.
 *
 * This component handles the Hightail implementation of the
 * nsIMsgCloudFileProvider interface.
 */

var {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;

Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource:///modules/gloda/log4moz.js");
Cu.import("resource:///modules/cloudFileAccounts.js");

var gServerUrl = "https://dpi.yousendit.com"; // Production url
// test url var gServerUrl = "https://test2-api.yousendit.com";

var kApiKey = "7spvjdt7m4kycr7jyhywrdn2";
var kAuthPath = "/dpi/v1/auth";
var kUserInfoPath = "/dpi/v2/user";
var kFolderPath = "/dpi/v1/folder/";
var kFolderFilePath = "/dpi/v1/folder/file/";
var kFolderInitUploadPath = kFolderPath + "file/initUpload";
var kFolderCommitUploadPath = kFolderPath + "file/commitUpload";
var kUrlTail = "s=4001583&cid=pm-4001583";

function nsHightail() {
  this.log = Log4Moz.getConfiguredLogger("Hightail");
}

nsHightail.prototype = {
  /* nsISupports */
  QueryInterface: XPCOMUtils.generateQI([Ci.nsIMsgCloudFileProvider]),

  classID: Components.ID("{dd2bce44-ca71-42ce-b806-6fa4e073919c}"),

  get type() { return "YouSendIt"; }, // Saved in prefs, cannot change!
  get displayName() { return "Hightail"; },
  get serviceURL() { return "https://www.hightail.com"; },
  get iconClass() { return "chrome://messenger/skin/icons/hightail.png"; },
  get accountKey() { return this._accountKey; },
  get lastError() { return this._lastErrorText; },
  get settingsURL() { return "chrome://messenger/content/cloudfile/Hightail/settings.xhtml"; },
  get managementURL() { return "chrome://messenger/content/cloudfile/Hightail/management.xhtml"; },

  _accountKey: false,
  _prefBranch: null,
  _userName: "",
  _password: "",
  _loggedIn: false,
  _userInfo: null,
  _file : null,
  _folderId: "",
  _requestDate: null,
  _successCallback: null,
  _request: null,
  _maxFileSize : -1,
  _fileSpaceUsed : -1,
  _availableStorage : -1,
  _totalStorage : -1,
  _lastErrorStatus : 0,
  _lastErrorText : "",
  _uploadingFile : null,
  _uploader : null,
  _urlsForFiles : {},
  _uploadInfo : {},
  _uploads: [],

  /**
   * Used by our testing framework to override the URLs that this component
   * communicates to.
   */
  overrideUrls: function(aNumUrls, aUrls) {
    gServerUrl = aUrls[0];
  },

  /**
   * Initializes an instance of this nsIMsgCloudFileProvider for an account
   * with key aAccountKey.
   *
   * @param aAccountKey the account key to initialize this
   *                    nsIMsgCloudFileProvider with.
   */
  init: function(aAccountKey) {
    this._accountKey = aAccountKey;
    this._prefBranch = Services.prefs.getBranch("mail.cloud_files.accounts." +
                                                aAccountKey + ".");
    this._userName = this._prefBranch.getCharPref("username");
    this._loggedIn = this._cachedAuthToken != "";
  },

  /**
   * Private function for retrieving or creating folder
   * on Hightail website for uploading file.
   *
   * @param aCallback called if folder is ready.
   */
  _initFolder: function(aCallback) {
    this.log.info('_initFolder');

    let saveFolderId = function(aFolderId) {
      this.log.info('saveFolderId');
      this._folderId = aFolderId;
      if (aCallback)
        aCallback();
    }.bind(this);

    let createThunderbirdFolder = function(aParentFolderId) {
      this._createFolder("Mozilla Thunderbird", aParentFolderId, saveFolderId);
    }.bind(this);

    let createAppsFolder = function(aParentFolderId) {
      this._createFolder("Apps", aParentFolderId, createThunderbirdFolder);
    }.bind(this);

    let findThunderbirdFolder = function(aParentFolderId) {
      this._findFolder("Mozilla Thunderbird", aParentFolderId,
                       createThunderbirdFolder, saveFolderId);
    }.bind(this);

    let findAppsFolder = function() {
      this._findFolder("Apps", 0, createAppsFolder, findThunderbirdFolder);
    }.bind(this);

    if (this._folderId == "")
      findAppsFolder();
    else
      this._checkFolderExist(this._folderId, aCallback, findAppsFolder);
  },

  /**
   * Private callback function passed to, and called from
   * nsHightailFileUploader.
   *
   * @param aRequestObserver a request observer for monitoring the start and
   *                         stop states of a request.
   * @param aStatus the status of the request.
   */
  _uploaderCallback: function(aRequestObserver, aStatus) {
    aRequestObserver.onStopRequest(null, null, aStatus);

    this._uploadingFile = null;
    this._uploads.shift();
    if (this._uploads.length > 0) {
      let nextUpload = this._uploads[0];
      this.log.info("chaining upload, file = " + nextUpload.file.leafName);
      this._uploadingFile = nextUpload.file;
      this._uploader = nextUpload;
      try {
        this.uploadFile(nextUpload.file, nextUpload.requestObserver);
      }
      catch (ex) {
        // I'd like to pass ex.result, but that doesn't seem to be defined.
        nextUpload.callback(nextUpload.requestObserver, Cr.NS_ERROR_FAILURE);
      }
    }
    else
      this._uploader = null;
  },

  /**
   * Attempt to upload a file to Hightail's servers.
   *
   * @param aFile an nsILocalFile for uploading.
   * @param aCallback an nsIRequestObserver for monitoring the start and
   *                  stop states of the upload procedure.
   */
  uploadFile: function(aFile, aCallback) {
    if (Services.io.offline)
      throw Ci.nsIMsgCloudFileProvider.offlineErr;

    this.log.info("Preparing to upload a file");

    // if we're uploading a file, queue this request.
    if (this._uploadingFile && this._uploadingFile != aFile) {
      this.log.info("Adding file to queue");
      let uploader = new nsHightailFileUploader(this, aFile,
                                                 this._uploaderCallback
                                                     .bind(this),
                                                 aCallback);
      this._uploads.push(uploader);
      return;
    }

    this._uploadingFile = aFile;

    let finish = function() {
      this._finishUpload(aFile, aCallback);
    }.bind(this);

    let onGetUserInfoSuccess = function() {
      this._initFolder(finish);
    }.bind(this);

    let onAuthFailure = function() {
      aCallback.onStopRequest(null, null,
                              Ci.nsIMsgCloudFileProvider.authErr);
    }.bind(this);

    this.log.info("Checking to see if we're logged in");

    if (!this._loggedIn) {
      let onLoginSuccess = function() {
        this._getUserInfo(onGetUserInfoSuccess, onAuthFailure);
      }.bind(this);

      return this.logon(onLoginSuccess, onAuthFailure, true);
    }

    if (!this._userInfo)
      return this._getUserInfo(onGetUserInfoSuccess, onAuthFailure);

    onGetUserInfoSuccess();
  },

  /**
   * A private function called when we're almost ready to kick off the upload
   * for a file. First, ensures that the file size is not too large, and that
   * we won't exceed our storage quota, and then kicks off the upload.
   *
   * @param aFile the nsILocalFile to upload
   * @param aCallback the nsIRequestObserver for monitoring the start and stop
   *                  states of the upload procedure.
   */
  _finishUpload: function(aFile, aCallback) {
    if (aFile.fileSize > 2147483648)
      return this._fileExceedsLimit(aCallback, '2GB', 0);
    if (aFile.fileSize > this._maxFileSize)
      return this._fileExceedsLimit(aCallback, 'Limit', 0);
    if (aFile.fileSize > this._availableStorage)
      return this._fileExceedsLimit(aCallback, 'Quota',
                                    aFile.fileSize + this._fileSpaceUsed);

    delete this._userInfo; // force us to update userInfo on every upload.

    if (!this._uploader) {
      this._uploader = new nsHightailFileUploader(this, aFile,
                                                   this._uploaderCallback
                                                       .bind(this),
                                                   aCallback);
      this._uploads.unshift(this._uploader);
    }

    this._uploadingFile = aFile;
    this._uploader.startUpload();
  },

  /**
   * A private function called when upload exceeds file limit.
   *
   * @param aCallback the nsIRequestObserver for monitoring the start and stop
   *                  states of the upload procedure.
   */
  _fileExceedsLimit: function(aCallback, aType, aStorageSize) {
    let cancel = Ci.nsIMsgCloudFileProvider.uploadCanceled;

    let args = {storage: aStorageSize};
    args.wrappedJSObject = args;
    Services.ww.openWindow(null,
                           "chrome://messenger/content/cloudfile/Hightail/"
                           + "fileExceeds" + aType + ".xul",
                           "Hightail", "chrome,centerscreen,dialog,modal,resizable=yes",
                           args).focus();

    return aCallback.onStopRequest(null, null, cancel);
  },

  /**
   * Cancels an in-progress file upload.
   *
   * @param aFile the nsILocalFile being uploaded.
   */
  cancelFileUpload: function(aFile) {
    this.log.info("in cancel upload");
    if (this._uploadingFile != null && this._uploader != null &&
        this._uploadingFile.equals(aFile)) {
      this._uploader.cancel();
    }
    else {
      for (let i = 0; i < this._uploads.length; i++)
        if (this._uploads[i].file.equals(aFile)) {
          this._uploads[i].requestObserver.onStopRequest(
            null, null, Ci.nsIMsgCloudFileProvider.uploadCanceled);
          this._uploads.splice(i, 1);
          return;
        }
    }
  },

  /**
   * A private function for dealing with stale tokens.  Attempts to refresh
   * the token without prompting for the password.
   *
   * @param aSuccessCallback called if token refresh is successful.
   * @param aFailureCallback called if token refresh fails.
   */
  _handleStaleToken: function(aSuccessCallback, aFailureCallback) {
    this.log.info("Handling a stale token.");
    this._loggedIn = false;
    this._cachedAuthToken = "";
    if (this.getPassword(this._userName, true) != "") {
      this.log.info("Attempting to reauth with saved password");
      // We had a stored password - let's try logging in with that now.
      this.logon(aSuccessCallback, aFailureCallback,
                 false);
    } else {
      this.log.info("No saved password stored, so we can't refresh the token silently.");
      aFailureCallback();
    }
  },

  /**
   * A private function for retrieving profile information about a user.
   *
   * @param successCallback a callback fired if retrieving profile information
   *                        is successful.
   * @param failureCallback a callback fired if retrieving profile information
   *                        fails.
   */
  _getUserInfo: function(successCallback, failureCallback) {
    this.log.info("getting user info");
    let args = "?email=" + this._userName + "&";

    let req = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"]
                .createInstance(Ci.nsIXMLHttpRequest);
    req.open("GET", gServerUrl + kUserInfoPath + args + kUrlTail, true);

    req.onload = function() {
      if (req.status >= 200 && req.status < 400) {
        this.log.info("request status = " + req.status +
                      " response = " + req.responseText);
        let docResponse = JSON.parse(req.responseText);
        this.log.info("user info response parsed = " + docResponse);
        if (docResponse.errorStatus)
          this.log.info("error status = " + docResponse.errorStatus.code);

        if (docResponse.errorStatus && docResponse.errorStatus.code > 200) {
          if (docResponse.errorStatus.code >= 400) {
            // Our token has gone stale
            this.log.info("Our token has gone stale - requesting a new one.");

            let retryGetUserInfo = function() {
              this._getUserInfo(successCallback, failureCallback);
            }.bind(this);

            this._handleStaleToken(retryGetUserInfo, failureCallback);
            return;
          }

          failureCallback();
          return;
        }
        this._userInfo = docResponse;
        let account = docResponse.account;
        let storage = docResponse.storage;
        if (storage) {
          this._fileSpaceUsed = parseInt(storage.currentUsage);
          this._availableStorage = parseInt(storage.storageQuota) - this._fileSpaceUsed;
        }
        else
          this._availableStorage = parseInt(account.availableStorage);

        this._maxFileSize = docResponse.type == "BAS" ? 52428800 : (parseInt(account.maxFileSize));
        this.log.info("available storage = " + this._availableStorage + " max file size = " + this._maxFileSize);

        successCallback();
      }
      else
        failureCallback();
    }.bind(this);

    req.onerror = function() {
      this.log.info("getUserInfo failed - status = " + req.status);
      failureCallback();
    }.bind(this);
    // Add a space at the end because http logging looks for two
    // spaces in the X-Auth-Token header to avoid putting passwords
    // in the log, and crashes if there aren't two spaces.
    req.setRequestHeader("X-Auth-Token", this._cachedAuthToken + " ");
    req.setRequestHeader("X-Api-Key", kApiKey);
    req.setRequestHeader("Accept", "application/json");
    req.send();
  },

  /**
   * Returns the sharing URL for some uploaded file.
   *
   * @param aFile the nsILocalFile to get the URL for.
   */
  urlForFile: function(aFile) {
    return this._urlsForFiles[aFile.path];
  },

  /**
   * Attempts to refresh cached profile information for the account associated
   * with this instance's account key.
   *
   * @param aWithUI a boolean for whether or not we should prompt the user for
   *                a password if we don't have a proper token.
   * @param aListener an nsIRequestObserver for monitoring the start and stop
   *                  states of fetching profile information.
   */
  refreshUserInfo: function(aWithUI, aListener) {
    if (Services.io.offline)
      throw Ci.nsIMsgCloudFileProvider.offlineErr;

    aListener.onStartRequest(null, null);

    // Let's define some reusable callback functions...
    let onGetUserInfoSuccess = function() {
      aListener.onStopRequest(null, null, Cr.NS_OK);
    }

    let onAuthFailure = function() {
      aListener.onStopRequest(null, null,
                              Ci.nsIMsgCloudFileProvider.authErr);
    }

    // If we're not logged in, attempt to login, and then attempt to
    // get user info if logging in is successful.
    this.log.info("Checking to see if we're logged in");
    if (!this._loggedIn) {
      let onLoginSuccess = function() {
        this._getUserInfo(onGetUserInfoSuccess, onAuthFailure);
      }.bind(this);

      return this.logon(onLoginSuccess, onAuthFailure, aWithUI);
    }

    // If we're logged in, attempt to get user info.
    if (!this._userInfo)
      return this._getUserInfo(onGetUserInfoSuccess, onAuthFailure);

  },

  /**
   * Creates an account for a user.  Note that, currently, this function is
   * not being used by the UI.
   */
  createNewAccount: function(aEmailAddress, aPassword,aFirstName, aLastName,
                             aRequestObserver) {
    if (Services.io.offline)
      throw Ci.nsIMsgCloudFileProvider.offlineErr;

    let args = "?email=" + aEmailAddress + "&password=" + aPassword + "&firstname="
               + aFirstName + "&lastname=" + aLastName + "&";

    let req = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"]
                .createInstance(Ci.nsIXMLHttpRequest);

    req.open("POST", gServerUrl + kUserInfoPath + args + kUrlTail, true);

    req.onload = function() {
      if (req.status >= 200 &&
          req.status < 400) {
        this.log.info("request status = " + req + " response = " +
                      req.responseText);
        aRequestObserver.onStopRequest(null, null, Cr.NS_OK);
      }
      else {
        let docResponse = JSON.parse(req.responseText);
        this._lastErrorText = docResponse.errorStatus.message;
        this._lastErrorStatus = docResponse.errorStatus.code;
        aRequestObserver.onStopRequest(null, null, Cr.NS_ERROR_FAILURE);
      }
    }.bind(this);

    req.onerror = function() {
      this.log.info("getUserInfo failed - status = " + req.status);
      aRequestObserver.onStopRequest(null, null, Cr.NS_ERROR_FAILURE);
    }.bind(this);
    // Add a space at the end because http logging looks for two
    // spaces in the X-Auth-Token header to avoid putting passwords
    // in the log, and crashes if there aren't two spaces.
    req.setRequestHeader("X-Auth-Token", this._cachedAuthToken + " ");
    req.setRequestHeader("X-Api-Key", kApiKey);
    req.setRequestHeader("Accept", "application/json");
    req.send();
  },

  /**
   * Attempt to find folder by name on Hightail website.
   *
   * @param aFolderName name of folder
   * @param aParentFolderId id of folder where we are looking
   * @param aNotFoundCallback called if folder is not found
   * @param aFoundCallback called if folder is found
   */
  _findFolder: function(aFolderName, aParentFolderId, aNotFoundCallback,
                        aFoundCallback) {

    this.log.info("Find folder: " + aFolderName);

    let checkChildFolders = function(folders) {
      this.log.info("Looking for a child folder");
      let folderId = 0;
      let folder = folders.folder;
      for (let i in folder) {
        if (folder[i].name == aFolderName) {
          folderId = folder[i].id;
          break;
        }
      }

      if (!folderId && aNotFoundCallback)
        aNotFoundCallback(aParentFolderId);

      if (folderId && aFoundCallback)
        aFoundCallback(folderId);
    }.bind(this);

    this._checkFolderExist(aParentFolderId, checkChildFolders);
  },

  /**
   * Attempt to find folder by id on Hightail website.
   *
   * @param aFolderId id of folder
   * @param aNotFoundCallback called if folder is not found
   * @param aFoundCallback called if folder is found
   */
  _checkFolderExist: function(aFolderId, aFoundCallback, aNotFoundCallback) {
    this.log.info('checkFolderExist');
    if (Services.io.offline)
      throw Ci.nsIMsgCloudFileProvider.offlineErr;

    let args = "?includeFiles=false&includeFolders=true&";

    let req = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"]
                .createInstance(Ci.nsIXMLHttpRequest);

    req.open("GET",
             gServerUrl + kFolderPath + aFolderId + args + kUrlTail,
             true);

    req.onload = function() {
      let docResponse = JSON.parse(req.responseText);
      if (req.status >= 200 && req.status < 400) {
        this.log.info("request status = " + req + " response = " +
                      req.responseText);

        if (aFoundCallback && docResponse.folders)
          aFoundCallback(docResponse.folders);
      }
      else {
        this._lastErrorText = docResponse.errorStatus.message;
        this._lastErrorStatus = docResponse.errorStatus.code;
        if (this._lastErrorStatus == 400 && this._lastErrorText == "Not Found" && aNotFoundCallback)
          aNotFoundCallback();
      }
    }.bind(this);

    req.onerror = function() {
      this.log.info("_checkFolderExist failed - status = " + req.status);
    }.bind(this);
    // Add a space at the end because http logging looks for two
    // spaces in the X-Auth-Token header to avoid putting passwords
    // in the log, and crashes if there aren't two spaces.
    req.setRequestHeader("X-Auth-Token", this._cachedAuthToken + " ");
    req.setRequestHeader("X-Api-Key", kApiKey);
    req.setRequestHeader("Accept", "application/json");
    req.send();
  },

  /**
   * Private function for creating folder on Hightail website.
   *
   * @param aName name of folder
   * @param aParent id of parent folder
   * @param aSuccessCallback called when folder is created
   */
  _createFolder: function(aName, aParent, aSuccessCallback) {
    this.log.info("Create folder: " + aName);
    if (Services.io.offline)
      throw Ci.nsIMsgCloudFileProvider.offlineErr;

    let args = "?name=" + aName + "&parentId=" + aParent + "&";

    let req = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"]
                .createInstance(Ci.nsIXMLHttpRequest);

    req.open("POST", gServerUrl + kFolderPath.replace(/\/$/, '') + args + kUrlTail, true);

    req.onload = function() {
      let docResponse = JSON.parse(req.responseText);
      if (req.status >= 200 && req.status < 400) {
        this.log.info("request status = " + req + " response = " +
                      req.responseText);

        if (aSuccessCallback)
          aSuccessCallback(docResponse.id)
      }
      else {
        this._lastErrorText = docResponse.errorStatus.message;
        this._lastErrorStatus = docResponse.errorStatus.code;
      }
    }.bind(this);

    req.onerror = function() {
      this.log.info("createFolder failed - status = " + req.status);
    }.bind(this);
    // Add a space at the end because http logging looks for two
    // spaces in the X-Auth-Token header to avoid putting passwords
    // in the log, and crashes if there aren't two spaces.
    req.setRequestHeader("X-Auth-Token", this._cachedAuthToken + " ");
    req.setRequestHeader("X-Api-Key", kApiKey);
    req.setRequestHeader("Accept", "application/json");
    req.send();
  },

  /**
   * If a the user associated with this account key already has an account,
   * allows them to log in.
   *
   * @param aRequestObserver an nsIRequestObserver for monitoring the start and
   *                         stop states of the login procedure.
   */
  createExistingAccount: function(aRequestObserver) {
     // XXX: replace this with a better function
    let successCb = function(aResponseText, aRequest) {
      aRequestObserver.onStopRequest(null, this, Cr.NS_OK);
    }.bind(this);

    let failureCb = function(aResponseText, aRequest) {
      aRequestObserver.onStopRequest(null, this,
                                     Ci.nsIMsgCloudFileProvider.authErr);
    }.bind(this);

    this.logon(successCb, failureCb, true);
  },

  /**
   * Returns an appropriate provider-specific URL for dealing with a particular
   * error type.
   *
   * @param aError an error to get the URL for.
   */
  providerUrlForError: function(aError) {
    if (aError == Ci.nsIMsgCloudFileProvider.uploadExceedsFileLimit)
      return "http://www.hightail.com";
    return "";
  },

  /**
   * If the provider doesn't have an API for creating an account, perhaps
   * there's a url we can load in a content tab that will allow the user
   * to create an account.
   */
  get createNewAccountUrl() { return ""; },

  /**
   * If we don't know the limit, this will return -1.
   */
  get fileUploadSizeLimit() { return this._maxFileSize; },

  get remainingFileSpace() { return this._availableStorage; },

  get fileSpaceUsed() { return this._fileSpaceUsed; },

  /**
   * Attempts to delete an uploaded file.
   *
   * @param aFile the nsILocalFile to delete.
   * @param aCallback an nsIRequestObserver for monitoring the start and stop
   *                  states of the delete procedure.
   */
  deleteFile: function(aFile, aCallback) {
    this.log.info("Deleting a file");

    if (Services.io.offline) {
      this.log.error("We're offline - we can't delete the file.");
      throw Ci.nsIMsgCloudFileProvider.offlineErr;
    }

    let uploadInfo = this._uploadInfo[aFile.path];
    if (!uploadInfo) {
      this.log.error("Could not find a record for the file to be deleted.");
      throw Cr.NS_ERROR_FAILURE;
    }

    let req = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"]
                .createInstance(Ci.nsIXMLHttpRequest);

    let args = kFolderFilePath + uploadInfo.fileId + "?";

    req.open("DELETE", gServerUrl + args + kUrlTail, true);
    this.log.info("Sending request to: " + gServerUrl + args);

    req.onerror = function() {
      let response = JSON.parse(req.responseText);
      this._lastErrorStatus = response.errorStatus.status;
      this._lastErrorText = response.errorStatus.message;
      this.log.error("There was a problem deleting: " + this._lastErrorText);
      aCallback.onStopRequest(null, null, Cr.NS_ERROR_FAILURE);
    }.bind(this);

    req.onload = function() {
      // Response is the URL.
      let response = req.responseText;
      this.log.info("delete response = " + response);
      let deleteInfo = JSON.parse(response);

      if (deleteInfo.errorStatus) {
        // Argh - for some reason, on deletion, the error code for a stale
        // token is 401 instead of 500.
        if (deleteInfo.errorStatus.code == 401) {
          this.log.warn("Token has gone stale! Will attempt to reauth.");
          // Our token has gone stale
          let onTokenRefresh = function() {
            this.deleteFile(aFile, aCallback);
          }.bind(this);

          let onTokenRefreshFailure = function() {
            aCallback.onStopRequest(null, null,
                                    Ci.nsIMsgCloudFileProvider.authErr);
          }
          this._handleStaleToken(onTokenRefresh, onTokenRefreshFailure);
          return;
        }

        this.log.error("Server has returned a failure on our delete request.");
        this.log.error("Error code: " + deleteInfo.errorStatus.code);
        this.log.error("Error message: " + deleteInfo.errorStatus.message);
        //aCallback.onStopRequest(null, null,
        //                        Ci.nsIMsgCloudFileProvider.uploadErr);
        return;
      }

      this.log.info("Delete was successful!");
      // Success!
      aCallback.onStopRequest(null, null, Cr.NS_OK);
    }.bind(this);

    req.setRequestHeader("X-Auth-Token", this._cachedAuthToken + " ");
    req.setRequestHeader("X-Api-Key", kApiKey);
    req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    req.setRequestHeader("Accept", "application/json");
    req.send();
  },

  /**
   * Returns the saved password for this account if one exists, or prompts
   * the user for a password. Returns the empty string on failure.
   *
   * @param aUsername the username associated with the account / password.
   * @param aNoPrompt a boolean for whether or not we should suppress
   *                  the password prompt if no password exists.  If so,
   *                  returns the empty string if no password exists.
   */
  getPassword: function(aUsername, aNoPrompt) {
    this.log.info("Getting password for user: " + aUsername);

    if (aNoPrompt)
      this.log.info("Suppressing password prompt");

    let passwordURI = gServerUrl;
    let logins = Services.logins.findLogins({}, passwordURI, null, passwordURI);
    for (let loginInfo of logins) {
      if (loginInfo.username == aUsername)
        return loginInfo.password;
    }
    if (aNoPrompt)
      return "";

    // OK, let's prompt for it.
    let win = Services.wm.getMostRecentWindow(null);

    let authPrompter = Services.ww.getNewAuthPrompter(win);
    let password = { value: "" };
    // Use the service name in the prompt text
    let serverUrl = gServerUrl;
    let userPos = gServerUrl.indexOf("//") + 2;
    let userNamePart = encodeURIComponent(this._userName) + '@';
    serverUrl = gServerUrl.substr(0, userPos) + userNamePart + gServerUrl.substr(userPos);
    let messengerBundle = Services.strings.createBundle(
      "chrome://messenger/locale/messenger.properties");
    let promptString = messengerBundle.formatStringFromName("passwordPrompt",
                                                            [this._userName,
                                                             this.displayName],
                                                            2);

    if (authPrompter.promptPassword(this.displayName, promptString, serverUrl,
                                    authPrompter.SAVE_PASSWORD_PERMANENTLY,
                                    password))
      return password.value;

    return "";
  },

  /**
   * Clears any saved Hightail passwords for this instance's account.
   */
  clearPassword: function() {
    let logins = Services.logins.findLogins({}, gServerUrl, null, gServerUrl);
    for (let loginInfo of logins)
      if (loginInfo.username == this._userName)
        Services.logins.removeLogin(loginInfo);
  },

  /**
   * Attempt to log on and get the auth token for this Hightail account.
   *
   * @param successCallback the callback to be fired if logging on is successful
   * @param failureCallback the callback to be fired if loggong on fails
   * @aparam aWithUI a boolean for whether or not we should prompt for a password
   *                 if no auth token is currently stored.
   */
  logon: function(successCallback, failureCallback, aWithUI) {
    this.log.info("Logging in, aWithUI = " + aWithUI);
    if (this._password == undefined || !this._password)
      this._password = this.getPassword(this._userName, !aWithUI);
    let args = "?email=" + this._userName + "&password=" + this._password + "&";
    this.log.info("Sending login information...");
    let req = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"]
                .createInstance(Ci.nsIXMLHttpRequest);
    let curDate = Date.now().toString();

    req.open("POST", gServerUrl + kAuthPath + args + kUrlTail, true);
    req.onerror = function() {
      this.log.info("logon failure");
      failureCallback();
    }.bind(this);

    req.onload = function() {
      if (req.status >= 200 && req.status < 400) {
        this.log.info("auth token response = " + req.responseText);
        let docResponse = JSON.parse(req.responseText);
        this.log.info("login response parsed = " + docResponse);
        this._cachedAuthToken = docResponse.authToken;
        this.log.info("authToken = " + this._cachedAuthToken);
        if (this._cachedAuthToken) {
          this._loggedIn = true;
          successCallback();
        }
        else {
          this.clearPassword();
          this._loggedIn = false;
          this._lastErrorText = docResponse.errorStatus.message;
          this._lastErrorStatus = docResponse.errorStatus.code;
          failureCallback();
        }
      }
      else {
        this.clearPassword();
        failureCallback();
      }
    }.bind(this);
    req.setRequestHeader("X-Api-Key", kApiKey);
    req.setRequestHeader("Date", curDate);
    req.setRequestHeader("Accept", "application/json");
    req.send();
    this.log.info("Login information sent!");
  },

  get _cachedAuthToken() {
    let authToken = cloudFileAccounts.getSecretValue(this.accountKey,
                                                     cloudFileAccounts.kTokenRealm);

    if (!authToken)
      return "";

    return authToken;
  },

  set _cachedAuthToken(aVal) {
    if (!aVal)
      aVal = "";

    cloudFileAccounts.setSecretValue(this.accountKey,
                                     cloudFileAccounts.kTokenRealm,
                                     aVal);
  },
};

function nsHightailFileUploader(aHightail, aFile, aCallback, aRequestObserver) {
  this.hightail = aHightail;
  this.log = this.hightail.log;
  this.log.info("new nsHightailFileUploader file = " + aFile.leafName);
  this.file = aFile;
  this.callback = aCallback;
  this.requestObserver = aRequestObserver;
}

nsHightailFileUploader.prototype = {
  hightail : null,
  file : null,
  callback : null,
  _request : null,

  /**
   * Kicks off the upload procedure for this uploader.
   */
  startUpload: function() {
    let curDate = Date.now().toString();

    this.requestObserver.onStartRequest(null, null);

    let onSuccess = function() {
      this._uploadFile();
    }.bind(this);

    let onFailure = function() {
      this.callback(this.requestObserver, Ci.nsIMsgCloudFileProvider.uploadErr);
    }.bind(this);

    return this._prepareToSend(onSuccess, onFailure);
  },

  /**
   * Communicates with Hightail to get the URL that we will send the upload
   * request to.
   *
   * @param successCallback the callback fired if getting the URL is successful
   * @param failureCallback the callback fired if getting the URL fails
   */
  _prepareToSend: function(successCallback, failureCallback) {
    let req = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"]
                .createInstance(Ci.nsIXMLHttpRequest);

    req.open("POST", gServerUrl + kFolderInitUploadPath + "?" + kUrlTail, true);

    req.onerror = failureCallback;

    req.onload = function() {
      let response = req.responseText;
      if (req.status >= 200 && req.status < 400) {
        this._urlInfo = JSON.parse(response);
        this.hightail._uploadInfo[this.file.path] = this._urlInfo;
        this.log.info("in prepare to send response = " + response);
        this.log.info("file id = " + this._urlInfo.fileId);
        this.log.info("upload url = " + this._urlInfo.uploadUrl[0]);
        successCallback();
      }
      else {
        this.log.error("Preparing to send failed!");
        this.log.error("Response was: " + response);
        this.hightail._lastErrorText = req.responseText;
        this.hightail._lastErrorStatus = req.status;
        failureCallback();
      }
    }.bind(this);

    // Add a space at the end because http logging looks for two
    // spaces in the X-Auth-Token header to avoid putting passwords
    // in the log, and crashes if there aren't two spaces.
    req.setRequestHeader("X-Auth-Token", this.hightail._cachedAuthToken + " ");
    req.setRequestHeader("X-Api-Key", kApiKey);
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    req.send();
  },

  /**
   * Once we've got the URL to upload the file to, this function actually does
   * the upload of the file to Hightail.
   */
  _uploadFile: function() {
    let req = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"]
                .createInstance(Ci.nsIXMLHttpRequest);

    let curDate = Date.now().toString();
    this.log.info("upload url = " + this._urlInfo.uploadUrl[0]);
    this.request = req;
    req.open("POST", this._urlInfo.uploadUrl[0] + "?" + kUrlTail, true);
    req.onload = function() {
      this.cleanupTempFile();
      if (req.status >= 200 && req.status < 400) {
        try {
          this.log.info("upload response = " + req.responseText);
          this._commitSend();
        } catch (ex) {
          this.log.error(ex);
        }
      }
      else
        this.callback(this.requestObserver,
                      Ci.nsIMsgCloudFileProvider.uploadErr);
    }.bind(this);

    req.onerror = function () {
      this.cleanupTempFile();
      if (this.callback)
        this.callback(this.requestObserver,
                      Ci.nsIMsgCloudFileProvider.uploadErr);
    }.bind(this);

    req.setRequestHeader("Date", curDate);
    let boundary = "------" + curDate;
    let contentType = "multipart/form-data; boundary="+ boundary;
    req.setRequestHeader("Content-Type", contentType);

    let fileContents = "--" + boundary +
      "\r\nContent-Disposition: form-data; name=\"bid\"\r\n\r\n" +
       this._urlInfo.fileId;

    let fileName = /^[\040-\176]+$/.test(this.file.leafName)
        ? this.file.leafName
        : encodeURIComponent(this.file.leafName);

    fileContents += "\r\n--" + boundary +
      "\r\nContent-Disposition: form-data; name=\"fname\"; filename=\"" +
      fileName + "\"\r\nContent-Type: application/octet-stream" +
      "\r\n\r\n";

    // Since js doesn't like binary data in strings, we're going to create
    // a temp file consisting of the message preamble, the file contents, and
    // the post script, and pass a stream based on that file to
    // nsIXMLHttpRequest.send().

    try {
      this._tempFile = this.getTempFile(this.file.leafName);
      let ostream = Cc["@mozilla.org/network/file-output-stream;1"]
                     .createInstance(Ci.nsIFileOutputStream);
      ostream.init(this._tempFile, -1, -1, 0);
      ostream.write(fileContents, fileContents.length);

      this._fstream = Cc["@mozilla.org/network/file-input-stream;1"]
                       .createInstance(Ci.nsIFileInputStream);
      let sstream = Cc["@mozilla.org/scriptableinputstream;1"]
                       .createInstance(Ci.nsIScriptableInputStream);
      this._fstream.init(this.file, -1, 0, 0);
      sstream.init(this._fstream);

      // This blocks the UI which is less than ideal. But it's a local
      // file operations so probably not the end of the world.
      while (sstream.available() > 0) {
        let bytes = sstream.readBytes(sstream.available());
        ostream.write(bytes, bytes.length);
      }

      fileContents = "\r\n--" + boundary + "--\r\n";
      ostream.write(fileContents, fileContents.length);

      ostream.close();
      this._fstream.close();
      sstream.close();

      // defeat fstat caching
      this._tempFile = this._tempFile.clone();
      this._fstream.init(this._tempFile, -1, 0, 0);
      this._fstream.close();
      // I don't trust re-using the old fstream.
      this._fstream = Cc["@mozilla.org/network/file-input-stream;1"]
                     .createInstance(Ci.nsIFileInputStream);
      this._fstream.init(this._tempFile, -1, 0, 0);
      this._bufStream = Cc["@mozilla.org/network/buffered-input-stream;1"]
                        .createInstance(Ci.nsIBufferedInputStream);
      this._bufStream.init(this._fstream, 4096);
      // nsIXMLHttpRequest's nsIVariant handling requires that we QI
      // to nsIInputStream.
      req.send(this._bufStream.QueryInterface(Ci.nsIInputStream));
    } catch (ex) {
      this.cleanupTempFile();
      this.log.error(ex);
      throw ex;
    }
  },

  /**
   * Cancels the upload request for the file associated with this Uploader.
   */
  cancel: function() {
    this.log.info("in uploader cancel");
    this.callback(this.requestObserver, Ci.nsIMsgCloudFileProvider.uploadCanceled);
    delete this.callback;
    if (this.request) {
      this.log.info("cancelling upload request");
      let req = this.request;
      if (req.channel) {
        this.log.info("cancelling upload channel");
        req.channel.cancel(Cr.NS_BINDING_ABORTED);
      }
      this.request = null;
    }
  },
  /**
   * Once the file is uploaded, if we want to get a sharing URL back, we have
   * to send a "commit" request - which this function does.
   */
  _commitSend: function() {
    this.log.info("commit sending file " + this._urlInfo.fileId);
    let req = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"]
                .createInstance(Ci.nsIXMLHttpRequest);
    let args = "?name=" + this.file.leafName +
               "&fileId=" + this._urlInfo.fileId +
               "&parentId=" + this.hightail._folderId + "&";

    req.open("POST", gServerUrl + kFolderCommitUploadPath + args + kUrlTail, true);

    req.onerror = function() {
      this.log.info("error in commit send");
      this.callback(this.requestObserver,
                    Ci.nsIMsgCloudFileProvider.uploadErr);
    }.bind(this);

    req.onload = function() {
      // Response is the URL.
      let response = req.responseText;
      this.log.info("commit response = " + response);
      let uploadInfo = JSON.parse(response);

      let succeed = function() {
        this.callback(this.requestObserver, Cr.NS_OK);
      }.bind(this);

      let failed = function() {
        this.callback(this.requestObserver, this.file.leafName.length > 120
                      ? Ci.nsIMsgCloudFileProvider.uploadExceedsFileNameLimit
                      : Ci.nsIMsgCloudFileProvider.uploadErr);
      }.bind(this);

      if (uploadInfo.errorStatus) {
        this.hightail._lastErrorText = uploadInfo.errorStatus.message;
        this.hightail._lastErrorStatus = uploadInfo.errorStatus.code;
        failed();
      }
      else if (uploadInfo.clickableDownloadUrl) {
        // We need a kludge here because Hightail is returning URLs without the scheme...
        let url = this._ensureScheme(uploadInfo.clickableDownloadUrl);
        this.hightail._urlsForFiles[this.file.path] = url;
        succeed();
      }
      else
        this._findDownloadUrl(uploadInfo.id, succeed, failed);
    }.bind(this);

    req.setRequestHeader("X-Auth-Token", this.hightail._cachedAuthToken + " ");
    req.setRequestHeader("X-Api-Key", kApiKey);
    req.setRequestHeader("Accept", "application/json");
    req.send();
  },

  /**
   * If there's no scheme prefix for a URL, attaches an https:// prefix
   * and returns the new result.
   *
   * @param aURL to ensure a scheme with
   */
  _ensureScheme: function(aURL) {
    try {
      let scheme = Services.io.extractScheme(aURL);
      return aURL;
    } catch(e) {
      // If we got NS_ERROR_MALFORMED_URI back, there's no scheme here.
      if (e.result == Cr.NS_ERROR_MALFORMED_URI)
        return "https://" + aURL;
      // Otherwise, we hit something different, and should throw.
      throw e;
    }
  },

  /**
   * Attempt to find download url for file.
   *
   * @param aFileId id of file
   * @param aSuccessCallback called if url is found
   * @param aFailureCallback called if url is not found
   */
  _findDownloadUrl: function(aFileId, aSuccessCallback, aFailureCallback) {
    let req = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"]
                .createInstance(Ci.nsIXMLHttpRequest);

    req.open("GET", gServerUrl + kFolderFilePath + aFileId, true);

    req.onerror = function() {
      this.log.info("error in findDownloadUrl");
      aFailureCallback();
    }.bind(this);

    req.onload = function() {
      let response = req.responseText;
      this.log.info("findDownloadUrl response = " + response);
      let fileInfo = JSON.parse(response);

      if (fileInfo.errorStatus)
        aFailureCallback();
      else {
        // We need a kludge here because Hightail is returning URLs without the scheme...
        let url = this._ensureScheme(fileInfo.clickableDownloadUrl);
        this.hightail._urlsForFiles[this.file.path] = url;
        aSuccessCallback();
      }
    }.bind(this);

    req.setRequestHeader("X-Auth-Token", this.hightail._cachedAuthToken + " ");
    req.setRequestHeader("X-Api-Key", kApiKey);
    req.setRequestHeader("Accept", "application/json");
    req.send();
  },

  /**
   * Creates and returns a temporary file on the local file system.
   */
  getTempFile: function(leafName) {
    let tempfile = Services.dirsvc.get("TmpD", Ci.nsIFile);
    tempfile.append(leafName)
    tempfile.createUnique(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, parseInt("0666", 8));
    // do whatever you need to the created file
    return tempfile.clone()
  },

  /**
   * Cleans up any temporary files that this nsHightailFileUploader may have
   * created.
   */
  cleanupTempFile: function() {
    if (this._bufStream)
      this._bufStream.close();
    if (this._fstream)
      this._fstream.close();
    if (this._tempFile)
      this._tempFile.remove(false);
  },
};

var NSGetFactory = XPCOMUtils.generateNSGetFactory([nsHightail]);