localstorage.js 14.3 KB
Newer Older
Tristan Cavelier's avatar
Tristan Cavelier committed
1 2 3 4 5 6 7 8
/**
 * JIO Local Storage. Type = 'local'.
 * It is a database located in the browser local storage.
 */
var newLocalStorage = function ( spec, my ) {
    spec = spec || {};
    var that = my.basicStorage( spec, my ), priv = {};

9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
    /*
     * Wrapper for the localStorage used to simplify instion of any kind of
     * values
     */
    var localstorage = {
        getItem: function (item) {
            return JSON.parse (localStorage.getItem(item));
        },
        setItem: function (item,value) {
            return localStorage.setItem(item,JSON.stringify (value));
        },
        deleteItem: function (item) {
            delete localStorage[item];
        }
    };

25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
    /**
     * Generates a hash code of a string
     * @method hashCode
     * @param  {string} string The string to hash
     * @return {string} The string hash code
     */
    priv.hashCode = function (string) {
        return hex_sha256(string);
    };

    /**
     * Generates the next revision of [previous_revision]. [string] helps us
     * to generate a hash code.
     * @methode generateNextRev
     * @param  {string} previous_revision The previous revision
     * @param  {string} string String to help generate hash code
     * @return {string} The next revision
     */
    priv.generateNextRev = function (previous_revision, string) {
         return (parseInt(previous_revision.split('-')[0],10)+1) + '-' +
            priv.hashCode(previous_revision + string);
    };

48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
    /**
     * Replace substrings to others substring following a [list_of_replacement].
     * It will be executed recusively to replace substrings which are not
     * replaced substrings.
     * It starts from the last element of the list of replacement.
     * @method replaceSubString
     * @param  {string} string The string to replace
     * @param  {array} list_of_replacement A list containing arrays with 2
     * values:
     * - {string} The substring to replace
     * - {string} The new substring
     * ex: [['b', 'abc'], ['abc', 'cba']]
     * @return {string} The new string
     */
    priv.replaceSubString = function (string, list_of_replacement) {
        var i, split_string = string.split(list_of_replacement[0][0]);
        if (list_of_replacement[1]) {
            for (i = 0; i < split_string.length; i += 1) {
                split_string[i] = priv.replaceSubString (
                    split_string[i],
                    list_of_replacement.slice(1)
                );
            }
Tristan Cavelier's avatar
Tristan Cavelier committed
71
        }
72
        return split_string.join(list_of_replacement[0][1]);
Tristan Cavelier's avatar
Tristan Cavelier committed
73
    };
74 75 76 77 78 79 80 81 82

    /**
     * It secures the [string] replacing all '%' by '%%' and '/' by '%2F'.
     * @method secureString
     * @param  {string} string The string to secure
     * @return {string} The secured string
     */
    priv.secureString = function (string) {
        return priv.replaceSubString (string, [['/','%2F'],['%','%%']]);
Tristan Cavelier's avatar
Tristan Cavelier committed
83 84
    };

85 86 87 88 89 90 91 92
    /**
     * It replaces all '%2F' by '/' and '%%' by '%'.
     * @method unsecureString
     * @param  {string} string The string to convert
     * @return {string} The converted string
     */
    priv.unsecureString = function (string) {
        return priv.replaceSubString (string, [['%%','%'],['%2F','/']]);
Tristan Cavelier's avatar
Tristan Cavelier committed
93 94 95
    };

    priv.username = spec.username || '';
96
    priv.secured_username = priv.secureString(priv.username);
Tristan Cavelier's avatar
Tristan Cavelier committed
97
    priv.applicationname = spec.applicationname || 'untitled';
98
    priv.secured_applicationname = priv.secureString(priv.applicationname);
Tristan Cavelier's avatar
Tristan Cavelier committed
99 100 101 102 103

    var storage_user_array_name = 'jio/local_user_array';
    var storage_file_array_name = 'jio/local_file_name_array/' +
        priv.secured_username + '/' + priv.secured_applicationname;

104
    // Overriding serialized()
Tristan Cavelier's avatar
Tristan Cavelier committed
105 106 107 108 109 110 111 112
    var super_serialized = that.serialized;
    that.serialized = function() {
        var o = super_serialized();
        o.applicationname = priv.applicationname;
        o.username = priv.username;
        return o;
    };

113
    // Overrinding validateState()
Tristan Cavelier's avatar
Tristan Cavelier committed
114 115 116 117 118 119 120 121 122 123 124 125 126
    that.validateState = function() {
        if (priv.secured_username) {
            return '';
        }
        return 'Need at least one parameter: "username".';
    };

    /**
     * Returns a list of users.
     * @method getUserArray
     * @return {array} The list of users.
     */
    priv.getUserArray = function () {
127
        return localstorage.getItem(storage_user_array_name) || [];
Tristan Cavelier's avatar
Tristan Cavelier committed
128 129 130 131 132 133 134 135 136 137
    };

    /**
     * Adds a user to the user list.
     * @method addUser
     * @param  {string} user_name The user name.
     */
    priv.addUser = function (user_name) {
        var user_array = priv.getUserArray();
        user_array.push(user_name);
138
        localstorage.setItem(storage_user_array_name,user_array);
Tristan Cavelier's avatar
Tristan Cavelier committed
139 140 141 142
    };

    /**
     * checks if a user exists in the user array.
143
     * @method doesUserExist
Tristan Cavelier's avatar
Tristan Cavelier committed
144 145 146
     * @param  {string} user_name The user name
     * @return {boolean} true if exist, else false
     */
147
    priv.doesUserExist = function (user_name) {
Tristan Cavelier's avatar
Tristan Cavelier committed
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
        var user_array = priv.getUserArray(), i, l;
        for (i = 0, l = user_array.length; i < l; i += 1) {
            if (user_array[i] === user_name) {
                return true;
            }
        }
        return false;
    };

    /**
     * Returns the file names of all existing files owned by the user.
     * @method getFileNameArray
     * @return {array} All the existing file paths.
     */
    priv.getFileNameArray = function () {
163
        return localstorage.getItem(storage_file_array_name) || [];
Tristan Cavelier's avatar
Tristan Cavelier committed
164 165 166 167 168 169 170 171 172 173
    };

    /**
     * Adds a file name to the local file name array.
     * @method addFileName
     * @param  {string} file_name The new file name.
     */
    priv.addFileName = function (file_name) {
        var file_name_array = priv.getFileNameArray();
        file_name_array.push(file_name);
174
        localstorage.setItem(storage_file_array_name,file_name_array);
Tristan Cavelier's avatar
Tristan Cavelier committed
175 176 177 178 179 180 181 182 183 184 185 186 187 188
    };

    /**
     * Removes a file name from the local file name array.
     * @method removeFileName
     * @param  {string} file_name The file name to remove.
     */
    priv.removeFileName = function (file_name) {
        var i, l, array = priv.getFileNameArray(), new_array = [];
        for (i = 0, l = array.length; i < l; i+= 1) {
            if (array[i] !== file_name) {
                new_array.push(array[i]);
            }
        }
189
        localstorage.setItem(storage_file_array_name,new_array);
Tristan Cavelier's avatar
Tristan Cavelier committed
190 191
    };

192 193 194 195 196 197 198 199 200 201 202 203 204 205
    /**
     * Extends [obj] adding 0 to 3 values according to [command] options.
     * @method manageOptions
     * @param  {object} obj The obj to extend
     * @param  {object} command The JIO command
     * @param  {object} doc The document object
     */
    priv.manageOptions = function (obj, command, doc) {
        obj = obj || {};
        if (command.getOption('revs')) {
            obj.revisions = doc._revisions;
        }
        if (command.getOption('revs_info')) {
            obj.revs_info = doc._revs_info;
Tristan Cavelier's avatar
Tristan Cavelier committed
206
        }
207 208 209 210
        if (command.getOption('conflicts')) {
            obj.conflicts = {total_rows:0,rows:[]};
        }
        return obj;
Tristan Cavelier's avatar
Tristan Cavelier committed
211 212
    };

213 214 215 216 217 218 219 220 221
    /**
     * Create a document in the local storage.
     * It will store the file in 'jio/local/USR/APP/FILE_NAME'.
     * The command may have some options:
     * - {boolean} conflicts Add a conflicts object to the response
     * - {boolean} revs Add the revisions history of the document
     * - {boolean} revs_info Add revisions informations
     * @method post
     */
Tristan Cavelier's avatar
Tristan Cavelier committed
222
    that.post = function (command) {
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
        var now = Date.now();
        // wait a little in order to simulate asynchronous saving
        setTimeout (function () {
            var docid, hash, doc, ret, path;

            if (command.getAttachmentId()) {
                that.error({
                    status:403,statusText:'Forbidden',error:'forbidden',
                    message:'Cannot add an attachment with post request.',
                    reason:'attachment cannot be added with a post request'
                });
                return;
            }

            docid = command.getDocId();
            path = 'jio/local/'+priv.secured_username+'/'+
                priv.secured_applicationname+'/'+docid;

            // reading
            doc = localstorage.getItem(path);
            if (!doc) {
                hash = priv.hashCode('' + doc + ' ' + now + '');
                // create document
                doc = {};
                doc._id = docid;
                doc._rev = '1-'+hash;
                doc._revisions = {
                    start: 1,
                    ids: [hash]
                };
                doc._revs_info = [{
                    rev: '1-'+hash,
                    // status can be 'available', 'deleted' or 'missing'
                    status: 'available'
                }];
                if (!priv.doesUserExist (priv.secured_username)) {
                    priv.addUser (priv.secured_username);
                }
                priv.addFileName(docid);
            } else {
                // cannot overwrite
                that.error ({
                    status:409,statusText:'Conflict',error:'conflict',
                    message:'Document already exists.',
                    reason:'the document already exists'
                });
                return;
            }
            localstorage.setItem(path, doc);
            that.success (
                priv.manageOptions(
                    {ok:true,id:docid,rev:doc._rev},
                    command,
                    doc
                )
            );
        });
Tristan Cavelier's avatar
Tristan Cavelier committed
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
    };

    /**
     * Saves a document in the local storage.
     * It will store the file in 'jio/local/USR/APP/FILE_NAME'.
     * @method put
     */
    that.put = function (command) {
        // wait a little in order to simulate asynchronous saving
        setTimeout (function () {
            var secured_docid = priv.secureDocId(command.getDocId()),
            doc = null, path =
                'jio/local/'+priv.secured_username+'/'+
                priv.secured_applicationname+'/'+
                secured_docid;

            if (!priv.checkSecuredDocId(
                secured_docid,command.getDocId(),'put')) {return;}
            // reading
            doc = LocalOrCookieStorage.getItem(path);
            if (!doc) {
                // create document
                doc = {
                    _id: command.getDocId(),
                    content: command.getDocContent(),
                    _creation_date: Date.now(),
                    _last_modified: Date.now()
                };
                if (!priv.userExists(priv.secured_username)) {
                    priv.addUser (priv.secured_username);
                }
                priv.addFileName(secured_docid);
            } else {
                // overwriting
                doc.content = command.getDocContent();
                doc._last_modified = Date.now();
            }
317
            localStorage.setItem(path, doc);
Tristan Cavelier's avatar
Tristan Cavelier committed
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
            that.success ({ok:true,id:command.getDocId()});
        });
    }; // end put

    /**
     * Loads a document from the local storage.
     * It will load file in 'jio/local/USR/APP/FILE_NAME'.
     * You can add an 'options' object to the job, it can contain:
     * - metadata_only {boolean} default false, retrieve the file metadata
     *   only if true.
     * @method get
     */
    that.get = function (command) {

        setTimeout(function () {
            var secured_docid = priv.secureDocId(command.getDocId()),
            doc = null;

            if (!priv.checkSecuredDocId(
                secured_docid,command.getDocId(),'get')) {return;}
338
            doc = localStorage.getItem(
Tristan Cavelier's avatar
Tristan Cavelier committed
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
                'jio/local/'+priv.secured_username+'/'+
                    priv.secured_applicationname+'/'+secured_docid);
            if (!doc) {
                that.error ({status:404,statusText:'Not Found.',
                             error:'not_found',
                             message:'Document "'+ command.getDocId() +
                             '" not found.',
                             reason:'missing'});
            } else {
                if (command.getOption('metadata_only')) {
                    delete doc.content;
                }
                that.success (doc);
            }
        });
    }; // end get

    /**
     * Gets a document list from the local storage.
     * It will retreive an array containing files meta data owned by
     * the user.
     * @method allDocs
     */
    that.allDocs = function (command) {

        setTimeout(function () {
            var new_array = [], array = [], i, l, k = 'key',
            path = 'jio/local/'+priv.secured_username+'/'+
                priv.secured_applicationname, file_object = {};

            array = priv.getFileNameArray();
            for (i = 0, l = array.length; i < l; i += 1) {
                file_object =
372
                    localstorage.getItem(path+'/'+array[i]);
Tristan Cavelier's avatar
Tristan Cavelier committed
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
                if (file_object) {
                    if (command.getOption('metadata_only')) {
                        new_array.push ({
                            id:file_object._id,key:file_object._id,value:{
                                _creation_date:file_object._creation_date,
                                _last_modified:file_object._last_modified}});
                    } else {
                        new_array.push ({
                            id:file_object._id,key:file_object._id,value:{
                                content:file_object.content,
                                _creation_date:file_object._creation_date,
                                _last_modified:file_object._last_modified}});
                    }
                }
            }
            that.success ({total_rows:new_array.length,rows:new_array});
        });
    }; // end allDocs

    /**
     * Removes a document from the local storage.
     * It will also remove the path from the local file array.
     * @method remove
     */
    that.remove = function (command) {
        setTimeout (function () {
            var secured_docid = priv.secureDocId(command.getDocId()),
            path = 'jio/local/'+
                priv.secured_username+'/'+
                priv.secured_applicationname+'/'+
                secured_docid;
            if (!priv.checkSecuredDocId(
                secured_docid,command.getDocId(),'remove')) {return;}
            // deleting
407
            localstorage.deleteItem(path);
Tristan Cavelier's avatar
Tristan Cavelier committed
408 409 410 411 412 413 414 415
            priv.removeFileName(secured_docid);
            that.success ({ok:true,id:command.getDocId()});
        });
    }; // end remove

    return that;
};
jIO.addStorageType('local', newLocalStorage);