revisionstorage.js 30.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
  "use strict";
14
  var that = {}, priv = {};
Sven Franck's avatar
Sven Franck committed
15 16
  spec = spec || {};
  that = my.basicStorage(spec, my);
17 18 19 20 21 22 23 24 25 26
  // ATTRIBUTES //
  priv.doc_tree_suffix = ".revision_tree.json";
  priv.sub_storage = spec.sub_storage;
  // METHODS //
  /**
   * Constructor
   */
  priv.RevisionStorage = function () {
    // no init
  };
Sven Franck's avatar
Sven Franck committed
27

28 29 30 31 32
  /**
   * Description to store in order to be restored later
   * @method specToStore
   * @return {object} Descriptions to store
   */
Sven Franck's avatar
Sven Franck committed
33
  that.specToStore = function () {
34 35 36
    return {
      "sub_storage": priv.sub_storage
    };
Sven Franck's avatar
Sven Franck committed
37 38
  };

39 40 41 42 43 44 45 46 47 48 49 50 51 52
  /**
   * 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
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
  /**
   * 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;
68
    };
Sven Franck's avatar
Sven Franck committed
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
    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);
  };

  /**
84 85 86 87
   * Checks a revision format
   * @method checkDocumentRevisionFormat
   * @param  {object} doc The document object
   * @return {object} null if ok, else error object
Sven Franck's avatar
Sven Franck committed
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
  priv.checkDocumentRevisionFormat = function (doc) {
    var send_error = function (message) {
      return {
        "status": 31,
        "statusText": "Wrong Revision Format",
        "error": "wrong_revision_format",
        "message": message,
        "reason": "Revision is wrong"
      };
    };
    if (typeof doc._rev === "string") {
      if (/^[0-9]+-[0-9a-zA-Z]+$/.test(doc._rev) === false) {
        return send_error("The document revision does not match " +
                          "^[0-9]+-[0-9a-zA-Z]+$");
      }
    }
    if (typeof doc._revs === "object") {
      if (typeof doc._revs.start !== "number" ||
          typeof doc._revs.ids !== "object" ||
          typeof doc._revs.ids.length !== "number") {
        return send_error("The document revision history is not well formated");
      }
    }
    if (typeof doc._revs_info === "object") {
      if (typeof doc._revs_info.length !== "number") {
        return send_error("The document revision information " +
                          "is not well formated");
      }
Sven Franck's avatar
Sven Franck committed
117 118 119
    }
  };

120
  /**
121 122 123
   * Creates a new document tree
   * @method newDocTree
   * @return {object} The new document tree
124
   */
125 126
  priv.newDocTree = function () {
    return {"children": []};
127 128
  };

Sven Franck's avatar
Sven Franck committed
129
  /**
130 131 132 133
   * Convert revs_info to a simple revisions history
   * @method revsInfoToHistory
   * @param  {array} revs_info The revs info
   * @return {object} The revisions history
Sven Franck's avatar
Sven Franck committed
134
   */
135 136 137 138 139 140 141 142 143 144 145
  priv.revsInfoToHistory = function (revs_info) {
    var i, revisions = {
      "start": 0,
      "ids": []
    };
    revs_info = revs_info || [];
    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]);
Sven Franck's avatar
Sven Franck committed
146
    }
147
    return revisions;
Sven Franck's avatar
Sven Franck committed
148 149 150
  };

  /**
151 152 153 154
   * Convert the revision history object to an array of revisions.
   * @method revisionHistoryToList
   * @param  {object} revs The revision history
   * @return {array} The revision array
Sven Franck's avatar
Sven Franck committed
155
   */
156 157 158 159 160 161
  priv.revisionHistoryToList = function (revs) {
    var i, start = revs.start, new_list = [];
    for (i = 0; i < revs.ids.length; i += 1, start -= 1) {
      new_list.push(start + "-" + revs.ids[i]);
    }
    return new_list;
Sven Franck's avatar
Sven Franck committed
162 163 164
  };

  /**
165 166 167 168 169
   * Convert revision list to revs info.
   * @method revisionListToRevsInfo
   * @param  {array} revision_list The revision list
   * @param  {object} doc_tree The document tree
   * @return {array} The document revs info
Sven Franck's avatar
Sven Franck committed
170
   */
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
  priv.revisionListToRevsInfo = function (revision_list, doc_tree) {
    var revisionListToRevsInfoRec, revs_info = [], j;
    for (j = 0; j < revision_list.length; j += 1) {
      revs_info.push({"rev": revision_list[j], "status": "missing"});
    }
    revisionListToRevsInfoRec = function (index, doc_tree) {
      var child, i;
      if (index < 0) {
        return;
      }
      for (i = 0; i < doc_tree.children.length; i += 1) {
        child = doc_tree.children[i];
        if (child.rev === revision_list[index]) {
          revs_info[index].status = child.status;
          revisionListToRevsInfoRec(index - 1, child);
        }
      }
188
    };
189 190
    revisionListToRevsInfoRec(revision_list.length - 1, doc_tree);
    return revs_info;
Sven Franck's avatar
Sven Franck committed
191 192 193
  };

  /**
194 195 196 197
   * Update a document metadata revision properties
   * @method fillDocumentRevisionProperties
   * @param  {object} doc The document object
   * @param  {object} doc_tree The document tree
Sven Franck's avatar
Sven Franck committed
198
   */
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
  priv.fillDocumentRevisionProperties = function (doc, doc_tree) {
    if (doc._revs_info) {
      doc._revs = priv.revsInfoToHistory(doc._revs_info);
    } else if (doc._revs) {
      doc._revs_info = priv.revisionListToRevsInfo(
        priv.revisionHistoryToList(doc._revs),
        doc_tree
      );
    } else if (doc._rev) {
      doc._revs_info = priv.getRevisionInfo(doc._rev, doc_tree);
      doc._revs = priv.revsInfoToHistory(doc._revs_info);
    } else {
      doc._revs_info = [];
      doc._revs = {"start": 0, "ids": []};
    }
    if (doc._revs.start > 0) {
      doc._rev = doc._revs.start + "-" + doc._revs.ids[0];
    } else {
      delete doc._rev;
    }
Sven Franck's avatar
Sven Franck committed
219 220 221
  };

  /**
222 223 224 225 226
   * Generates the next revision of a document.
   * @methode generateNextRevision
   * @param  {object} doc The document metadata
   * @param  {boolean} deleted_flag The deleted flag
   * @return {array} 0:The next revision number and 1:the hash code
Sven Franck's avatar
Sven Franck committed
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
  priv.generateNextRevision = function (doc, deleted_flag) {
    var string, revision_history, revs_info, pseudo_revision;
    doc = priv.clone(doc) || {};
    revision_history = doc._revs;
    revs_info = doc._revs_info;
    delete doc._rev;
    delete doc._revs;
    delete doc._revs_info;
    string = JSON.stringify(doc) + JSON.stringify(revision_history) +
      JSON.stringify(deleted_flag ? true : false);
    revision_history.start += 1;
    revision_history.ids.unshift(priv.hashCode(string));
    doc._revs = revision_history;
    doc._rev = revision_history.start + "-" + revision_history.ids[0];
    revs_info.unshift({
      "rev": doc._rev,
      "status": deleted_flag ? "deleted" : "available"
    });
    doc._revs_info = revs_info;
    return doc;
  };

  /**
   * Gets the revs info from the document tree
   * @method getRevisionInfo
   * @param  {string} revision The revision to search for
   * @param  {object} doc_tree The document tree
   * @return {array} The revs info
   */
  priv.getRevisionInfo = function (revision, doc_tree) {
    var getRevisionInfoRec;
    getRevisionInfoRec = function (doc_tree) {
      var i, child, revs_info;
      for (i = 0; i < doc_tree.children.length; i += 1) {
        child = doc_tree.children[i];
        if (child.rev === revision) {
          return [{"rev": child.rev, "status": child.status}];
265
        }
266 267 268 269
        revs_info = getRevisionInfoRec(child);
        if (revs_info.length > 0 || revision === undefined) {
          revs_info.push({"rev": child.rev, "status": child.status});
          return revs_info;
270
        }
Sven Franck's avatar
Sven Franck committed
271
      }
272
      return [];
273
    };
274
    return getRevisionInfoRec(doc_tree);
Sven Franck's avatar
Sven Franck committed
275 276
  };

277 278 279 280 281 282 283
  priv.updateDocumentTree = function (doc, doc_tree) {
    var revs_info, updateDocumentTreeRec, next_rev;
    doc = priv.clone(doc);
    revs_info = doc._revs_info;
    updateDocumentTreeRec = function (doc_tree, revs_info) {
      var i, child, info;
      if (revs_info.length === 0) {
Sven Franck's avatar
Sven Franck committed
284 285
        return;
      }
286 287 288 289 290 291
      info = revs_info.pop();
      for (i = 0; i < doc_tree.children.length; i += 1) {
        child = doc_tree.children[i];
        if (child.rev === info.rev) {
          return updateDocumentTreeRec(child, revs_info);
        }
Sven Franck's avatar
Sven Franck committed
292
      }
293 294 295 296 297 298
      doc_tree.children.unshift({
        "rev": info.rev,
        "status": info.status,
        "children": []
      });
      updateDocumentTreeRec(doc_tree.children[0], revs_info);
Sven Franck's avatar
Sven Franck committed
299
    };
300
    updateDocumentTreeRec(doc_tree, priv.clone(revs_info));
Sven Franck's avatar
Sven Franck committed
301 302
  };

303 304 305 306 307 308 309 310 311 312 313
  priv.send = function (method, doc, option, callback) {
    that.addJob(
      method,
      priv.sub_storage,
      doc,
      option,
      function (success) {
        callback(undefined, success);
      },
      function (err) {
        callback(err, undefined);
314
      }
315
    );
316 317
  };

318 319 320
  priv.getWinnerRevsInfo = function (doc_tree) {
    var revs_info = [], getWinnerRevsInfoRec;
    getWinnerRevsInfoRec = function (doc_tree, tmp_revs_info) {
Sven Franck's avatar
Sven Franck committed
321
      var i;
322 323
      if (doc_tree.rev) {
        tmp_revs_info.unshift({"rev": doc_tree.rev, "status": doc_tree.status});
Sven Franck's avatar
Sven Franck committed
324
      }
325 326 327 328
      if (doc_tree.children.length === 0) {
        if (revs_info.length < tmp_revs_info.length ||
            (revs_info.length > 0 && revs_info[0].status === "deleted")) {
          revs_info = priv.clone(tmp_revs_info);
329
        }
Sven Franck's avatar
Sven Franck committed
330
      }
331 332
      for (i = 0; i < doc_tree.children.length; i += 1) {
        getWinnerRevsInfoRec(doc_tree.children[i], tmp_revs_info);
Sven Franck's avatar
Sven Franck committed
333
      }
334 335 336
      tmp_revs_info.shift();
    };
    getWinnerRevsInfoRec(doc_tree, []);
Sven Franck's avatar
Sven Franck committed
337 338 339
    return revs_info;
  };

340 341 342
  priv.getConflicts = function (revision, doc_tree) {
    var conflicts = [], getConflictsRec;
    getConflictsRec = function (doc_tree) {
Sven Franck's avatar
Sven Franck committed
343
      var i;
344
      if (doc_tree.rev === revision) {
Sven Franck's avatar
Sven Franck committed
345 346
        return;
      }
347 348 349 350
      if (doc_tree.children.length === 0) {
        if (doc_tree.status !== "deleted") {
          conflicts.push(doc_tree.rev);
        }
Sven Franck's avatar
Sven Franck committed
351
      }
352 353
      for (i = 0; i < doc_tree.children.length; i += 1) {
        getConflictsRec(doc_tree.children[i]);
Sven Franck's avatar
Sven Franck committed
354
      }
355
    };
356 357
    getConflictsRec(doc_tree);
    return conflicts.length === 0 ? undefined : conflicts;
Sven Franck's avatar
Sven Franck committed
358 359
  };

360 361 362 363 364 365 366 367 368
  priv.get = function (doc, option, callback) {
    priv.send("get", doc, option, callback);
  };
  priv.put = function (doc, option, callback) {
    priv.send("put", doc, option, callback);
  };
  priv.remove = function (doc, option, callback) {
    priv.send("remove", doc, option, callback);
  };
369 370 371
  priv.getAttachment = function (attachment, option, callback) {
    priv.send("getAttachment", attachment, option, callback);
  };
372 373 374
  priv.putAttachment = function (attachment, option, callback) {
    priv.send("putAttachment", attachment, option, callback);
  };
375 376 377
  priv.removeAttachment = function (attachment, option, callback) {
    priv.send("removeAttachment", attachment, option, callback);
  };
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 407 408 409 410

  priv.getDocument = function (doc, option, callback) {
    doc = priv.clone(doc);
    doc._id = doc._id + "." + doc._rev;
    delete doc._attachment;
    delete doc._rev;
    delete doc._revs;
    delete doc._revs_info;
    priv.get(doc, option, callback);
  };
  priv.putDocument = function (doc, option, callback) {
    doc = priv.clone(doc);
    doc._id = doc._id + "." + doc._rev;
    delete doc._attachment;
    delete doc._data;
    delete doc._mimetype;
    delete doc._rev;
    delete doc._revs;
    delete doc._revs_info;
    priv.put(doc, option, callback);
  };

  priv.getRevisionTree = function (doc, option, callback) {
    doc = priv.clone(doc);
    doc._id = doc._id + priv.doc_tree_suffix;
    priv.get(doc, option, callback);
  };

  priv.getAttachmentList = function (doc, option, callback) {
    var attachment_id, dealResults, state = "ok", result_list = [], count = 0;
    dealResults = function (attachment_id, attachment_meta) {
      return function (err, attachment) {
        if (state !== "ok") {
Sven Franck's avatar
Sven Franck committed
411
          return;
412
        }
413 414 415 416 417 418 419 420
        count -= 1;
        if (err) {
          if (err.status === 404) {
            result_list.push(undefined);
          } else {
            state = "error";
            return callback(err, undefined);
          }
421
        }
422 423 424 425 426 427 428 429 430 431
        result_list.push({
          "_attachment": attachment_id,
          "_data": attachment,
          "_mimetype": attachment_meta.content_type
        });
        if (count === 0) {
          state = "finished";
          callback(undefined, result_list);
        }
      };
432
    };
433 434 435
    for (attachment_id in doc._attachments) {
      if (doc._attachments.hasOwnProperty(attachment_id)) {
        count += 1;
436 437
        priv.getAttachment(
          {"_id": doc._id, "_attachment": attachment_id},
438 439 440 441
          option,
          dealResults(attachment_id, doc._attachments[attachment_id])
        );
      }
Sven Franck's avatar
Sven Franck committed
442
    }
443 444
    if (count === 0) {
      callback(undefined, []);
Sven Franck's avatar
Sven Franck committed
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
  priv.putAttachmentList = function (doc, option, attachment_list, callback) {
    var i, dealResults, state = "ok", count = 0, attachment;
    attachment_list = attachment_list || [];
    dealResults = function (index) {
      return function (err, response) {
        if (state !== "ok") {
          return;
        }
        count -= 1;
        if (err) {
          state = "error";
          return callback(err, undefined);
        }
        if (count === 0) {
          state = "finished";
          callback(undefined, {"id": doc._id, "ok": true});
        }
      };
    };
    for (i = 0; i < attachment_list.length; i += 1) {
      attachment = attachment_list[i];
      if (attachment !== undefined) {
        count += 1;
471
        attachment._id = doc._id + "." + doc._rev;
472
        priv.putAttachment(attachment, option, dealResults(i));
Sven Franck's avatar
Sven Franck committed
473 474
      }
    }
475 476 477
    if (count === 0) {
      return callback(undefined, {"id": doc._id, "ok": true});
    }
Sven Franck's avatar
Sven Franck committed
478 479
  };

480 481 482 483 484
  priv.putDocumentTree = function (doc, option, doc_tree, callback) {
    doc_tree = priv.clone(doc_tree);
    doc_tree._id = doc._id + priv.doc_tree_suffix;
    priv.put(doc_tree, option, callback);
  };
Sven Franck's avatar
Sven Franck committed
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
  priv.notFoundError = function (message, reason) {
    return {
      "status": 404,
      "statusText": "Not Found",
      "error": "not_found",
      "message": message,
      "reason": reason
    };
  };

  priv.conflictError = function (message, reason) {
    return {
      "status": 409,
      "statusText": "Conflict",
      "error": "conflict",
      "message": message,
      "reason": reason
    };
  };

  priv.revisionGenericRequest = function (doc, option,
                                          specific_parameter, onEnd) {
    var prev_doc, doc_tree, attachment_list, callback = {};
    if (specific_parameter.doc_id) {
      doc._id = specific_parameter.doc_id;
Sven Franck's avatar
Sven Franck committed
511
    }
512 513
    if (specific_parameter.attachment_id) {
      doc._attachment = specific_parameter.attachment_id;
Sven Franck's avatar
Sven Franck committed
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
    callback.begin = function () {
      var check_error;
      doc._id = doc._id || priv.generateUuid();
      if (specific_parameter.revision_needed && !doc._rev) {
        return onEnd(priv.conflictError(
          "Document update conflict",
          "No document revision was provided"
        ), undefined);
      }
      // check revision format
      check_error = priv.checkDocumentRevisionFormat(doc);
      if (check_error !== undefined) {
        return onEnd(check_error, undefined);
      }
      priv.getRevisionTree(doc, option, callback.getRevisionTree);
    };
    callback.getRevisionTree = function (err, response) {
      var winner_info, previous_revision = doc._rev,
        generate_new_revision = doc._revs || doc._revs_info ? false : true;
      if (err) {
        if (err.status !== 404) {
          err.message = "Cannot get document revision tree";
          return onEnd(err, undefined);
        }
Sven Franck's avatar
Sven Franck committed
539
      }
540 541 542 543 544 545 546 547 548
      doc_tree = response || priv.newDocTree();
      if (specific_parameter.get || specific_parameter.getAttachment) {
        if (!doc._rev) {
          winner_info = priv.getWinnerRevsInfo(doc_tree);
          if (winner_info.length === 0) {
            return onEnd(priv.notFoundError(
              "Document not found",
              "missing"
            ), undefined);
Sven Franck's avatar
Sven Franck committed
549
          }
550 551 552 553 554
          if (winner_info[0].status === "deleted") {
            return onEnd(priv.notFoundError(
              "Document not found",
              "deleted"
            ), undefined);
555
          }
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
          doc._rev = winner_info[0].rev;
        }
        priv.fillDocumentRevisionProperties(doc, doc_tree);
        return priv.getDocument(doc, option, callback.getDocument);
      }
      priv.fillDocumentRevisionProperties(doc, doc_tree);
      if (generate_new_revision) {
        if (previous_revision && doc._revs_info.length === 0) {
          // the document history has changed, it means that the document
          // revision was wrong. Add a pseudo history to the document
          doc._rev = previous_revision;
          doc._revs = {
            "start": parseInt(previous_revision.split("-")[0], 10),
            "ids": [previous_revision.split("-")[1]]
          };
          doc._revs_info = [{"rev": previous_revision, "status": "missing"}];
        }
        doc = priv.generateNextRevision(
          doc,
          specific_parameter.remove
576 577
        );
      }
578 579 580 581 582
      if (doc._revs_info.length > 1) {
        prev_doc = {
          "_id": doc._id,
          "_rev": doc._revs_info[1].rev
        };
583 584 585
        if (!generate_new_revision && specific_parameter.putAttachment) {
          prev_doc._rev = doc._revs_info[0].rev;
        }
586 587 588 589 590 591 592 593 594 595 596 597 598
      }
      // force revs_info status
      doc._revs_info[0].status = (specific_parameter.remove ?
                                  "deleted" : "available");
      priv.updateDocumentTree(doc, doc_tree);
      if (prev_doc) {
        return priv.getDocument(prev_doc, option, callback.getDocument);
      }
      if (specific_parameter.remove || specific_parameter.removeAttachment) {
        return onEnd(priv.notFoundError(
          "Unable to remove an inexistent document",
          "missing"
        ), undefined);
599
      }
600
      priv.putDocument(doc, option, callback.putDocument);
601
    };
602 603 604 605 606 607 608 609 610 611
    callback.getDocument = function (err, res_doc) {
      var k, conflicts;
      if (err) {
        if (err.status === 404) {
          if (specific_parameter.remove ||
              specific_parameter.removeAttachment) {
            return onEnd(priv.conflictError(
              "Document update conflict",
              "Document is missing"
            ), undefined);
612
          }
613 614 615 616 617
          if (specific_parameter.get) {
            return onEnd(priv.notFoundError(
              "Unable to find the document",
              "missing"
            ), undefined);
Sven Franck's avatar
Sven Franck committed
618
          }
619 620 621 622
          res_doc = {};
        } else {
          err.message = "Cannot get document";
          return onEnd(err, undefined);
623
        }
624
      }
625 626 627 628 629 630 631 632
      if (specific_parameter.get) {
        res_doc._id = doc._id;
        res_doc._rev = doc._rev;
        if (option.conflicts === true) {
          conflicts = priv.getConflicts(doc._rev, doc_tree);
          if (conflicts) {
            res_doc._conflicts = conflicts;
          }
633
        }
634 635 636 637 638 639 640
        if (option.revs === true) {
          res_doc._revisions = doc._revs;
        }
        if (option.revs_info === true) {
          res_doc._revs_info = doc._revs_info;
        }
        return onEnd(undefined, res_doc);
641
      }
642 643
      if (specific_parameter.putAttachment ||
          specific_parameter.removeAttachment) {
644 645 646 647
        // copy metadata (not beginning by "_" to document
        for (k in res_doc) {
          if (res_doc.hasOwnProperty(k) && !k.match("^_")) {
            doc[k] = res_doc[k];
648 649 650
          }
        }
      }
651 652
      if (specific_parameter.remove) {
        priv.putDocumentTree(doc, option, doc_tree, callback.putDocumentTree);
653
      } else {
654
        priv.getAttachmentList(res_doc, option, callback.getAttachmentList);
655 656
      }
    };
657 658 659 660 661 662 663 664 665 666 667 668 669
    callback.getAttachmentList = function (err, res_list) {
      var i, attachment_found = false;
      if (err) {
        err.message = "Cannot get attachment";
        return onEnd(err, undefined);
      }
      attachment_list = res_list || [];
      if (specific_parameter.getAttachment) {
        // getting specific attachment
        for (i = 0; i < attachment_list.length; i += 1) {
          if (attachment_list[i] &&
              doc._attachment ===
              attachment_list[i]._attachment) {
670
            return onEnd(undefined, attachment_list[i]._data);
671 672
          }
        }
673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
        return onEnd(priv.notFoundError(
          "Unable to get an inexistent attachment",
          "missing"
        ), undefined);
      }
      if (specific_parameter.remove_from_attachment_list) {
        // removing specific attachment
        for (i = 0; i < attachment_list.length; i += 1) {
          if (attachment_list[i] &&
              specific_parameter.remove_from_attachment_list._attachment ===
              attachment_list[i]._attachment) {
            attachment_found = true;
            attachment_list[i] = undefined;
            break;
          }
        }
        if (!attachment_found) {
          return onEnd(priv.notFoundError(
            "Unable to remove an inexistent attachment",
            "missing"
          ), undefined);
694 695
        }
      }
696 697 698 699 700 701 702 703 704 705 706 707
      priv.putDocument(doc, option, callback.putDocument);
    };
    callback.putDocument = function (err, response) {
      var i, attachment_found = false;
      if (err) {
        err.message = "Cannot post the document";
        return onEnd(err, undefined);
      }
      if (specific_parameter.add_to_attachment_list) {
        // adding specific attachment
        attachment_list = attachment_list || [];
        for (i = 0; i < attachment_list.length; i += 1) {
708 709
          if (attachment_list[i] &&
              specific_parameter.add_to_attachment_list._attachment ===
710 711 712
              attachment_list[i]._attachment) {
            attachment_found = true;
            attachment_list[i] = specific_parameter.add_to_attachment_list;
713 714 715
            break;
          }
        }
716 717
        if (!attachment_found) {
          attachment_list.unshift(specific_parameter.add_to_attachment_list);
718
        }
719 720 721 722 723 724
      }
      priv.putAttachmentList(
        doc,
        option,
        attachment_list,
        callback.putAttachmentList
725 726
      );
    };
727 728 729 730 731 732 733 734
    callback.putAttachmentList = function (err, response) {
      if (err) {
        err.message = "Cannot copy attacments to the document";
        return onEnd(err, undefined);
      }
      priv.putDocumentTree(doc, option, doc_tree, callback.putDocumentTree);
    };
    callback.putDocumentTree = function (err, response) {
735
      var response_object;
736 737 738 739
      if (err) {
        err.message = "Cannot update the document history";
        return onEnd(err, undefined);
      }
740
      response_object = {
741
        "ok": true,
742
        "id": doc._id,
743
        "rev": doc._rev
744 745 746 747 748 749 750
      };
      if (specific_parameter.putAttachment ||
          specific_parameter.removeAttachment ||
          specific_parameter.getAttachment) {
        response_object.attachment = doc._attachment;
      }
      onEnd(undefined, response_object);
751 752 753 754 755 756 757
      // if (option.keep_revision_history !== true) {
      //   // priv.remove(prev_doc, option, function () {
      //   //   - change "available" status to "deleted"
      //   //   - remove attachments
      //   //   - done, no callback
      //   // });
      // }
758
    };
759
    callback.begin();
760 761
  };

Sven Franck's avatar
Sven Franck committed
762
  /**
763
   * Post the document metadata and create or update a document tree.
Sven Franck's avatar
Sven Franck committed
764
   * Options:
765 766 767
   * - {boolean} keep_revision_history To keep the previous revisions
   *                                   (false by default) (NYI).
   * @method post
Sven Franck's avatar
Sven Franck committed
768 769
   * @param  {object} command The JIO command
   */
770 771 772 773 774 775 776 777
  that.post = function (command) {
    priv.revisionGenericRequest(
      command.cloneDoc(),
      command.cloneOption(),
      {},
      function (err, response) {
        if (err) {
          return that.error(err);
Sven Franck's avatar
Sven Franck committed
778
        }
779 780 781
        that.success(response);
      }
    );
Sven Franck's avatar
Sven Franck committed
782 783 784
  };

  /**
785
   * Put the document metadata and create or update a document tree.
Sven Franck's avatar
Sven Franck committed
786 787
   * Options:
   * - {boolean} keep_revision_history To keep the previous revisions
788 789
   *                                   (false by default) (NYI).
   * @method put
Sven Franck's avatar
Sven Franck committed
790 791
   * @param  {object} command The JIO command
   */
792 793 794 795 796 797 798 799 800 801 802 803 804
  that.put = function (command) {
    priv.revisionGenericRequest(
      command.cloneDoc(),
      command.cloneOption(),
      {},
      function (err, response) {
        if (err) {
          return that.error(err);
        }
        that.success(response);
      }
    );
  };
Sven Franck's avatar
Sven Franck committed
805 806


807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
  that.putAttachment = function (command) {
    priv.revisionGenericRequest(
      command.cloneDoc(),
      command.cloneOption(),
      {
        "doc_id": command.getDocId(),
        "attachment_id": command.getAttachmentId(),
        "add_to_attachment_list": {
          "_attachment": command.getAttachmentId(),
          "_mimetype": command.getAttachmentMimeType(),
          "_data": command.getAttachmentData()
        },
        "putAttachment": true
      },
      function (err, response) {
        if (err) {
          return that.error(err);
Sven Franck's avatar
Sven Franck committed
824
        }
825
        that.success(response);
Sven Franck's avatar
Sven Franck committed
826
      }
827 828
    );
  };
Sven Franck's avatar
Sven Franck committed
829

830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848
  that.remove = function (command) {
    if (command.getAttachmentId()) {
      return that.removeAttachment(command);
    }
    priv.revisionGenericRequest(
      command.cloneDoc(),
      command.cloneOption(),
      {
        "revision_needed": true,
        "remove": true
      },
      function (err, response) {
        if (err) {
          return that.error(err);
        }
        that.success(response);
      }
    );
  };
Sven Franck's avatar
Sven Franck committed
849

850 851 852 853 854 855 856 857 858 859 860
  that.removeAttachment = function (command) {
    priv.revisionGenericRequest(
      command.cloneDoc(),
      command.cloneOption(),
      {
        "doc_id": command.getDocId(),
        "attachment_id": command.getAttachmentId(),
        "revision_needed": true,
        "removeAttachment": true,
        "remove_from_attachment_list": {
          "_attachment": command.getAttachmentId()
Sven Franck's avatar
Sven Franck committed
861
        }
862 863 864 865
      },
      function (err, response) {
        if (err) {
          return that.error(err);
Sven Franck's avatar
Sven Franck committed
866
        }
867 868 869 870 871 872 873 874 875 876 877 878 879 880
        that.success(response);
      }
    );
  };

  that.get = function (command) {
    if (command.getAttachmentId()) {
      return that.getAttachment(command);
    }
    priv.revisionGenericRequest(
      command.cloneDoc(),
      command.cloneOption(),
      {
        "get": true
Sven Franck's avatar
Sven Franck committed
881
      },
882 883 884 885 886
      function (err, response) {
        if (err) {
          return that.error(err);
        }
        that.success(response);
Sven Franck's avatar
Sven Franck committed
887 888 889 890
      }
    );
  };

891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906
  that.getAttachment = function (command) {
    priv.revisionGenericRequest(
      command.cloneDoc(),
      command.cloneOption(),
      {
        "doc_id": command.getDocId(),
        "attachment_id": command.getAttachmentId(),
        "getAttachment": true
      },
      function (err, response) {
        if (err) {
          return that.error(err);
        }
        that.success(response);
      }
    );
Sven Franck's avatar
Sven Franck committed
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 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
  that.allDocs = function (command) {
    var rows, result = {"total_rows": 0, "rows": []}, functions = {};
    functions.finished = 0;
    functions.falseResponseGenerator = function (response, callback) {
      callback(undefined, response);
    };
    functions.fillResultGenerator = function (doc_id) {
      return function (err, doc_tree) {
        var document_revision, row, revs_info;
        if (err) {
          return that.error(err);
        }
        revs_info = priv.getWinnerRevsInfo(doc_tree);
        document_revision =
          rows.document_revisions[doc_id + "." + revs_info[0].rev]
        if (document_revision) {
          row = {
            "id": doc_id,
            "key": doc_id,
            "value": {
              "rev": revs_info[0].rev
            }
          };
          if (document_revision.doc && command.getOption("include_docs")) {
            document_revision.doc._id = doc_id;
            document_revision.doc._rev = revs_info[0].rev;
            row.doc = document_revision.doc;
          }
          result.rows.push(row);
          result.total_rows += 1;
        }
        functions.success();
      };
    };
    functions.success = function () {
      functions.finished -= 1;
      console.log("-1");
      if (functions.finished === 0) {
        console.log("end");
        that.success(result);
      }
    };
    priv.send("allDocs", null, command.cloneOption(), function (err, response) {
      var i, j, row, selector, selected;
      if (err) {
        return that.error(err);
      }
      selector = /^(.*)\.revision_tree\.json$/;
      rows = {
        "revision_trees": {
          // id.revision_tree.json: {
          //   id: blabla
          //   doc: {...}
          // }
        },
        "document_revisions": {
          // id.rev: {
          //   id: blabla
          //   rev: 1-1
          //   doc: {...}
          // }
        }
      };
      while (response.rows.length > 0) {
        // filling rows
        row = response.rows.shift();
        selected = selector.exec(row.id)
        if (selected) {
          // this is a revision tree
          rows.revision_trees[row.id] = {
            "id": selected[1]
          };
          if (row.doc) {
            rows.revision_trees[row.id].doc = row.doc;
          }
        } else {
          // this is a simple revision
          rows.document_revisions[row.id] = {
            "id": row.id.split(".").slice(0,-1),
            "rev": row.id.split(".").slice(-1)
          };
          if (row.doc) {
            rows.document_revisions[row.id].doc = row.doc;
          }
        }
      }
      console.log(priv.clone(rows));
      functions.finished += 1;
      for (i in rows.revision_trees) {
        if (rows.revision_trees.hasOwnProperty(i)) {
          functions.finished += 1;
          console.log("+1");
          if (rows.revision_trees[i].doc) {
            setTimeout(functions.falseResponseGenerator(
              rows.revision_trees[i].doc,
              functions.fillResultGenerator(rows.revision_trees[i].id)
            ));
          } else {
            priv.getRevisionTree(
              {"_id": rows.revision_trees[i].id},
              command.cloneOption(),
              functions.fillResultGenerator(rows.revision_trees[i].id)
            );
          }
        }
      }
      functions.success();
    });
  };

1019 1020
  // END //
  priv.RevisionStorage();
Sven Franck's avatar
Sven Franck committed
1021
  return that;
1022
}); // end RevisionStorage