index.js 12 KB
Newer Older
李晓兵's avatar
李晓兵 committed
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
/*
 * Copyright 2013 Research In Motion Limited.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* global PluginResult, JNEXT, escape */

var pimContacts,
    ContactError = require("./ContactError"),
    ContactName = require("./ContactName"),
    ContactFindOptions = require("./ContactFindOptions");

function populateSearchFields(fields) {
    var i,
        l,
        key,
        searchFieldsObject = {},
        searchFields = [];

    for (i = 0, l = fields.length; i < l; i++) {
        if (fields[i] === "*") {
            searchFieldsObject[ContactFindOptions.SEARCH_FIELD_GIVEN_NAME] = true;
            searchFieldsObject[ContactFindOptions.SEARCH_FIELD_FAMILY_NAME] = true;
            searchFieldsObject[ContactFindOptions.SEARCH_FIELD_PHONE] = true;
            searchFieldsObject[ContactFindOptions.SEARCH_FIELD_EMAIL] = true;
            searchFieldsObject[ContactFindOptions.SEARCH_FIELD_ORGANIZATION_NAME] = true;
        } else if (fields[i] === "displayName" || fields[i] === "name") {
            searchFieldsObject[ContactFindOptions.SEARCH_FIELD_GIVEN_NAME] = true;
            searchFieldsObject[ContactFindOptions.SEARCH_FIELD_FAMILY_NAME] = true;
        } else if (fields[i] === "nickname") {
            // not supported by Cascades
        } else if (fields[i] === "phoneNumbers") {
            searchFieldsObject[ContactFindOptions.SEARCH_FIELD_PHONE] = true;
        } else if (fields[i] === "emails") {
            searchFieldsObject[ContactFindOptions.SEARCH_FIELD_EMAIL] = true;
        } else if (fields[i] === "addresses") {
            // not supported by Cascades
        } else if (fields[i] === "ims") {
            // not supported by Cascades
        } else if (fields[i] === "organizations") {
            searchFieldsObject[ContactFindOptions.SEARCH_FIELD_ORGANIZATION_NAME] = true;
        } else if (fields[i] === "birthday") {
            // not supported by Cascades
        } else if (fields[i] === "note") {
            // not supported by Cascades
        } else if (fields[i] === "photos") {
            // not supported by Cascades
        } else if (fields[i] === "categories") {
            // not supported by Cascades
        } else if (fields[i] === "urls") {
            // not supported by Cascades
        }
    }

    for (key in searchFieldsObject) {
        if (searchFieldsObject.hasOwnProperty(key)) {
            searchFields.push(window.parseInt(key));
        }
    }

    return searchFields;
}

function convertBirthday(birthday) {
    //Convert date string from native to milliseconds since epoch for cordova-js
    var birthdayInfo;
    if (birthday) {
        birthdayInfo = birthday.split("-");
        return new Date(birthdayInfo[0], birthdayInfo[1] - 1, birthdayInfo[2]).getTime();
    } else {
        return null;
    }
}

function processJnextSaveData(result, JnextData) {
    var data = JnextData;

    if (data._success === true) {
        data.birthday = convertBirthday(data.birthday);
        result.callbackOk(data, false);
    } else {
        result.callbackError(data.code, false);
    }
}

function processJnextRemoveData(result, JnextData) {
    var data = JnextData;

    if (data._success === true) {
        result.callbackOk(data);
    } else {
        result.callbackError(ContactError.UNKNOWN_ERROR, false);
    }
}

function processJnextFindData(eventId, eventHandler, JnextData) {
    var data = JnextData,
        i,
        l,
        more = false,
        resultsObject = {};

    if (data.contacts) {
        for (i = 0, l = data.contacts.length; i < l; i++) {
            data.contacts[i].birthday = convertBirthday(data.contacts[i].birthday);
            data.contacts[i].name = new ContactName(data.contacts[i].name);
        }
    } else {
        data.contacts = []; // if JnextData.contacts return null, return an empty array
    }

    if (data._success === true) {
        eventHandler.error = false;
    }

    if (eventHandler.multiple) {
        // Concatenate results; do not add the same contacts
        for (i = 0, l = eventHandler.searchResult.length; i < l; i++) {
            resultsObject[eventHandler.searchResult[i].id] = true;
        }

        for (i = 0, l = data.contacts.length; i < l; i++) {
            if (resultsObject[data.contacts[i].id]) {
                // Already existing
            } else {
                eventHandler.searchResult.push(data.contacts[i]);
            }
        }

        // check if more search is required
        eventHandler.searchFieldIndex++;
        if (eventHandler.searchFieldIndex < eventHandler.searchFields.length) {
            more = true;
        }
    } else {
        eventHandler.searchResult = data.contacts;
    }

    if (more) {
        pimContacts.getInstance().invokeJnextSearch(eventId);
    } else {
        if (eventHandler.error) {
            eventHandler.result.callbackError(data.code, false);
        } else {
            eventHandler.result.callbackOk(eventHandler.searchResult, false);
        }
    }
}

module.exports = {
    search: function (successCb, failCb, args, env) {
        var cordovaFindOptions = {},
            result = new PluginResult(args, env),
            key;

        for (key in args) {
            if (args.hasOwnProperty(key)) {
                cordovaFindOptions[key] = JSON.parse(decodeURIComponent(args[key]));
            }
        }

        pimContacts.getInstance().find(cordovaFindOptions, result, processJnextFindData);
        result.noResult(true);
    },
    save: function (successCb, failCb, args, env) {
        var attributes = {},
            result = new PluginResult(args, env),
            nativeEmails = [];

        attributes = JSON.parse(decodeURIComponent(args[0]));

        //convert birthday format for our native .so file
        if (attributes.birthday) {
            attributes.birthday = new Date(attributes.birthday).toDateString();
        }

        if (attributes.emails) {
            attributes.emails.forEach(function (email) {
                if (email.value) {
                    if (email.type) {
                        nativeEmails.push({ "type" : email.type, "value" : email.value });
                    } else {
                        nativeEmails.push({ "type" : "home", "value" : email.value });
                    }
                }
            });
            attributes.emails = nativeEmails;
        }

        if (attributes.id !== null) {
            attributes.id = window.parseInt(attributes.id);
        }

        attributes._eventId = result.callbackId;
        pimContacts.getInstance().save(attributes, result, processJnextSaveData);
        result.noResult(true);
    },
    remove: function (successCb, failCb, args, env) {
        var result = new PluginResult(args, env),
            attributes = {
                "contactId": window.parseInt(JSON.parse(decodeURIComponent(args[0]))),
                "_eventId": result.callbackId
            };

        if (!window.isNaN(attributes.contactId)) {
            pimContacts.getInstance().remove(attributes, result, processJnextRemoveData);
            result.noResult(true);
        } else {
            result.error(ContactError.UNKNOWN_ERROR);
            result.noResult(false);
        }
    }
};

///////////////////////////////////////////////////////////////////
// JavaScript wrapper for JNEXT plugin
///////////////////////////////////////////////////////////////////

JNEXT.PimContacts = function ()
{
    var self = this,
        hasInstance = false;

    self.find = function (cordovaFindOptions, pluginResult, handler) {
        //register find eventHandler for when JNEXT onEvent fires
        self.eventHandlers[cordovaFindOptions.callbackId] = {
            "result" : pluginResult,
            "action" : "find",
            "multiple" : cordovaFindOptions[1].filter ? true : false,
            "fields" : cordovaFindOptions[0],
            "searchFilter" : cordovaFindOptions[1].filter,
            "searchFields" : cordovaFindOptions[1].filter ? populateSearchFields(cordovaFindOptions[0]) : null,
            "searchFieldIndex" : 0,
            "searchResult" : [],
            "handler" : handler,
            "error" : true
        };

        self.invokeJnextSearch(cordovaFindOptions.callbackId);
        return "";
    };

    self.invokeJnextSearch = function(eventId) {
        var jnextArgs = {},
            findHandler = self.eventHandlers[eventId];

        jnextArgs._eventId = eventId;
        jnextArgs.fields = findHandler.fields;
        jnextArgs.options = {};
        jnextArgs.options.filter = [];

        if (findHandler.multiple) {
            jnextArgs.options.filter.push({
                "fieldName" : findHandler.searchFields[findHandler.searchFieldIndex],
                "fieldValue" : findHandler.searchFilter
            });
            //findHandler.searchFieldIndex++;
        }

        JNEXT.invoke(self.m_id, "find " + JSON.stringify(jnextArgs));
    };

    self.getContact = function (args) {
        return JSON.parse(JNEXT.invoke(self.m_id, "getContact " + JSON.stringify(args)));
    };

    self.save = function (args, pluginResult, handler) {
        //register save eventHandler for when JNEXT onEvent fires
        self.eventHandlers[args._eventId] = {
            "result" : pluginResult,
            "action" : "save",
            "handler" : handler
        };
        JNEXT.invoke(self.m_id, "save " + JSON.stringify(args));
        return "";
    };

    self.remove = function (args, pluginResult, handler) {
        //register remove eventHandler for when JNEXT onEvent fires
        self.eventHandlers[args._eventId] = {
            "result" : pluginResult,
            "action" : "remove",
            "handler" : handler
        };
        JNEXT.invoke(self.m_id, "remove " + JSON.stringify(args));
        return "";
    };

    self.getId = function () {
        return self.m_id;
    };

    self.getContactAccounts = function () {
        var value = JNEXT.invoke(self.m_id, "getContactAccounts");
        return JSON.parse(value);
    };

    self.init = function () {
        if (!JNEXT.require("libpimcontacts")) {
            return false;
        }

        self.m_id = JNEXT.createObject("libpimcontacts.PimContacts");

        if (self.m_id === "") {
            return false;
        }

        JNEXT.registerEvents(self);
    };

    // Handle data coming back from JNEXT native layer. Each async function registers a handler and a PluginResult object.
    // When JNEXT fires onEvent we parse the result string  back into JSON and trigger the appropriate handler (eventHandlers map
    // uses callbackId as key), along with the actual data coming back from the native layer. Each function may have its own way of
    // processing native data so we do not do any processing here.

    self.onEvent = function (strData) {
        var arData = strData.split(" "),
            strEventDesc = arData[0],
            eventHandler,
            args = {};

        if (strEventDesc === "result") {
            args.result = escape(strData.split(" ").slice(2).join(" "));
            eventHandler = self.eventHandlers[arData[1]];
            if (eventHandler.action === "save" || eventHandler.action === "remove") {
                eventHandler.handler(eventHandler.result, JSON.parse(decodeURIComponent(args.result)));
            } else if (eventHandler.action === "find") {
                eventHandler.handler(arData[1], eventHandler, JSON.parse(decodeURIComponent(args.result)));
            }
        }
    };

    self.m_id = "";
    self.eventHandlers = {};

    self.getInstance = function () {
        if (!hasInstance) {
            self.init();
            hasInstance = true;
        }
        return self;
    };
};

pimContacts = new JNEXT.PimContacts();