xwikistorage.js 21.9 KB
Newer Older
1 2 3 4 5 6
/*jslint indent: 2,
    maxlen: 80,
    sloppy: true,
    nomen: true,
    plusplus: true
*/
7
/*global
8
    define: true,
9
    jIO: true,
10
    jQuery: true,
11 12 13 14 15 16 17 18 19
    XMLHttpRequest: true,
    Blob: true,
    FormData: true,
    window: true
*/
/**
 * JIO XWiki Storage. Type = 'xwiki'.
 * XWiki Document/Attachment storage.
 */
20 21 22
(function () {
  var $, store;
  store = function (spec, my) {
23

24 25
    spec = spec || {};
    var that, priv, xwikistorage;
26

27 28
    that = my.basicStorage(spec, my);
    priv = {};
29

30
    /**
31
     * Get the Space and Page components of a documkent ID.
32
     *
33 34
     * @param id the document id.
     * @return a map of { 'space':<Space>, 'page':<Page> }
35
     */
36 37 38 39 40 41 42 43 44 45
    priv.getParts = function (id) {
      if (id.indexOf('/') === -1) {
        return {
          space: 'Main',
          page: id
        };
      }
      return {
        space: id.substring(0, id.indexOf('/')),
        page: id.substring(id.indexOf('/') + 1)
46
      };
47
    };
48

49 50 51 52 53 54 55
    /**
     * Get the Anti-CSRF token and do something with it.
     *
     * @param andThen function which is called with (formToken, err)
     *                as parameters.
     */
    priv.doWithFormToken = function (andThen) {
56
      $.ajax({
57
        url: priv.formTokenPath,
58 59
        type: "GET",
        async: true,
60 61 62 63 64 65 66 67
        dataType: 'text',
        success: function (html) {
          var m, token;
          // this is unreliable
          //var token = $('meta[name=form_token]', html).attr("content");
          m = html.match(/<meta name="form_token" content="(\w*)"\/>/);
          token = (m && m[1]) || null;
          if (!token) {
68
            andThen(null, {
69 70 71 72 73 74
              "status": 404,
              "statusText": "Not Found",
              "error": "err_form_token_not_found",
              "message": "Anti-CSRF form token was not found in page",
              "reason": "XWiki main page did not contain expected " +
                        "Anti-CSRF form token"
75
            });
76 77
          } else {
            andThen(token, null);
78
          }
79 80 81 82 83 84 85 86 87 88 89
        },
        error: function (jqxhr, err, cause) {
          andThen(null, {
            "status": jqxhr.status,
            "statusText": jqxhr.statusText,
            "error": err,
            "message": "Could not get Anti-CSRF form token from [" +
                priv.xwikiurl + "]",
            "reason": cause
          });
        },
Sven Franck's avatar
Sven Franck committed
90
      });
91
    };
92

93
    /**
94
     * Get the REST read URL for a document.
95
     *
96 97
     * @param docId the id of the document.
     * @return the REST URL for accessing this document.
98
     */
99 100 101 102 103
    priv.getDocRestURL = function (docId) {
      var parts = priv.getParts(docId);
      return priv.xwikiurl + '/rest/wikis/'
        + priv.wiki + '/spaces/' + parts.space + '/pages/' + parts.page;
    };
104 105

    /**
106 107 108
     * Make an HTML5 Blob object.
     * Equivilant to the `new Blob()` constructor.
     * Will fall back on deprecated BlobBuilder if necessary.
109
     */
110 111 112 113 114 115 116 117 118 119 120 121
    priv.makeBlob = function (contentArray, options) {
      var i, bb, BB;
      try {
        // use the constructor if possible.
        return new Blob(contentArray, options);
      } catch (err) {
        // fall back on the blob builder.
        BB = (window.MozBlobBuilder || window.WebKitBlobBuilder
          || window.BlobBuilder);
        bb = new BB();
        for (i = 0; i < contentArray.length; i++) {
          bb.append(contentArray[i]);
Sven Franck's avatar
Sven Franck committed
122
        }
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
        return bb.getBlob(options ? options.type : undefined);
      }
    };

    priv.isBlob = function (potentialBlob) {
      return typeof (potentialBlob) !== 'undefined' &&
        potentialBlob.toString() === "[object Blob]";
    };

    /*
     * Wrapper for the xwikistorage based on localstorage JiO store.
     */
    xwikistorage = {
      /**
       * Get content of an XWikiDocument.
       *
       * @param docId the document ID.
       * @param andThen a callback taking (doc, err), doc being the document
       *                json object and err being the error if any.
       */
      getItem: function (docId, andThen) {

        var success = function (jqxhr) {
          var out, xd;
          out = {};
          try {
            xd = $(jqxhr.responseText);
            xd.find('modified').each(function () {
              out._last_modified = Date.parse($(this).text());
            });
            xd.find('created').each(function () {
              out._creation_date = Date.parse($(this).text());
            });
            xd.find('title').each(function () { out.title = $(this).text(); });
            xd.find('parent').each(function () {
              out.parent = $(this).text();
            });
            xd.find('syntax').each(function () {
              out.syntax = $(this).text();
            });
            xd.find('content').each(function () {
              out.content = $(this).text();
            });
            out._id = docId;
            andThen(out, null);
          } catch (err) {
            andThen(null, {
              status: 500,
              statusText: "internal error",
              error: err,
              message: err.message,
              reason: ""
            });
          }
        };

Sven Franck's avatar
Sven Franck committed
179
        $.ajax({
180 181
          url: priv.getDocRestURL(docId),
          type: "GET",
Sven Franck's avatar
Sven Franck committed
182
          async: true,
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
          dataType: 'xml',

          // Use complete instead of success and error because phantomjs
          // sometimes causes error to be called with html return code 200.
          complete: function (jqxhr) {
            if (jqxhr.status === 404) {
              andThen(null, null);
              return;
            }
            if (jqxhr.status !== 200) {
              andThen(null, {
                "status": jqxhr.status,
                "statusText": jqxhr.statusText,
                "error": "",
                "message": "Failed to get document [" + docId + "]",
                "reason": ""
              });
              return;
            }
            success(jqxhr);
Sven Franck's avatar
Sven Franck committed
203
          }
204
        });
205
      },
206

207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
      /**
       * Get content of an XWikiAttachment.
       *
       * @param attachId the attachment ID.
       * @param andThen a callback taking (attach, err), attach being the
       *                attachment blob and err being the error if any.
       */
      getAttachment: function (docId, fileName, andThen) {
        var xhr, parts, url;
        // need to do this manually, jquery doesn't support returning blobs.
        xhr = new XMLHttpRequest();
        parts = priv.getParts(docId);
        url = priv.xwikiurl + '/bin/download/' + parts.space +
            "/" + parts.page + "/" + fileName + '?cb=' + Math.random();
        xhr.open('GET', url, true);
        if (priv.useBlobs) {
          xhr.responseType = 'blob';
        } else {
          xhr.responseType = 'text';
226
        }
227

228
        xhr.onload = function (e) {
229 230 231 232 233 234
          if (xhr.status === 200) {
            var contentType = xhr.getResponseHeader("Content-Type");
            if (contentType.indexOf(';') > -1) {
              contentType = contentType.substring(0, contentType.indexOf(';'));
            }
            andThen(xhr.response);
235
          } else {
236
            andThen(null, {
237 238 239
              "status": xhr.status,
              "statusText": xhr.statusText,
              "error": "err_network_error",
240
              "message": "Failed to get attachment ["
241
                  + docId + "/" + fileName + "]",
242
              "reason": "Error getting data from network"
243
            });
Sven Franck's avatar
Sven Franck committed
244
          }
245
        };
246

247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
        xhr.send();
      },

      /**
       * Store an XWikiDocument.
       *
       * @param id the document identifier.
       * @param doc the document JSON object containing
       *            "parent", "title", "content", and/or "syntax" keys.
       * @param andThen a callback taking (err), err being the error if any.
       */
      setItem: function (id, doc, andThen) {
        priv.doWithFormToken(function (formToken, err) {
          if (err) {
            that.error(err);
            return;
          }
          var parts = priv.getParts(id);
          $.ajax({
            url: priv.xwikiurl + "/bin/preview/" +
              parts.space + '/' + parts.page,
            type: "POST",
            async: true,
            dataType: 'text',
            data: {
              parent: doc.parent || '',
              title: doc.title || '',
              xredirect: '',
              language: 'en',
  //            RequiresHTMLConversion: 'content',
  //            content_syntax: doc.syntax || 'xwiki/2.1',
              content: doc.content || '',
              xeditaction: 'edit',
              comment: 'Saved by JiO',
              action_saveandcontinue: 'Save & Continue',
              syntaxId: doc.syntax || 'xwiki/2.1',
              xhidden: 0,
              minorEdit: 0,
              ajax: true,
              form_token: formToken
            },
            success: function () {
              andThen(null);
            },
            error: function (jqxhr, err, cause) {
              andThen({
                "status": jqxhr.status,
                "statusText": jqxhr.statusText,
                "error": err,
                "message": "Failed to store document [" + id + "]",
                "reason": cause
              });
            }
          });
        });
      },

      /**
       * Store an XWikiAttachment.
       *
       * @param docId the ID of the document to attach to.
       * @param fileName the attachment file name.
       * @param mimeType the MIME type of the attachment content.
       * @param content the attachment content.
       * @param andThen a callback taking one parameter, the error if any.
       */
      setAttachment: function (docId, fileName, mimeType, content, andThen) {
        priv.doWithFormToken(function (formToken, err) {
          var parts, blob, fd, xhr;
          if (err) {
            that.error(err);
            return;
Sven Franck's avatar
Sven Franck committed
319
          }
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
          parts = priv.getParts(docId);
          blob = priv.isBlob(content)
            ? content
            : priv.makeBlob([content], {type: mimeType});
          fd = new FormData();
          fd.append("filepath", blob, fileName);
          fd.append("form_token", formToken);
          xhr = new XMLHttpRequest();
          xhr.open('POST', priv.xwikiurl + "/bin/upload/" +
                           parts.space + '/' + parts.page, true);
          xhr.onload = function (e) {
            if (xhr.status === 302 || xhr.status === 200) {
              andThen(null);
            } else {
              andThen({
                "status": xhr.status,
                "statusText": xhr.statusText,
                "error": "err_network_error",
                "message": "Failed to store attachment ["
                    + docId + "/" + fileName + "]",
                "reason": "Error posting data"
              });
            }
          };
          xhr.send(fd);
Sven Franck's avatar
Sven Franck committed
345
        });
346
      },
347

348 349 350 351 352
      removeItem: function (id, andThen) {
        priv.doWithFormToken(function (formToken, err) {
          if (err) {
            that.error(err);
            return;
Sven Franck's avatar
Sven Franck committed
353
          }
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
          var parts = priv.getParts(id);
          $.ajax({
            url: priv.xwikiurl + "/bin/delete/" +
              parts.space + '/' + parts.page,
            type: "POST",
            async: true,
            dataType: 'text',
            data: {
              confirm: '1',
              form_token: formToken
            },
            success: function () {
              andThen(null);
            },
            error: function (jqxhr, err, cause) {
              andThen({
                "status": jqxhr.status,
                "statusText": jqxhr.statusText,
                "error": err,
                "message": "Failed to delete document [" + id + "]",
                "reason": cause
              });
            }
          });
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 411 412 413 414
      removeAttachment: function (docId, fileName, andThen) {
        var parts = priv.getParts(docId);
        priv.doWithFormToken(function (formToken, err) {
          if (err) {
            that.error(err);
            return;
          }
          $.ajax({
            url: priv.xwikiurl + "/bin/delattachment/" + parts.space + '/' +
                parts.page + '/' + fileName,
            type: "POST",
            async: true,
            dataType: 'text',
            data: {
              ajax: '1',
              form_token: formToken
            },
            success: function () {
              andThen(null);
            },
            error: function (jqxhr, err, cause) {
              andThen({
                "status": jqxhr.status,
                "statusText": jqxhr.statusText,
                "error": err,
                "message": "Failed to delete attachment ["
                    + docId + '/' + fileName + "]",
                "reason": cause
              });
            }
          });
        });
      }
    };
415

416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
    // ==================== Tools ====================
    /**
     * Update [doc] the document object and remove [doc] keys
     * which are not in [new_doc]. It only changes [doc] keys not starting
     * with an underscore.
     * ex: doc:     {key:value1,_key:value2} with
     *     new_doc: {key:value3,_key:value4} updates
     *     doc:     {key:value3,_key:value2}.
     * @param  {object} doc The original document object.
     * @param  {object} new_doc The new document object
     */
    priv.documentObjectUpdate = function (doc, new_doc) {
      var k;
      for (k in doc) {
        if (doc.hasOwnProperty(k)) {
          if (k[0] !== '_') {
            delete doc[k];
          }
434 435
        }
      }
436 437 438 439 440
      for (k in new_doc) {
        if (new_doc.hasOwnProperty(k)) {
          if (k[0] !== '_') {
            doc[k] = new_doc[k];
          }
441 442
        }
      }
443
    };
444

445 446 447 448 449 450 451 452 453 454 455 456
    /**
     * Checks if an object has no enumerable keys
     * @method objectIsEmpty
     * @param  {object} obj The object
     * @return {boolean} true if empty, else false
     */
    priv.objectIsEmpty = function (obj) {
      var k;
      for (k in obj) {
        if (obj.hasOwnProperty(k)) {
          return false;
        }
457
      }
458 459
      return true;
    };
460

461 462 463
    // ==================== attributes ====================
    // the wiki to store stuff in
    priv.wiki = spec.wiki || 'xwiki';
464

465 466 467
    // unused
    priv.username = spec.username;
    priv.language = spec.language;
468

469 470 471 472 473 474 475
    // URL location of the wiki, unused since
    // XWiki doesn't currently allow cross-domain requests.
    priv.xwikiurl = spec.xwikiurl ||
       window.location.href.replace(/\/xwiki\/bin\//, '/xwiki\n')
         .split('\n')[0];
    // should be: s@/xwiki/bin/.*$@/xwiki@
    // but jslint gets in the way.
476

477 478
    // Which URL to load for getting the Anti-CSRF form token, used for testing.
    priv.formTokenPath = spec.formTokenPath || priv.xwikiurl;
479

480 481 482
    // If true then Blob objects will be returned by
    // getAttachment() rather than strings.
    priv.useBlobs = spec.useBlobs || false;
483

484 485 486 487
  // If true then Blob objects will be returned by
  // getAttachment() rather than strings.
  priv.useBlobs = spec.useBlobs || false;

488

489 490 491 492 493 494
    that.specToStore = function () {
      return {
        "username": priv.username,
        "language": priv.language,
        "xwikiurl": priv.xwikiurl,
      };
495 496
    };

497 498 499 500
    // can't fo wrong since no parameters are required.
    that.validateState = function () {
      return '';
    };
501

502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
    // ==================== commands ====================
    /**
     * Create a document in local storage.
     * @method post
     * @param  {object} command The JIO command
     */
    that.post = function (command) {
      var docId = command.getDocId();
      if (!(typeof docId === "string" && docId !== "")) {
        setTimeout(function () {
          that.error({
            "status": 405,
            "statusText": "Method Not Allowed",
            "error": "method_not_allowed",
            "message": "Cannot create document which id is undefined",
            "reason": "Document id is undefined"
518 519
          });
        });
520
        return;
521
      }
522
      xwikistorage.getItem(docId, function (doc, err) {
523 524
        if (err) {
          that.error(err);
525 526 527 528 529 530 531 532 533 534 535 536 537 538
        } else if (doc === null) {
          // the document does not exist
          xwikistorage.setItem(command.getDocId(),
                               command.cloneDoc(),
                               function (err) {
              if (err) {
                that.error(err);
              } else {
                that.success({
                  "ok": true,
                  "id": command.getDocId()
                });
              }
            });
539
        } else {
540 541 542 543 544 545 546
          // the document already exists
          that.error({
            "status": 409,
            "statusText": "Conflicts",
            "error": "conflicts",
            "message": "Cannot create a new document",
            "reason": "Document already exists (use 'put' to modify it)"
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
    /**
     * Create or update a document in local storage.
     * @method put
     * @param  {object} command The JIO command
     */
    that.put = function (command) {
      xwikistorage.getItem(command.getDocId(), function (doc, err) {
        if (err) {
          that.error(err);
        } else if (doc === null) {
          doc = command.cloneDoc();
        } else {
          priv.documentObjectUpdate(doc, command.cloneDoc());
        }
        // write
        xwikistorage.setItem(command.getDocId(), doc, function (err) {
          if (err) {
            that.error(err);
          } else {
            that.success({
              "ok": true,
              "id": command.getDocId()
            });
          }
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
      });
    };

    /**
     * Add an attachment to a document
     * @method  putAttachment
     * @param  {object} command The JIO command
     */
    that.putAttachment = function (command) {
      xwikistorage.getItem(command.getDocId(), function (doc, err) {
        if (err) {
          that.error(err);
        } else if (doc === null) {
          //  the document does not exist
          that.error({
            "status": 404,
            "statusText": "Not Found",
            "error": "not_found",
            "message": "Impossible to add attachment",
            "reason": "Document not found"
          });
        } else {
          // Document exists, upload attachment.
          xwikistorage.setAttachment(command.getDocId(),
                                     command.getAttachmentId(),
                                     command.getAttachmentMimeType(),
                                     command.getAttachmentData(),
                                     function (err) {
              if (err) {
                that.error(err);
              } else {
                that.success({
                  "ok": true,
                  "id": command.getDocId() + "/" + command.getAttachmentId()
                });
              }
            });
        }
      });
    };

    /**
     * Get a document or attachment
     * @method get
     * @param  {object} command The JIO command
     */
    that.get = that.getAttachment = function (command) {
      if (typeof command.getAttachmentId() === "string") {
        // seeking for an attachment
        xwikistorage.getAttachment(command.getDocId(),
627
                                   command.getAttachmentId(),
628
                                   function (attach, err) {
629 630
            if (err) {
              that.error(err);
631 632
            } else if (attach !== null) {
              that.success(attach);
633
            } else {
634 635 636 637 638 639
              that.error({
                "status": 404,
                "statusText": "Not Found",
                "error": "not_found",
                "message": "Cannot find the attachment",
                "reason": "Attachment does not exist"
640 641 642
              });
            }
          });
643 644 645
      } else {
        // seeking for a document
        xwikistorage.getItem(command.getDocId(), function (doc, err) {
646 647
          if (err) {
            that.error(err);
648 649
          } else if (doc !== null) {
            that.success(doc);
650 651 652 653 654
          } else {
            that.error({
              "status": 404,
              "statusText": "Not Found",
              "error": "not_found",
655 656
              "message": "Cannot find the document",
              "reason": "Document does not exist"
657 658 659
            });
          }
        });
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
      }
    };

    /**
     * Remove a document or attachment
     * @method remove
     * @param  {object} command The JIO command
     */
    that.remove = that.removeAttachment = function (command) {
      var notFoundError, objId, complete;
      notFoundError = function (word) {
        that.error({
          "status": 404,
          "statusText": "Not Found",
          "error": "not_found",
          "message": word + " not found",
          "reason": "missing"
        });
      };

      objId = command.getDocId();
      complete = function (err) {
682 683 684
        if (err) {
          that.error(err);
        } else {
685 686 687
          that.success({
            "ok": true,
            "id": objId
688 689
          });
        }
690 691 692 693 694 695 696 697 698
      };
      if (typeof command.getAttachmentId() === "string") {
        objId += '/' + command.getAttachmentId();
        xwikistorage.removeAttachment(command.getDocId(),
                                      command.getAttachmentId(),
                                      complete);
      } else {
        xwikistorage.removeItem(objId, complete);
      }
699 700
    };

701 702 703 704 705 706 707 708 709 710 711 712 713
    /**
     * Get all filenames belonging to a user from the document index
     * @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": "xwikistorage forbids AllDocs command executions"
714
        });
715
      });
716
    };
717 718

    return that;
719 720
  };

721 722 723 724 725 726 727 728 729
  if (typeof (define) === 'function' && define.amd) {
    define(['jquery', 'jiobase', 'module'], function (jquery, j, mod) {
      $ = jquery;
      jIO.addStorageType('xwiki', store);

      var conf = mod.config();
      conf.type = 'xwiki';

      return jIO.newJio(conf);
730
    });
731 732 733 734
  } else {
    jIO.addStorageType('xwiki', store);
    $ = jQuery;
  }
735

736
}());