localstorage.js 20.7 KB
Newer Older
1
/*
2 3 4 5
 * Copyright 2013, Nexedi SA
 * Released under the LGPL license.
 * http://www.gnu.org/licenses/lgpl.html
 */
6

7
/*jslint indent: 2, maxlen: 80, sloppy: true, nomen: true, regexp: true */
8 9
/*global jIO, localStorage, setTimeout, complex_queries, window, define,
  exports, require */
10

Tristan Cavelier's avatar
Tristan Cavelier committed
11 12
/**
 * JIO Local Storage. Type = 'local'.
Sven Franck's avatar
Sven Franck committed
13
 * Local browser "database" storage.
14 15 16 17 18
 *
 * Storage Description:
 *
 *     {
 *       "type": "local",
19 20 21
 *       "mode": <string>,
 *         // - "localStorage" // default
 *         // - "memory"
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
 *       "username": <non empty string>, // to define user space
 *       "application_name": <string> // default 'untitled'
 *     }
 *
 * Document are stored in path
 * 'jio/localstorage/username/application_name/document_id' like this:
 *
 *     {
 *       "_id": "document_id",
 *       "_attachments": {
 *         "attachment_name": {
 *           "length": data_length,
 *           "digest": "md5-XXX",
 *           "content_type": "mime/type"
 *         },
 *         "attachment_name2": {..}, ...
 *       },
 *       "metadata_name": "metadata_value"
 *       "metadata_name2": ...
 *       ...
 *     }
 *
 * Only "_id" and "_attachments" are specific metadata keys, other one can be
 * added without loss.
 *
 * @class LocalStorage
Tristan Cavelier's avatar
Tristan Cavelier committed
48
 */
Sven Franck's avatar
Sven Franck committed
49

50 51 52 53 54 55
// define([module_name], [dependencies], module);
(function (dependencies, module) {
  "use strict";
  if (typeof define === 'function' && define.amd) {
    return define(dependencies, module);
  }
56 57
  if (typeof exports === 'object') {
    return module(exports, require('jio'), require('complex_queries'));
58
  }
59 60 61 62 63 64 65 66
  window.local_storage = {};
  module(window.local_storage, jIO, complex_queries);
}([
  'exports',
  'jio',
  'complex_queries'
], function (exports, jIO, complex_queries) {
  "use strict";
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83

  /**
   * Checks if an object has no enumerable keys
   *
   * @param  {Object} obj The object
   * @return {Boolean} true if empty, else false
   */
  function objectIsEmpty(obj) {
    var k;
    for (k in obj) {
      if (obj.hasOwnProperty(k)) {
        return false;
      }
    }
    return true;
  }

84 85
  var ram = {}, memorystorage, localstorage;

86 87 88 89
  /*
   * Wrapper for the localStorage used to simplify instion of any kind of
   * values
   */
90
  localstorage = {
91 92 93 94 95 96 97 98 99 100 101 102
    getItem: function (item) {
      var value = localStorage.getItem(item);
      return value === null ? null : JSON.parse(value);
    },
    setItem: function (item, value) {
      return localStorage.setItem(item, JSON.stringify(value));
    },
    removeItem: function (item) {
      return localStorage.removeItem(item);
    }
  };

103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
  /*
   * Wrapper for the localStorage used to simplify instion of any kind of
   * values
   */
  memorystorage = {
    getItem: function (item) {
      var value = ram[item];
      return value === undefined ? null : JSON.parse(value);
    },
    setItem: function (item, value) {
      ram[item] = JSON.stringify(value);
    },
    removeItem: function (item) {
      delete ram[item];
    }
  };

120 121 122 123 124 125
  /**
   * The JIO LocalStorage extension
   *
   * @class LocalStorage
   * @constructor
   */
126 127 128 129 130 131 132 133 134
  function LocalStorage(spec) {
    if (typeof spec.username !== 'string' && !spec.username) {
      throw new TypeError("LocalStorage 'username' must be a string " +
                          "which contains more than one character.");
    }
    this._localpath = 'jio/localstorage/' + spec.username + '/' + (
      spec.application_name === null || spec.application_name ===
        undefined ? 'untitled' : spec.application_name.toString()
    );
135 136
    switch (spec.mode) {
    case "memory":
137 138 139
      this._database = ram;
      this._storage = memorystorage;
      this._mode = "memory";
140 141
      break;
    default:
142 143 144
      this._database = localStorage;
      this._storage = localstorage;
      this._mode = "localStorage";
145 146
      break;
    }
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
  /**
   * Create a document in local storage.
   *
   * @method post
   * @param  {Object} command The JIO command
   * @param  {Object} metadata The metadata to store
   * @param  {Object} options The command options
   */
  LocalStorage.prototype.post = function (command, metadata) {
    var doc, doc_id = metadata._id;
    if (!doc_id) {
      doc_id = jIO.util.generateUuid();
    }
    doc = this._storage.getItem(this._localpath + "/" + doc_id);
    if (doc === null) {
      // the document does not exist
      doc = jIO.util.deepClone(metadata);
      doc._id = doc_id;
      delete doc._attachments;
      this._storage.setItem(this._localpath + "/" + doc_id, doc);
      command.success({"id": doc_id});
    } else {
      // the document already exists
      command.error(
        "conflict",
        "document exists",
        "Cannot create a new document"
      );
    }
  };
Sven Franck's avatar
Sven Franck committed
180

181 182 183 184 185 186 187 188 189
  /**
   * Create or update a document in local storage.
   *
   * @method put
   * @param  {Object} command The JIO command
   * @param  {Object} metadata The metadata to store
   * @param  {Object} options The command options
   */
  LocalStorage.prototype.put = function (command, metadata) {
190
    var doc, tmp, status;
191 192 193 194 195
    doc = this._storage.getItem(this._localpath + "/" + metadata._id);
    if (doc === null) {
      //  the document does not exist
      doc = jIO.util.deepClone(metadata);
      delete doc._attachments;
196
      status = "created";
197 198 199 200 201
    } else {
      // the document already exists
      tmp = jIO.util.deepClone(metadata);
      tmp._attachments = doc._attachments;
      doc = tmp;
202
      status = "ok";
203 204 205
    }
    // write
    this._storage.setItem(this._localpath + "/" + metadata._id, doc);
206
    command.success(status);
207
  };
208

209 210 211 212 213 214 215 216 217
  /**
   * Add an attachment to a document
   *
   * @method putAttachment
   * @param  {Object} command The JIO command
   * @param  {Object} param The given parameters
   * @param  {Object} options The command options
   */
  LocalStorage.prototype.putAttachment = function (command, param) {
218
    var that = this, doc, status = "ok";
219 220 221 222 223 224 225 226 227
    doc = this._storage.getItem(this._localpath + "/" + param._id);
    if (doc === null) {
      //  the document does not exist
      return command.error(
        "not_found",
        "missing",
        "Impossible to add attachment"
      );
    }
228

229 230
    // the document already exists
    // download data
231
    jIO.util.readBlobAsBinaryString(param._blob).then(function (e) {
232
      doc._attachments = doc._attachments || {};
233 234 235
      if (doc._attachments[param._attachment]) {
        status = "created";
      }
236 237
      doc._attachments[param._attachment] = {
        "content_type": param._blob.type,
238
        "digest": jIO.util.makeBinaryStringDigest(e.target.result),
239 240
        "length": param._blob.size
      };
Sven Franck's avatar
Sven Franck committed
241

242
      that._storage.setItem(that._localpath + "/" + param._id + "/" +
243
                            param._attachment, e.target.result);
244
      that._storage.setItem(that._localpath + "/" + param._id, doc);
245 246
      command.success(status,
                      {"hash": doc._attachments[param._attachment].digest});
247
    }, function (e) {
248 249 250
      command.error(
        "request_timeout",
        "blob error",
251
        "Error " + e.status + ", unable to get blob content"
252
      );
253 254
    }, function (e) {
      command.notify((e.loaded / e.total) * 100);
255 256
    });
  };
Sven Franck's avatar
Sven Franck committed
257

258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
  /**
   * Get a document
   *
   * @method get
   * @param  {Object} command The JIO command
   * @param  {Object} param The given parameters
   * @param  {Object} options The command options
   */
  LocalStorage.prototype.get = function (command, param) {
    var doc = this._storage.getItem(
      this._localpath + "/" + param._id
    );
    if (doc !== null) {
      command.success({"data": doc});
    } else {
      command.error(
        "not_found",
        "missing",
        "Cannot find document"
      );
    }
  };
Sven Franck's avatar
Sven Franck committed
280

281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
  /**
   * Get an attachment
   *
   * @method getAttachment
   * @param  {Object} command The JIO command
   * @param  {Object} param The given parameters
   * @param  {Object} options The command options
   */
  LocalStorage.prototype.getAttachment = function (command, param) {
    var doc;
    doc = this._storage.getItem(this._localpath + "/" + param._id);
    if (doc === null) {
      return command.error(
        "not_found",
        "missing document",
        "Cannot find document"
      );
    }
299

300 301 302 303 304 305 306 307
    if (typeof doc._attachments !== 'object' ||
        typeof doc._attachments[param._attachment] !== 'object') {
      return command.error(
        "not_found",
        "missing attachment",
        "Cannot find attachment"
      );
    }
Sven Franck's avatar
Sven Franck committed
308

309 310 311 312 313 314 315 316
    command.success({
      "data": this._storage.getItem(
        this._localpath + "/" + param._id +
          "/" + param._attachment
      ) || "",
      "content_type": doc._attachments[param._attachment].content_type || ""
    });
  };
317

318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
  /**
   * Remove a document
   *
   * @method remove
   * @param  {Object} command The JIO command
   * @param  {Object} param The given parameters
   * @param  {Object} options The command options
   */
  LocalStorage.prototype.remove = function (command, param) {
    var doc, i, attachment_list;
    doc = this._storage.getItem(this._localpath + "/" + param._id);
    attachment_list = [];
    if (doc !== null && typeof doc === "object") {
      if (typeof doc._attachments === "object") {
        // prepare list of attachments
        for (i in doc._attachments) {
          if (doc._attachments.hasOwnProperty(i)) {
            attachment_list.push(i);
336 337
          }
        }
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
      }
    } else {
      return command.error(
        "not_found",
        "missing",
        "Document not found"
      );
    }
    this._storage.removeItem(this._localpath + "/" + param._id);
    // delete all attachments
    for (i = 0; i < attachment_list.length; i += 1) {
      this._storage.removeItem(this._localpath + "/" + param._id +
                               "/" + attachment_list[i]);
    }
    command.success();
  };
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
  /**
   * Remove an attachment
   *
   * @method removeAttachment
   * @param  {Object} command The JIO command
   * @param  {Object} param The given parameters
   * @param  {Object} options The command options
   */
  LocalStorage.prototype.removeAttachment = function (command, param) {
    var doc = this._storage.getItem(this._localpath + "/" + param._id);
    if (typeof doc !== 'object') {
      return command.error(
        "not_found",
        "missing document",
        "Document not found"
      );
    }
    if (typeof doc._attachments !== "object" ||
        typeof doc._attachments[param._attachment] !== "object") {
      return command.error(
        "not_found",
        "missing attachment",
        "Attachment not found"
      );
    }
Sven Franck's avatar
Sven Franck committed
380

381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
    delete doc._attachments[param._attachment];
    if (objectIsEmpty(doc._attachments)) {
      delete doc._attachments;
    }
    this._storage.setItem(this._localpath + "/" + param._id, doc);
    this._storage.removeItem(this._localpath + "/" + param._id +
                             "/" + param._attachment);
    command.success();
  };

  /**
   * Get all filenames belonging to a user from the document index
   *
   * @method allDocs
   * @param  {Object} command The JIO command
   * @param  {Object} param The given parameters
   * @param  {Object} options The command options
   */
  LocalStorage.prototype.allDocs = function (command, param, options) {
    var i, row, path_re, rows, document_list, document_object;
Tristan Cavelier's avatar
Tristan Cavelier committed
401
    param.unused = true;
402 403 404 405 406 407 408 409 410
    rows = [];
    document_list = [];
    path_re = new RegExp(
      "^" + complex_queries.stringEscapeRegexpCharacters(this._localpath) +
        "/[^/]+$"
    );
    if (options.query === undefined && options.sort_on === undefined &&
        options.select_list === undefined &&
        options.include_docs === undefined) {
411
      rows = [];
412 413 414 415 416 417 418 419 420
      for (i in this._database) {
        if (this._database.hasOwnProperty(i)) {
          // filter non-documents
          if (path_re.test(i)) {
            row = { value: {} };
            row.id = i.split('/').slice(-1)[0];
            row.key = row.id;
            if (options.include_docs) {
              row.doc = JSON.parse(this._storage.getItem(i));
421
            }
422
            rows.push(row);
423 424
          }
        }
425 426 427 428 429 430 431 432
      }
      command.success({"data": {"rows": rows, "total_rows": rows.length}});
    } else {
      // create complex query object from returned results
      for (i in this._database) {
        if (this._database.hasOwnProperty(i)) {
          if (path_re.test(i)) {
            document_list.push(this._storage.getItem(i));
433 434
          }
        }
435 436 437 438 439 440 441
      }
      options.select_list = options.select_list || [];
      options.select_list.push("_id");
      if (options.include_docs === true) {
        document_object = {};
        document_list.forEach(function (meta) {
          document_object[meta._id] = meta;
442 443
        });
      }
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
      complex_queries.QueryFactory.create(options.query || "").
        exec(document_list, options);
      document_list = document_list.map(function (value) {
        var o = {
          "id": value._id,
          "key": value._id
        };
        if (options.include_docs === true) {
          o.doc = document_object[value._id];
          delete document_object[value._id];
        }
        delete value._id;
        o.value = value;
        return o;
      });
      command.success({"data": {
        "total_rows": document_list.length,
        "rows": document_list
      }});
    }
  };

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
  /**
   * Check the storage or a specific document
   *
   * @method check
   * @param  {Object} command The JIO command
   * @param  {Object} param The command parameters
   * @param  {Object} options The command options
   */
  LocalStorage.prototype.check = function (command, param) {
    this.genericRepair(command, param, false);
  };

  /**
   * Repair the storage or a specific document
   *
   * @method repair
   * @param  {Object} command The JIO command
   * @param  {Object} param The command parameters
   * @param  {Object} options The command options
   */
  LocalStorage.prototype.repair = function (command, param) {
    this.genericRepair(command, param, true);
  };

  /**
   * A generic method that manage check or repair command
   *
   * @method genericRepair
   * @param  {Object} command The JIO command
   * @param  {Object} param The command parameters
   * @param  {Boolean} repair If true then repair else just check
   */
  LocalStorage.prototype.genericRepair = function (command, param, repair) {

    var that = this, result;

    function referenceAttachment(param, attachment) {
      if (jIO.util.indexOf(param.referenced_attachments, attachment) !== -1) {
        return;
      }
      var i = jIO.util.indexOf(param.unreferenced_attachments, attachment);
      if (i !== -1) {
        param.unreferenced_attachments.splice(i, 1);
      }
      param.referenced_attachments[param.referenced_attachments.length] =
        attachment;
    }

    function attachmentFound(param, attachment) {
      if (jIO.util.indexOf(param.referenced_attachments, attachment) !== -1) {
        return;
      }
      if (jIO.util.indexOf(param.unreferenced_attachments, attachment) !== -1) {
        return;
      }
      param.unreferenced_attachments[param.unreferenced_attachments.length] =
        attachment;
    }

    function repairOne(param, repair) {
      var i, doc, modified;
      doc = that._storage.getItem(that._localpath + "/" + param._id);
      if (doc === null) {
        return; // OK
      }

      // check document type
      if (typeof doc !== 'object') {
        // wrong document
        if (!repair) {
          return {"error": true, "answers": [
            "conflict",
            "corrupted",
            "Document is unrecoverable"
          ]};
        }
        // delete the document
        that._storage.removeItem(that._localpath + "/" + param._id);
        return; // OK
      }
      // good document type
      // repair json document
      if (!repair) {
        if (!(new jIO.Metadata(doc).check())) {
          return {"error": true, "answers": [
            "conflict",
            "corrupted",
            "Some metadata might be lost"
          ]};
        }
      } else {
        modified = jIO.util.uniqueJSONStringify(doc) !==
          jIO.util.uniqueJSONStringify(new jIO.Metadata(doc).format()._dict);
      }
      if (doc._attachments !== undefined) {
        if (typeof doc._attachments !== 'object') {
          if (!repair) {
            return {"error": true, "answers": [
              "conflict",
              "corrupted",
              "Attachments are unrecoverable"
            ]};
          }
          delete doc._attachments;
          that._storage.setItem(that._localpath + "/" + param._id, doc);
          return; // OK
        }
        for (i in doc._attachments) {
          if (doc._attachments.hasOwnProperty(i)) {
            // check attachment existence
            if (that._storage.getItem(that._localpath + "/" + param._id + "/" +
                                      i) !== 'string') {
              if (!repair) {
                return {"error": true, "answers": [
                  "conflict",
                  "missing attachment",
                  "Attachment \"" + i + "\" of \"" + param._id + "\" is missing"
                ]};
              }
              delete doc._attachments[i];
              if (objectIsEmpty(doc._attachments)) {
                delete doc._attachments;
              }
              modified = true;
            } else {
              // attachment exists
              // check attachment metadata
              // check length
              referenceAttachment(param, param._id + "/" + doc._attachments[i]);
              if (doc._attachments[i].length !== undefined &&
                  typeof doc._attachments[i].length !== 'number') {
                if (!repair) {
                  return {"error": true, "answers": [
                    "conflict",
                    "corrupted",
                    "Attachment metadata length corrupted"
                  ]};
                }
                // It could take a long time to get the length, no repair.
                // length can be omited
                delete doc._attachments[i].length;
              }
              // It could take a long time to regenerate the hash, no check.
              // Impossible to discover the attachment content type.
            }
          }
        }
      }
      if (modified) {
        that._storage.setItem(that._localpath + "/" + param._id, doc);
      }
      // OK
    }

    function repairAll(param, repair) {
      var i, result;
      for (i in that._database) {
        if (that._database.hasOwnProperty(i)) {
          // browsing every entry
          if (i.slice(0, that._localpath.length) === that._localpath) {
            // is part of the user space
            if (/^[^\/]+\/[^\/]+$/.test(i.slice(that._localpath.length + 1))) {
              // this is an attachment
              attachmentFound(param, i.slice(that._localpath.length + 1));
            } else if (/^[^\/]+$/.test(i.slice(that._localpath.length + 1))) {
              // this is a document
              param._id = i.slice(that._localpath.length + 1);
              result = repairOne(param, repair);
              if (result) {
                return result;
              }
            } else {
              // this is pollution
              that._storage.removeItem(i);
            }
          }
        }
      }
      // remove unreferenced attachments
      for (i = 0; i < param.unreferenced_attachments.length; i += 1) {
        that._storage.removeItem(that._localpath + "/" +
                                 param.unreferenced_attachments[i]);
      }
    }

    param.referenced_attachments = [];
    param.unreferenced_attachments = [];
    if (typeof param._id === 'string') {
      result = repairOne(param, repair) || {};
    } else {
      result = repairAll(param, repair) || {};
    }
    if (result.error) {
      return command.error.apply(command, result.answers || []);
    }
    command.success.apply(command, result.answers || []);
  };

664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679
  jIO.addStorage('local', LocalStorage);

  //////////////////////////////////////////////////////////////////////
  // Tools

  /**
   * Tool to help users to create local storage description for JIO
   *
   * @param  {String} username The username
   * @param  {String} [application_name] The application_name
   * @return {Object} The storage description
   */
  function createDescription(username, application_name) {
    var description = {
      "type": "local",
      "username": username.toString()
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
    if (application_name !== undefined) {
      description.application_name = application_name.toString();
    }
    return description;
  }
  exports.createDescription = createDescription;

  function clear() {
    var k;
    for (k in localStorage) {
      if (localStorage.hasOwnProperty(k)) {
        if (/^jio\/localstorage\//.test(k)) {
          localStorage.removeItem(k);
        }
      }
    }
  }
  exports.clear = clear;
  exports.clearLocalStorage = clear;

  function clearMemoryStorage() {
    jIO.util.dictClear(ram);
  }
  exports.clearMemoryStorage = clearMemoryStorage;
Tristan Cavelier's avatar
Tristan Cavelier committed
705

706
}));