revisionstorage.js 28.2 KB
Newer Older
Sven Franck's avatar
Sven Franck committed
1 2
/*jslint indent: 2, maxlen: 80, sloppy: true, nomen: true */
/*global jIO: true, hex_sha256: true, setTimeout: true */
3
/**
4
 * JIO Revision Storage.
5
 * It manages document version and can generate conflicts.
6 7 8
 * Description:
 * {
 *     "type": "revision",
9
 *     "sub_storage": <sub storage description>
10
 * }
11
 */
12
jIO.addStorageType('revision', function (spec, my) {
Sven Franck's avatar
Sven Franck committed
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
  "use strict";
  var that, priv = {};
  spec = spec || {};
  that = my.basicStorage(spec, my);

  priv.substorage_key = "sub_storage";
  priv.doctree_suffix = ".revision_tree.json";
  priv.substorage = spec[priv.substorage_key];

  that.specToStore = function () {
    var o = {};
    o[priv.substorage_key] = priv.substorage;
    return o;
  };

28 29 30 31 32 33 34 35 36 37 38 39 40 41
  /**
   * Clones an object in deep (without functions)
   * @method clone
   * @param  {any} object The object to clone
   * @return {any} The cloned object
   */
  priv.clone = function (object) {
    var tmp = JSON.stringify(object);
    if (tmp === undefined) {
      return undefined;
    }
    return JSON.parse(tmp);
  };

Sven Franck's avatar
Sven Franck committed
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
  /**
   * Generate a new uuid
   * @method generateUuid
   * @return {string} The new uuid
   */
  priv.generateUuid = function () {
    var S4 = function () {
      /* 65536 */
      var i, string = Math.floor(
        Math.random() * 0x10000
      ).toString(16);
      for (i = string.length; i < 4; i += 1) {
        string = '0' + string;
      }
      return string;
57
    };
Sven Franck's avatar
Sven Franck committed
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
    return S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() +
      S4() + S4();
  };

  /**
   * 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);
  };

  /**
   * Returns an array version of a revision string
   * @method revisionToArray
   * @param  {string} revision The revision string
   * @return {array} Array containing a revision number and a hash
   */
  priv.revisionToArray = function (revision) {
    if (typeof revision === "string") {
      return [parseInt(revision.split('-')[0], 10),
        revision.split('-')[1]];
    }
    return revision;
  };

86 87 88 89 90 91 92 93 94 95 96 97 98 99
  /**
   * Convert the revision history object to an array of revisions.
   * @method revisionHistoryToArray
   * @param  {object} revs The revision history
   * @return {array} The revision array
   */
  priv.revisionHistoryToArray = function (revs) {
    var i, start = revs.start, newlist = [];
    for (i = 0; i < revs.ids.length; i += 1, start -= 1) {
      newlist.push(start + "-" + revs.ids[i]);
    }
    return newlist;
  };

Sven Franck's avatar
Sven Franck committed
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
  /**
   * 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  {object} doc The document metadata
   * @param  {object} revisions The revision history
   * @param  {boolean} deleted_flag The deleted flag
   * @return {array} 0:The next revision number and 1:the hash code
   */
  priv.generateNextRevision = function (previous_revision,
    doc, revisions, deleted_flag) {
    var string = JSON.stringify(doc) + JSON.stringify(revisions) +
      JSON.stringify(deleted_flag ? true : false);
    if (typeof previous_revision === "number") {
      return [previous_revision + 1, priv.hashCode(string)];
    }
    previous_revision = priv.revisionToArray(previous_revision);
    return [previous_revision[0] + 1, priv.hashCode(string)];
  };

  /**
   * Checks a revision format
   * @method checkRevisionFormat
   * @param  {string} revision The revision string
   * @return {boolean} True if ok, else false
   */
  priv.checkRevisionFormat = function (revision) {
    return (/^[0-9]+-[0-9a-zA-Z]+$/.test(revision));
  };

  /**
   * Creates an empty document tree
   * @method createDocumentTree
   * @param  {array} children An array of children (optional)
   * @return {object} The new document tree
   */
  priv.createDocumentTree = function (children) {
    return {
      "children": children || []
140
    };
Sven Franck's avatar
Sven Franck committed
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
  };

  /**
   * Creates a new document tree node
   * @method createDocumentTreeNode
   * @param  {string} revision The node revision
   * @param  {string} status The node status
   * @param  {array} children An array of children (optional)
   * @return {object} The new document tree node
   */
  priv.createDocumentTreeNode = function (revision, status, children) {
    return {
      "rev": revision,
      "status": status,
      "children": children || []
156
    };
Sven Franck's avatar
Sven Franck committed
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
  };

  /**
   * Gets the specific revision from a document tree.
   * @method getRevisionFromDocumentTree
   * @param  {object} document_tree The document tree
   * @param  {string} revision The specific revision
   * @return {array} The good revs info array
   */
  priv.getRevisionFromDocumentTree = function (document_tree, revision) {
    var result, search, revs_info = [];
    result = [];
    // search method fills "result" with the good revs info
    search = function (document_tree) {
      var i;
      if (document_tree.rev !== undefined) {
        // node is not root
        revs_info.unshift({
          "rev": document_tree.rev,
          "status": document_tree.status
        });
        if (document_tree.rev === revision) {
          result = revs_info;
          return;
181
        }
Sven Franck's avatar
Sven Franck committed
182 183 184 185 186 187 188 189
      }
      // This node has children
      for (i = 0; i < document_tree.children.length; i += 1) {
        // searching deeper to find the good rev
        search(document_tree.children[i]);
        if (result.length > 0) {
          // The result is already found
          return;
190
        }
Sven Franck's avatar
Sven Franck committed
191 192
        revs_info.shift();
      }
193
    };
Sven Franck's avatar
Sven Franck committed
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
    search(document_tree);
    return result;
  };

  /**
   * Gets the winner revision from a document tree.
   * The winner is the deeper revision on the left.
   * @method getWinnerRevisionFromDocumentTree
   * @param  {object} document_tree The document tree
   * @return {array} The winner revs info array
   */
  priv.getWinnerRevisionFromDocumentTree = function (document_tree) {
    var result, search, revs_info = [];
    result = [];
    // search method fills "result" with the winner revs info
    search = function (document_tree, deep) {
      var i;
      if (document_tree.rev !== undefined) {
        // node is not root
        revs_info.unshift({
          "rev": document_tree.rev,
          "status": document_tree.status
        });
      }
      if (document_tree.children.length === 0 && document_tree.status !==
          "deleted") {
        // This node is a leaf
        if (result.length < deep) {
          // The leaf is deeper than result
          result = [];
          for (i = 0; i < revs_info.length; i += 1) {
            result.push(revs_info[i]);
          }
227
        }
Sven Franck's avatar
Sven Franck committed
228 229 230 231 232 233 234 235 236 237 238 239 240
        return;
      }
      // This node has children
      for (i = 0; i < document_tree.children.length; i += 1) {
        // searching deeper to find the deeper leaf
        search(document_tree.children[i], deep + 1);
        revs_info.shift();
      }
    };
    search(document_tree, 0);
    return result;
  };

241 242 243 244
  /**
   * Add a document revision branch to the document tree
   * @method updateDocumentTree
   * @param  {object} doctree The document tree object
245
   * @param  {object|array} revs The revision history object or a revision array
246 247 248 249
   * @param  {boolean} deleted The deleted flag
   * @param  {array} The document revs_info
   */
  priv.updateDocumentTree = function (doctree, revs, deleted) {
Tristan Cavelier's avatar
Tristan Cavelier committed
250
    var revs_info, doctree_iterator, flag, i, rev;
251
    revs_info = [];
252 253 254 255 256 257 258
    if (revs.ids) {
      // revs is a revision history object
      revs = priv.revisionHistoryToArray(revs);
    } else {
      // revs is an array of revisions
      revs = priv.clone(revs);
    }
259 260
    doctree_iterator = doctree;
    while (revs.length > 0) {
Tristan Cavelier's avatar
Tristan Cavelier committed
261
      rev = revs.pop(0);
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
      revs_info.unshift({
        "rev": rev,
        "status": "missing"
      });
      for (i = 0; i < doctree_iterator.children.length; i += 1) {
        if (doctree_iterator.children[i].rev === rev) {
          doctree_iterator = doctree_iterator.children[i];
          revs_info[0].status = doctree_iterator.status;
          rev = undefined;
          break;
        }
      }
      if (rev) {
        doctree_iterator.children.unshift({
          "rev": rev,
          "status": "missing",
          "children": []
        });
        doctree_iterator = doctree_iterator.children[0];
      }
    }
    flag = deleted === true ? "deleted" : "available";
    revs_info[0].status = flag;
    doctree_iterator.status = flag;
    return revs_info;
  };

Sven Franck's avatar
Sven Franck committed
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
  /**
   * Add a document revision to the document tree
   * @method postToDocumentTree
   * @param  {object} doctree The document tree object
   * @param  {object} doc The document object
   * @param  {boolean} set_node_to_deleted Set the revision to deleted
   * @return {array} The added document revs_info
   */
  priv.postToDocumentTree = function (doctree, doc, set_node_to_deleted) {
    var i, revs_info, next_rev, next_rev_str, selectNode, selected_node,
      flag;
    flag = set_node_to_deleted === true ? "deleted" : "available";
    revs_info = [];
    selected_node = doctree;
    selectNode = function (node) {
      var i;
      if (node.rev !== undefined) {
        // node is not root
        revs_info.unshift({
          "rev": node.rev,
          "status": node.status
        });
      }
      if (node.rev === doc._rev) {
        selected_node = node;
        return "node_selected";
      }
      for (i = 0; i < node.children.length; i += 1) {
        if (selectNode(node.children[i]) === "node_selected") {
          return "node_selected";
319
        }
Sven Franck's avatar
Sven Franck committed
320 321 322 323 324 325 326
        revs_info.shift();
      }
    };
    if (typeof doc._rev === "string") {
      // document has a previous revision
      if (selectNode(selected_node) !== "node_selected") {
        // no node was selected, so add a node with a specific rev
327
        revs_info.unshift({
Sven Franck's avatar
Sven Franck committed
328 329
          "rev": doc._rev,
          "status": "missing"
330
        });
331 332 333 334
        selected_node.children.unshift(priv.createDocumentTreeNode(
          doc._rev,
          "missing"
        ));
Sven Franck's avatar
Sven Franck committed
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
        selected_node = selected_node.children[0];
      }
    }
    next_rev = priv.generateNextRevision(
      doc._rev || 0,
      doc,
      priv.revsInfoToHistory(revs_info),
      set_node_to_deleted
    );
    next_rev_str = next_rev.join("-");
    // don't add if the next rev already exists
    for (i = 0; i < selected_node.children.length; i += 1) {
      if (selected_node.children[i].rev === next_rev_str) {
        revs_info.unshift({
          "rev": next_rev_str,
          "status": flag
        });
        if (selected_node.children[i].status !== flag) {
          selected_node.children[i].status = flag;
        }
355
        return revs_info;
Sven Franck's avatar
Sven Franck committed
356 357 358 359 360 361 362
      }
    }
    revs_info.unshift({
      "rev": next_rev.join('-'),
      "status": flag
    });

363 364 365 366
    selected_node.children.unshift(priv.createDocumentTreeNode(
      next_rev.join('-'),
      flag
    ));
Sven Franck's avatar
Sven Franck committed
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

    return revs_info;
  };

  /**
   * Gets an array of leaves revisions from document tree
   * @method getLeavesFromDocumentTree
   * @param  {object} document_tree The document tree
   * @param  {string} except The revision to except
   * @return {array} The array of leaves revisions
   */
  priv.getLeavesFromDocumentTree = function (document_tree, except) {
    var result, search;
    result = [];
    // search method fills [result] with the winner revision
    search = function (document_tree) {
      var i;
      if (except !== undefined && except === document_tree.rev) {
        return;
      }
      if (document_tree.children.length === 0 && document_tree.status !==
          "deleted") {
        // This node is a leaf
        result.push(document_tree.rev);
        return;
      }
      // This node has children
      for (i = 0; i < document_tree.children.length; i += 1) {
        // searching deeper to find the deeper leaf
        search(document_tree.children[i]);
      }
398
    };
Sven Franck's avatar
Sven Franck committed
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
    search(document_tree);
    return result;
  };

  /**
   * Check if revision is a leaf
   * @method isRevisionALeaf
   * @param  {string} revision revision to check
   * @param  {array} leaves all leaves on tree
   * @return {boolean} true/false
   */
  priv.isRevisionALeaf = function (document_tree, revision) {
    var result, search;
    result = undefined;
    // search method fills "result" with the good revs info
    search = function (document_tree) {
      var i;
      if (document_tree.rev !== undefined) {
        // node is not root
        if (document_tree.rev === revision) {
          if (document_tree.children.length === 0) {
            // This node is a leaf
            result = true;
            return;
          }
          result = false;
          return;
426
        }
Sven Franck's avatar
Sven Franck committed
427 428 429 430 431 432 433 434
      }
      // This node has children
      for (i = 0; i < document_tree.children.length; i += 1) {
        // searching deeper to find the good rev
        search(document_tree.children[i]);
        if (result !== undefined) {
          // The result is already found
          return;
435
        }
Sven Franck's avatar
Sven Franck committed
436
      }
437
    };
Sven Franck's avatar
Sven Franck committed
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
    search(document_tree);
    return result || false;
  };

  /**
   * Convert revs_info to a simple revisions history
   * @method revsInfoToHistory
   * @param  {array} revs_info The revs info
   * @return {object} The revisions history
   */
  priv.revsInfoToHistory = function (revs_info) {
    var revisions = {
      "start": 0,
      "ids": []
    }, i;
    if (revs_info.length > 0) {
      revisions.start = parseInt(revs_info[0].rev.split('-')[0], 10);
    }
    for (i = 0; i < revs_info.length; i += 1) {
      revisions.ids.push(revs_info[i].rev.split('-')[1]);
    }
    return revisions;
  };

  /**
   * Returns the revision of the revision position from a revs_info array.
   * @method getRevisionFromPosition
   * @param  {array} revs_info The revs_info array
   * @param  {number} rev_pos The revision position number
   * @return {string} The revision of the good position (empty string if fail)
   */
  priv.getRevisionFromPosition = function (revs_info, rev_pos) {
    var i;
    for (i = revs_info.length - 1; i >= 0; i -= 1) {
      if (priv.revisionToArray(revs_info[i].rev)[0] === rev_pos) {
        return revs_info[i].rev;
      }
    }
    return '';
  };

  /**
   * Post the document metadata and create or update a document tree.
   * Options:
   * - {boolean} keep_revision_history To keep the previous revisions
   *                                   (false by default) (NYI).
   * @method post
   * @param  {object} command The JIO command
   */
  that.post = function (command) {
    var f = {}, doctree, revs_info, doc, docid;
    doc = command.cloneDoc();
    docid = command.getDocId();

    if (typeof doc._rev === "string" && !priv.checkRevisionFormat(doc._rev)) {
      that.error({
        "status": 31,
        "statusText": "Wrong Revision Format",
        "error": "wrong_revision_format",
        "message": "The document previous revision does not match " +
          "^[0-9]+-[0-9a-zA-Z]+$",
        "reason": "Previous revision is wrong"
      });
      return;
    }
    if (typeof docid !== "string") {
      doc._id = priv.generateUuid();
      docid = doc._id;
    }
    f.getDocumentTree = function () {
      var option = command.cloneOption();
      if (option.max_retry === 0) {
        option.max_retry = 3;
      }
      that.addJob(
        "get",
        priv.substorage,
        docid + priv.doctree_suffix,
        option,

        function (response) {

          doctree = response;
Tristan Cavelier's avatar
Tristan Cavelier committed
521
          f.postDocument("put");
Sven Franck's avatar
Sven Franck committed
522 523 524 525 526 527 528 529 530 531 532 533
        },
        function (err) {
          switch (err.status) {
          case 404:
            doctree = priv.createDocumentTree();
            f.postDocument("post");
            break;
          default:
            err.message = "Cannot get document revision tree";
            that.error(err);
            break;
          }
534
        }
Sven Franck's avatar
Sven Franck committed
535
      );
536
    };
Sven Franck's avatar
Sven Franck committed
537
    f.postDocument = function (doctree_update_method) {
538 539 540 541 542
      if (doc._revs) {
        revs_info = priv.updateDocumentTree(doctree, doc._revs);
      } else {
        revs_info = priv.postToDocumentTree(doctree, doc);
      }
Sven Franck's avatar
Sven Franck committed
543
      doc._id = docid + "." + revs_info[0].rev;
544
      delete doc._rev;
545
      delete doc._revs;
Sven Franck's avatar
Sven Franck committed
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
      that.addJob(
        "post",
        priv.substorage,
        doc,
        command.cloneOption(),
        function () {
          f.sendDocumentTree(doctree_update_method);
        },
        function (err) {
          switch (err.status) {
          case 409:
            // file already exists
            f.sendDocumentTree(doctree_update_method);
            break;
          default:
            err.message = "Cannot upload document";
            that.error(err);
            break;
          }
565
        }
Sven Franck's avatar
Sven Franck committed
566
      );
567
    };
Sven Franck's avatar
Sven Franck committed
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
    f.sendDocumentTree = function (method) {
      doctree._id = docid + priv.doctree_suffix;
      that.addJob(
        method,
        priv.substorage,
        doctree,
        command.cloneOption(),
        function () {
          that.success({
            "ok": true,
            "id": docid,
            "rev": revs_info[0].rev
          });
        },
        function (err) {
          // xxx do we try to delete the posted document ?
          err.message = "Cannot save document revision tree";
          that.error(err);
586
        }
Sven Franck's avatar
Sven Franck committed
587
      );
588
    };
Sven Franck's avatar
Sven Franck committed
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
    f.getDocumentTree();
  };

  /**
   * Update the document metadata and update a document tree.
   * Options:
   * - {boolean} keep_revision_history To keep the previous revisions
   *                                   (false by default) (NYI).
   * @method put
   * @param  {object} command The JIO command
   */
  that.put = function (command) {
    that.post(command);
  };

  /**
   * Get the document metadata or attachment.
   * Options:
   * - {boolean} revs Add simple revision history (false by default).
   * - {boolean} revs_info Add revs info (false by default).
   * - {boolean} conflicts Add conflict object (false by default).
   * @method get
   * @param  {object} command The JIO command
   */
  that.get = function (command) {
    var f = {}, doctree, revs_info, prev_rev, option;
    option = command.cloneOption();
    if (option.max_retry === 0) {
      option.max_retry = 3;
    }
    prev_rev = command.getOption("rev");
    if (typeof prev_rev === "string") {
      if (!priv.checkRevisionFormat(prev_rev)) {
        that.error({
          "status": 31,
          "statusText": "Wrong Revision Format",
          "error": "wrong_revision_format",
          "message": "The document previous revision does not match " +
            "[0-9]+-[0-9a-zA-Z]+",
          "reason": "Previous revision is wrong"
        });
        return;
      }
    }
    f.getDocumentTree = function () {
      that.addJob(
        "get",
        priv.substorage,
        command.getDocId() + priv.doctree_suffix,
        option,
        function (response) {
          doctree = response;
          if (prev_rev === undefined) {
            revs_info = priv.getWinnerRevisionFromDocumentTree(doctree);
643 644 645 646 647 648 649 650 651 652 653 654
            if (revs_info.length > 0) {
              prev_rev = revs_info[0].rev;
            } else {
              that.error({
                "status": 404,
                "statusText": "Not Found",
                "error": "not_found",
                "message": "Cannot find the document",
                "reason": "Document is deleted"
              });
              return;
            }
Sven Franck's avatar
Sven Franck committed
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
          } else {
            revs_info = priv.getRevisionFromDocumentTree(doctree, prev_rev);
          }
          f.getDocument(command.getDocId() + "." + prev_rev,
            command.getAttachmentId());
        },
        function (err) {
          switch (err.status) {
          case 404:
            that.error(err);
            break;
          default:
            err.message = "Cannot get document revision tree";
            that.error(err);
            break;
          }
Sven Franck's avatar
Sven Franck committed
671
        }
Sven Franck's avatar
Sven Franck committed
672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
      );
    };
    f.getDocument = function (docid, attmtid) {
      that.addJob(
        "get",
        priv.substorage,
        docid,
        option,
        function (response) {
          var attmt;
          if (typeof response !== "string") {
            if (attmtid !== undefined) {
              if (response._attachments !== undefined) {
                attmt = response._attachments[attmtid];
                if (attmt !== undefined) {
                  prev_rev = priv.getRevisionFromPosition(
                    revs_info,
                    attmt.revpos
                  );
                  f.getDocument(command.getDocId() + "." + prev_rev + "/" +
                    attmtid);
                  return;
Sven Franck's avatar
Sven Franck committed
694
                }
Sven Franck's avatar
Sven Franck committed
695 696 697 698 699 700 701 702 703
              }
              that.error({
                "status": 404,
                "statusText": "Not Found",
                "error": "not_found",
                "message": "Cannot find the attachment",
                "reason": "Attachment is missing"
              });
              return;
Sven Franck's avatar
Sven Franck committed
704
            }
Sven Franck's avatar
Sven Franck committed
705 706 707 708
            response._id = command.getDocId();
            response._rev = prev_rev;
            if (command.getOption("revs") === true) {
              response._revisions = priv.revsInfoToHistory(revs_info);
Sven Franck's avatar
Sven Franck committed
709
            }
Sven Franck's avatar
Sven Franck committed
710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726
            if (command.getOption("revs_info") === true) {
              response._revs_info = revs_info;
            }
            if (command.getOption("conflicts") === true) {
              response._conflicts = priv.getLeavesFromDocumentTree(
                doctree,
                prev_rev
              );
              if (response._conflicts.length === 0) {
                delete response._conflicts;
              }
            }
          }
          that.success(response);
        },
        function (err) {
          that.error(err);
Sven Franck's avatar
Sven Franck committed
727
        }
Sven Franck's avatar
Sven Franck committed
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
      );
    };
    if (command.getAttachmentId() && prev_rev !== undefined) {
      f.getDocument(command.getDocId() + "." + prev_rev +
        "/" + command.getAttachmentId());
    } else {
      f.getDocumentTree();
    }
  };

  /**
   * Remove document or attachment.
   * Options:
   * - {boolean} keep_revision_history To keep the previous revisions
   * @method remove
   * @param  {object} command The JIO command
   */
  that.remove = function (command) {
    var f = {}, del_rev, option, new_doc, revs_info;
    option = command.cloneOption();
    if (option.max_retry === 0) {
      option.max_retry = 3;
    }
    del_rev = command.getDoc()._rev;

    f.removeDocument = function (docid, doctree) {
      if (command.getOption("keep_revision_history") !== true) {
        if (command.getAttachmentId() === undefined) {
          // update tree
          revs_info = priv.postToDocumentTree(
            doctree,
            command.getDoc(),
            true
          );
          // remove revision
          that.addJob(
            "remove",
            priv.substorage,
            docid,
            option,
            function () {
              // put tree
              doctree._id = command.getDocId() + priv.doctree_suffix;
              that.addJob(
                "put",
                priv.substorage,
                doctree,
                command.cloneOption(),
                function () {
                  that.success({
                    "ok": true,
                    "id": command.getDocId(),
                    "rev": revs_info[0].rev
                  });
                },
                function () {
                  that.error({
                    "status": 409,
                    "statusText": "Conflict",
                    "error": "conflict",
                    "message": "Document update conflict.",
                    "reason": "Cannot update document tree"
                  });
                  return;
                }
              );
            },
            function () {
              that.error({
                "status": 404,
                "statusText": "Not Found",
                "error": "not_found",
                "message": "File not found",
                "reason": "Document was not found"
              });
              return;
            }
          );
        } else {
          // get previsous document
          that.addJob(
Sven Franck's avatar
Sven Franck committed
809 810
            "get",
            priv.substorage,
Sven Franck's avatar
Sven Franck committed
811
            command.getDocId() + "." + del_rev,
Sven Franck's avatar
Sven Franck committed
812 813
            option,
            function (response) {
Sven Franck's avatar
Sven Franck committed
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
              // update tree
              revs_info = priv.postToDocumentTree(doctree, command.getDoc());
              new_doc = response;
              delete new_doc._attachments;
              new_doc._id = new_doc._id + "." + revs_info[0].rev;

              // post new document version
              that.addJob(
                "post",
                priv.substorage,
                new_doc,
                command.cloneOption(),
                function () {
                  // put tree
                  doctree._id = command.getDocId() + priv.doctree_suffix;
                  that.addJob(
                    "put",
                    priv.substorage,
                    doctree,
                    command.cloneOption(),
                    function () {
                      that.success({
                        "ok": true,
                        "id": new_doc._id,
                        "rev": revs_info[0].rev
                      });
                    },
                    function (err) {
                      err.message =
                        "Cannot save document revision tree";
                      that.error(err);
Sven Franck's avatar
Sven Franck committed
845
                    }
Sven Franck's avatar
Sven Franck committed
846 847 848 849 850 851 852 853 854 855 856
                  );
                },
                function () {
                  that.error({
                    "status": 409,
                    "statusText": "Conflict",
                    "error": "conflict",
                    "message": "Document update conflict.",
                    "reason": "Cannot update document"
                  });
                  return;
Sven Franck's avatar
Sven Franck committed
857
                }
Sven Franck's avatar
Sven Franck committed
858
              );
Sven Franck's avatar
Sven Franck committed
859
            },
Sven Franck's avatar
Sven Franck committed
860 861 862 863 864 865 866 867 868
            function () {
              that.error({
                "status": 404,
                "statusText": "Not Found",
                "error": "not_found",
                "message": "File not found",
                "reason": "Document was not found"
              });
              return;
Sven Franck's avatar
Sven Franck committed
869
            }
Sven Franck's avatar
Sven Franck committed
870 871 872
          );
        }
      }
Sven Franck's avatar
Sven Franck committed
873
    };
Sven Franck's avatar
Sven Franck committed
874 875 876 877 878 879 880 881 882
    if (typeof del_rev === "string") {
      if (!priv.checkRevisionFormat(del_rev)) {
        that.error({
          "status": 31,
          "statusText": "Wrong Revision Format",
          "error": "wrong_revision_format",
          "message": "The document previous revision does not match " +
            "[0-9]+-[0-9a-zA-Z]+",
          "reason": "Previous revision is wrong"
883
        });
Sven Franck's avatar
Sven Franck committed
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
        return;
      }
    }

    // get doctree
    that.addJob(
      "get",
      priv.substorage,
      command.getDocId() + priv.doctree_suffix,
      option,
      function (response) {
        response._conflicts = priv.getLeavesFromDocumentTree(response);

        if (del_rev === undefined) {
          // no revision provided
          that.error({
            "status": 409,
            "statusText": "Conflict",
            "error": "conflict",
            "message": "Document update conflict.",
            "reason": "Cannot delete a document without revision"
          });
          return;
        }
        // revision provided
        if (priv.isRevisionALeaf(response, del_rev) === true) {
          if (typeof command.getAttachmentId() === "string") {
            f.removeDocument(command.getDocId() + "." + del_rev +
              "/" + command.getAttachmentId(), response);
          } else {
            f.removeDocument(command.getDocId() + "." + del_rev,
              response);
          }
        } else {
          that.error({
            "status": 409,
            "statusText": "Conflict",
            "error": "conflict",
            "message": "Document update conflict.",
            "reason": "Trying to remove non-latest revision"
          });
          return;
        }
      },
      function () {
        that.error({
          "status": 404,
          "statusText": "Not Found",
          "error": "not_found",
          "message": "Document tree not found, please checkdocument ID",
          "reason": "Incorrect document ID"
        });
        return;
      }
    );
  };

  /**
   * Get all documents
   * @method allDocs
   * @param  {object} command The JIO command
   */
  that.allDocs = function () {
    setTimeout(function () {
      that.error({
        "status": 405,
        "statusText": "Method Not Allowed",
        "error": "method_not_allowed",
        "message": "Your are not allowed to use this command",
        "reason": "LocalStorage forbids AllDocs command executions"
      });
    });
  };

  return that;
959
});