aboutsummaryrefslogtreecommitdiffstats
path: root/importAddrBook.js
blob: 97f44669c1ad5e95d3dc25b9455c0bc904dadc6a (plain) (blame)
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
/*jshint forin:true, noarg:true, noempty:true, eqeqeq:true,
  bitwise:true, strict:true, undef:true, curly:true, browser:true,
  devel:true, indent:2, maxerr:50, moz:true, newcap:false, moz:true */

/* global mozContact: false,
   ContactTelField: false, parseLDIF: false */

(function () {
  "use strict";

  // Shim for the intersection of two Arrays.
  if (!Array.prototype.intersection) {
    Array.prototype.intersection = function (anotherArr) {
      return this.filter(function(n) {
        if (anotherArr.indexOf(n) === -1) { return false; }
        return true;
      });
    };
  }

  const phoneFields = [
      "mobile", "facsimiletelephonenumber", "homePhone", "telephoneNumber"
    ];

  const emailFields = [ "mail" ];

  /**
   * Not used presently and not debugged.
   */
  function whenContactAlreadyPresent(rec, cb_not_found, cb_found) {
    var rec_keys = Object.keys(rec);

    // Finding whether the contact has email or telephone
    var email_fields = rec_keys.intersection(emailFields);
    var phone_fields = rec_keys.intersection(phoneFields);
    var search_keys = [];

    if (email_fields.length > 0) {
      search_keys = email_fields;
    }
    else if (phone_fields.length > 0) {
      search_keys = phone_fields;
    }

    if (search_keys.length > 0) {
      var search_opts = {
        filterValue : rec(search_keys[0]),
        filterBy    : search_keys,
        filterOp    : "contains",
        filterLimit : 1
      };

      var search = navigator.mozContacts.find(search_opts);

      // Possible duplicate found ... bail out, rather do nothing!
      search.onsuccess = function() {
        // search.result is found record (Array of length 1)
        cb_found(rec, search.result);
      };

      // No duplicates, go ahead and create new record
      search.onerror = function() {
        cb_not_found(rec);
      };

    }
  }

  function restoreURLForm(url) {
    document.getElementById("progress-div").style.display = "none";
    document.getElementById("URL-form").style.display = "block";
    if (url !== undefined) {
      document.getElementsByName("URL")[0].value = url;
    }
  }

  function insertData(ldifText) {
    var progressEl = document.querySelector("#progress-div progress");

    var records = parseLDIF(ldifText.split("\n"));

    console.log("records.length = " + records.length);
    if (records.length > 0) {
      if (!window.confirm("THIS WILL ERASE ALL CONTACTS ON YOUR PHONE!\n" +
            "Are you cool with that?")) {
        return false;
      }
    }

    var cl_req = navigator.mozContacts.clear();

    cl_req.onerror = function() {
      throw new Error("Cannot clear whole Contacts database?");
    };

    cl_req.onsuccess = function() {
      progressEl.max = records.length;
      progressEl.value = 0;

      records.forEach(function (rec) {
        var add_contact = translateObjectToContact(rec);

        var sav_req = navigator.mozContacts.save(add_contact);

        sav_req.onsuccess = function() {
          progressEl.value += 1;
          if (progressEl.value >= records.length) {
            window.alert("All contacts have been imported!");
            restoreURLForm();
          }
        };

        sav_req.onerror = function() {
          console.error("Cannot save record " + add_contact.id +
            "\n" + rec.toSource());
        };
      });
    };

  }

  function submitHandler (evt) {
    var URL = document.getElementsByName("URL")[0].value;
    var progressForm = document.getElementById("progress-div");

    document.getElementById("URL-form").style.display = "none";
    progressForm.style.display = "block";

    var req = new XMLHttpRequest();
    req.open("GET", URL, true);
    var progressEl = progressForm.getElementsByTagName("progress")[0];

    req.onprogress = function(evt) {
      if (evt.lengthComputable) {
        progressEl.max = evt.total;
        progressEl.value = evt.loaded;
      }
    };

    req.onload = function() {
      var inText = req.responseText;
      if (inText.length > 0) {
        insertData(inText);

        if (localStorage) {
          localStorage.setItem("lastURL", URL);
        }

      }
    };

    req.onerror = function() {
      window.alert("Cannot load " + URL + "!");
      restoreURLForm(URL);
    };

    req.send();

    evt.stopPropagation();
    evt.preventDefault();
  }

  window.onload = function() {
    if (localStorage && localStorage.lastURL) {
      var oldURL = localStorage.getItem('lastURL');
      document.getElementsByName("URL")[0].value = oldURL;
    }

    document.body.addEventListener("submit",
        submitHandler, false);
  };

}());