Code coverage report for api/corpus/Connection.js

Statements: 75.93% (306 / 403)      Branches: 72.4% (244 / 337)      Functions: 82.22% (37 / 45)      Lines: 75.93% (306 / 403)      Ignored: none     

All files » api/corpus/ » Connection.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 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 86 87 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 117 118 119 120 121 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 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 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 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 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 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 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 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 398 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 426 427 428 429 430 431 432 433 434 435 436 437 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 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 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 809 810 811 812 813 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 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 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 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 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036    1 1                                                                                                   1 262 262   262 262 253 253 1012 9         262     1                                                                   1                                                               15     15 15 5 1   4     10   15           1634 395   1239     249 70   179 52 52   127     127   127 127 127 127   127 127   127 2   127 2     127       127           47     47       47 47           1       1 1   1                                       39     39     118     118 46 46   72 72     72           110 7 7 2   7   110     5     5       5 5     5           553 106 106     553 45   553     140     140 44 44   96 96     96 96           271 56     271 129 41   88         271     138     138 44 44   94 94     94           12 12         7     7     7 7   7     7 4 3     3 3 1   3               224     164     164 2 2   162 162 162     162           293 293 176 176   176 5     5 4   5 5   176     117 83     34 34 6   34 34     34 34 34           34 34     7     7     7 7 7       7   7 4   3 3 3     3             292 98       124 30   94 94                                             292     124           1                 295     362           87 87                             63                                                                           225 225   225   225 225   225 225 225     225 225 225 225 225 225   225 225                     1                                                                                                                               1 1                 1   1           54 54 54 54   54 51 51           54 2     54 54 1 1       53     53                           53         53 14 14             14     14       14       53 1 52                     52   52   52   52   52 5 47 1 46   46 1 45 1 44 12 32 6 26   26   26   26 20 6 1 5 1       53 4 4 4 4                       4 4   4 4       4 1 1   3 3 3   3 3                     3     53   33   20                 1 292 1     1       291 291 291 7 7     291 14 2 2             291 2 2     291 7 7 2   5       291       291 10     291         4 2           1 157     1   77 63   14 14 122     122     14   7   14                 1                                                                                                                             1  
/* globals window, URL, localStorage */
 
var FieldDBObject = require("./../FieldDBObject").FieldDBObject;
var Diacritics = require("diacritics");
/**
 * @class Corpus connections by default define a set of web services which are used by that corpus,
 *         generally on one server. However, over time and use the user might move their audio data to
 *         different servers etc making it more conveint to provide a configuration object which by
 *         convention is the same server, but can be overriden and read by any of the client apps or
 *         webservices. The central authority for a users" corpus is in the user's details on the
 *         user's authentication server.
 *
 *         This class contains basic functions to manipulate CorpusConection json and schema,
 *         can be used as a shared model between clients and servers
 *
 *
 *
 * @param  {Connection} optionalRequestedConnection a object with minimally a dbname
 *
 * @param  {string} dbname                 a name space for the database also a url friendly permanent
 *                                         datbase name (composed of a username and an identifier)
 *
 * @param  {string} corpusid               a uuid of the corpus doc within the database which defines the corpus
 * @param  {string} dbname              @deprecated use dbname instead
 * @param  {string} protocol               @deprecated [https:, http] use corpusUrls instead
 * @param  {string} domain                 @deprecated use corpusUrls instead
 * @param  {string} port                   @deprecated use corpusUrls instead
 * @param  {string} path                   @deprecated use corpusUrls instead was used for McGill server
 *
 * @param  {string} userFriendlyServerName a server name that represents where (most of) the user's resources are
 *                                         for this corpus [Default, Beta, Original, Mcgill Prosody, Localhost, etc]
 *
 * @param  {array} clientUrls              an array of objects {"userFriendlyClientName" :
 *                                         [Spreadsheet, Prototype Online, Localhost Chrome App, Public Url, Acivity Feed, etc],
 *                                         url": completeUrlThatCouldBringSomeoneStraightToThisCorpus}
 * @param  {array} corpusUrls              an array of urls which could "compose" this corpus either by overllapping
 *                                         or by union (for the users who want to have meta corpora which combine multiple
 *                                         smaller corpora, or users with large corpora who would like to shard it across servers)
 * @param  {array} audioUrls               an array of audio/video/speech webservice urls which can be used with
 *                                         this corpus, could be youtube, sound cloud or other storage with or
 *                                         without a one-to-one mapping of namespace with this corpus
 * @param  {array} activityUrls            an array of activity feed urls where this corpus"s activities should
 *                                         be stored (usually only one, but oculd have the active one in
 *                                         position 0 and other older ones afterwards)
 *
 * @param  {array} authUrls                an array of strings indicating where a user could login to get to this corpus
 * @param  {array} lexiconUrls             an array of lexicon urls which can be used with this corpus
 * @param  {array} searchUrls              an array of search urls which can be used with this corpus
 *
 * @name  Connection
 * @extends FieldDBObject
 * @constructs
 */
var Connection = function Connection(options) {
  Eif (!this._fieldDBtype) {
    this._fieldDBtype = "Connection";
  }
  this.debug("Constructing Connection ", options);
  if (options) {
    var cleanDefaultValues = ["dbname", "pouchname", "title", "titleAsUrl"];
    cleanDefaultValues.map(function(cleanMe) {
      if (options[cleanMe] === "default") {
        options[cleanMe] = "";
      }
    });
  }
 
  FieldDBObject.apply(this, arguments);
};
 
Connection.DEFAULT_LOCALHOST_CONNECTION = function(options) {
  return {
    "corpusid": "TBA",
    "dbname": options.dbname,
    "protocol": "https://",
    "domain": "localhost",
    "port": "3183",
    "path": "",
    "userFriendlyServerName": "Localhost",
    "authUrls": ["https://localhost:3182"],
    "clientUrls": [{
      "userFriendlyClientName": "Spreadsheet",
      "url": "chrome-extension://pcflbgejbbgijjbmaodhhbibegdfecjc/index.html"
    }, {
      "userFriendlyClientName": "Prototype Online",
      "url": "https://localhost:6984/" + options.dbname + "/_design/data/corpus.html"
    }, {
      "userFriendlyClientName": "Localhost Chrome App",
      "url": "chrome-extension://kaaemcdklbfiiaihlnkmknkgbnkamcbh/user.html#corpus/" + options.dbname
    }, {
      "userFriendlyClientName": "Public Url",
      "url": "https://localhost:3182/" + options.username + "/" + options.corpusidentifier + "/" + options.dbname
    }, {
      "userFriendlyClientName": "Activity Feed",
      "url": "https://localhost:6984/" + options.dbname + "-activity_feed/_design/activity/activity_feed.html"
    }],
    "corpusUrls": ["https://localhost:6984/" + options.dbname],
    "lexiconUrls": ["https://localhost:3185/train/lexicon/" + options.dbname],
    "searchUrls": ["https://localhost:3195/search/" + options.dbname],
    "audioUrls": ["https://localhost:3184/" + options.dbname + "/utterances"],
    "activityUrls": ["https://localhost:6984/" + options.dbname + "-activity_feed"]
  };
};
 
Connection.prototype = Object.create(FieldDBObject.prototype, /** @lends Connection.prototype */ {
 
  constructor: {
    value: Connection
  },
 
  INTERNAL_MODELS: {
    value: {
      corpusid: FieldDBObject.DEFAULT_STRING,
      titleAsUrl: FieldDBObject.DEFAULT_STRING,
      dbname: FieldDBObject.DEFAULT_STRING,
 
      pouchname: FieldDBObject.DEFAULT_STRING,
      protocol: FieldDBObject.DEFAULT_STRING,
      domain: FieldDBObject.DEFAULT_STRING,
      port: FieldDBObject.DEFAULT_STRING,
      path: FieldDBObject.DEFAULT_STRING,
      userFriendlyServerName: FieldDBObject.DEFAULT_STRING,
 
      authUrls: FieldDBObject.DEFAULT_ARRAY,
      clientUrls: FieldDBObject.DEFAULT_ARRAY,
      corpusUrls: FieldDBObject.DEFAULT_ARRAY,
      lexiconUrls: FieldDBObject.DEFAULT_ARRAY,
      searchUrls: FieldDBObject.DEFAULT_ARRAY,
      audioUrls: FieldDBObject.DEFAULT_ARRAY,
      websiteUrls: FieldDBObject.DEFAULT_ARRAY,
      activityUrls: FieldDBObject.DEFAULT_ARRAY
    }
  },
 
  guessDbType: {
    value: function(value) {
      Iif (!value) {
        return;
      }
      var dbType;
      if (value.indexOf("activity_feed") > -1) {
        if (value.split("-").length >= 3) {
          dbType = "corpus_activity_feed";
        } else {
          dbType = "user_activity_feed";
        }
      } else {
        dbType = "corpus";
      }
      return dbType;
    }
  },
 
  dbname: {
    get: function() {
      if (this.parent && this.parent.dbname) {
        return this.parent.dbname;
      }
      return this._dbname;
    },
    set: function(value) {
      if (value === this._dbname) {
        return;
      }
      if (!value) {
        delete this._dbname;
        return;
      } else {
        Iif (typeof value.trim !== "function") {
          return;
        }
        value = value.trim();
 
        Eif (value !== "default") {
          var pieces = value.split("-");
          var username = pieces.shift();
          var corpusidentifier = pieces.join("-");
 
          username = Connection.validateUsername(username);
          corpusidentifier = Connection.validateIdentifier(corpusidentifier);
 
          if (username.changes && username.changes.length > 0) {
            this.warn(username.changes.join("; "), username.originalIdentifier);
          }
          if (corpusidentifier.changes && corpusidentifier.changes.length > 0) {
            this.warn(corpusidentifier.changes.join("; "), corpusidentifier.originalIdentifier);
          }
 
          value = username.identifier + "-" + corpusidentifier.identifier;
 
        }
      }
      this._dbname = value;
    }
  },
 
  owner: {
    get: function() {
      Iif (!this.dbname) {
        return;
      }
      var pieces = this.dbname.split("-");
      // if (pieces.length !== 2 && this.dbname.indexOf("-activity_feed") !== (this.dbname.length - "-activity_feed".length) ){
      //   throw new Error("Database names should be composed of a username-datbaseidentifier " + this.dbname);
      // }
      var username = pieces[0];
      return username;
    }
  },
 
  gravatar: {
    get: function() {
      Iif (this.parent && this.parent.gravatar) {
        this._gravatar = this.parent.gravatar;
        // } else if (this.parent.team.gravatar) { // Dont use team gravatars for corpus connection gravatars anymore
        //   this._gravatar = this.parent.team.gravatar;
      } else Eif (!this._gravatar && this.dbname && this.parent && this.parent.team && typeof this.parent.team.buildGravatar === "function") {
        this._gravatar = this.parent.team.buildGravatar(this.dbname);
      }
      return this._gravatar;
    },
    set: function(value) {
      if (value === this._gravatar) {
        return;
      }
      if (!value) {
        delete this._gravatar;
        return;
      } else {
        if (typeof value.trim === "function") {
          value = value.trim();
        }
      }
      this._gravatar = value;
    }
  },
 
  corpusid: {
    get: function() {
      Iif (!this._corpusid && this.parent && this.parent.id && this.parent.rev && typeof this.parent.normalizeFieldWithExistingCorpusFields === "function") {
        this._corpusid = this.parent.id;
      }
      return this._corpusid;
    },
    set: function(value) {
      Iif (value === this._corpusid) {
        return;
      }
      if (!value) {
        delete this._corpusid;
        return;
      } else {
        Eif (typeof value.trim === "function") {
          value = value.trim();
        }
      }
      this._corpusid = value;
    }
  },
 
  description: {
    get: function() {
      if (this.parent && this.parent.description) {
        this._description = this.parent.description;
        if (this._description.length > 220) {
          this._description = this._description.substring(0, 200) + "...";
        }
        this.debug("returned this.parent.description", this.parent.id);
      }
      return this._description;
    },
    set: function(value) {
      Iif (value === this._description) {
        return;
      }
      Iif (!value) {
        delete this._description;
        return;
      } else {
        Eif (typeof value.trim === "function") {
          value = value.trim();
        }
      }
      this._description = value;
    }
  },
 
  title: {
    get: function() {
      if (this.parent && this.parent.title) {
        this._title = this.parent.title;
        this.debug("returned this.parent.title", this.parent.id);
      }
 
      if (!this._title && this.dbname) {
        this._title = this.dbname.replace(this.owner + "-", "");
      }
      return this._title;
    },
    set: function(value) {
      Iif (value === this._title) {
        return;
      }
      if (!value) {
        delete this._title;
        return;
      } else {
        Eif (typeof value.trim === "function") {
          value = value.trim();
        }
      }
      this._title = value;
      this._titleAsUrl = "";
    }
  },
 
  titleAsUrl: {
    get: function() {
      if (this.parent && this.parent.titleAsUrl) {
        this._titleAsUrl = this.parent.titleAsUrl;
      }
 
      if (!this._titleAsUrl) {
        if (this.title) {
          this._titleAsUrl = this.sanitizeStringForFileSystem(this.title, "_").toLowerCase();
        } else {
          Iif (this.dbname) {
            this._title = this._titleAsUrl = this.dbname.replace(this.owner + "-", "");
          }
        }
      }
      return this._titleAsUrl;
    },
    set: function(value) {
      Iif (value === this._titleAsUrl) {
        return;
      }
      if (!value) {
        delete this._titleAsUrl;
        return;
      } else {
        Eif (typeof value.trim === "function") {
          value = value.trim();
        }
      }
      this._titleAsUrl = value;
    }
  },
 
  authUrl: {
    get: function() {
      Eif (this.authUrls && this.authUrls[0]) {
        return this.authUrls[0];
      }
      return "";
    },
    set: function(value) {
      Iif (this.authUrls && value === this.authUrls[0]) {
        return;
      }
      Iif (!value) {
        return;
      } else {
        Eif (typeof value.trim === "function") {
          value = value.trim();
        }
        value = value.replace(/[^.\/]*.fieldlinguist.com:3183/g, "auth.lingsync.org");
      }
 
      if (!this.authUrls) {
        this.authUrls = [value];
      } else Iif (this.authUrls.length === 0) {
        this.authUrls.unshift(value);
      } else {
        var alreadyKnown = this.authUrls.indexOf(value);
        if (alreadyKnown > -1) {
          this.authUrls.splice(alreadyKnown, 1);
        }
        this.authUrls.unshift(value);
      }
 
    }
  },
 
  domain: {
    get: function() {
      return this._domain || "";
    },
    set: function(value) {
      Iif (value === this._domain) {
        return;
      }
      if (!value) {
        delete this._domain;
        return;
      } else {
        Eif (typeof value.trim === "function") {
          value = value.trim();
          value = value.replace(/ifielddevs.iriscouch.com/g, "corpus.lingsync.org");
        }
      }
      this._domain = value;
    }
  },
 
  corpusUrl: {
    get: function() {
      var corpusurl;
      if (this.corpusUrls && this.corpusUrls[0]) {
        this.debug("getting corpusUrl", this.dbname, this.corpusUrls);
        corpusurl = this.corpusUrls[0];
 
        if (this.dbname && corpusurl.indexOf(this.dbname) === -1) {
          this.debug(" corpusUrl should have had the dbname", corpusurl);
 
          // if its a couchdb, use the dbname in the url
          if (corpusurl.indexOf("984") > -1 || corpusurl.indexOf("https://corpusdev.") > -1 || corpusurl.indexOf("https://corpus.") > -1) {
            corpusurl = corpusurl + "/" + this.dbname;
          }
          this.debug(" corpusUrl is", corpusurl);
          this.corpusUrls[0] = corpusurl;
        }
        return corpusurl;
      }
 
      if (!this.domain || !this.dbname) {
        return "";
      }
 
      corpusurl = this.protocol + this.domain;
      if (this.port && this.port !== "443" && this.port !== "80") {
        corpusurl = corpusurl + ":" + this.port;
      }
      var path = this.path || "";
      Iif (path) {
        path = "/" + path;
      }
      corpusurl = corpusurl + path;
      corpusurl = corpusurl + "/" + this.dbname;
      corpusurl = corpusurl.replace("http://localhost:5984", "https://localhost:6984");
      /*
       * For debugging cors #838: Switch to use the corsproxy corpus service instead
       * of couchdb directly
       */
      // corpusurl = corpusurl.replace(/https/g,"http").replace(/6984/g,"3186");
      this.corpusUrls = [corpusurl];
      return corpusurl;
    },
    set: function(value) {
      Iif (this.corpusUrls && value === this.corpusUrls[0]) {
        return;
      }
      Iif (!value) {
        return;
      } else {
        Eif (typeof value.trim === "function") {
          value = value.trim();
          value = value.replace("http://localhost:5984", "https://localhost:6984");
        }
      }
 
      Iif (!this.corpusUrls) {
        this.corpusUrls = [value];
      } else if (this.corpusUrls.length === 0) {
        this.corpusUrls.unshift(value);
      } else {
        this.corpusUrls = Connection.cleanCorpusUrls(this.corpusUrls);
        var alreadyKnown = this.corpusUrls.indexOf(value);
        Iif (alreadyKnown > -1) {
          this.corpusUrls.splice(alreadyKnown, 1);
        }
        this.corpusUrls.unshift(value);
      }
    }
  },
 
  websiteUrl: {
    get: function() {
      if (this.websiteUrls && this.websiteUrls[0]) {
        return this.websiteUrls[0];
      }
    },
    set: function(value) {
      if (this.websiteUrls && value === this.websiteUrls[0]) {
        return;
      }
      Eif (!value) {
        return;
      } else {
        if (typeof value.trim === "function") {
          value = value.trim();
        }
      }
 
      if (!this.websiteUrls) {
        this.websiteUrls = [value];
      } else if (this.websiteUrls.length === 0) {
        this.websiteUrls.unshift(value);
      } else {
        var alreadyKnown = this.websiteUrls.indexOf(value);
        if (alreadyKnown > -1) {
          this.websiteUrls.splice(alreadyKnown, 1);
        }
        this.websiteUrls.unshift(value);
      }
    }
  },
 
  website: {
    get: function() {
      return this.websiteUrl;
    },
    set: function(value) {
      this.websiteUrl = value;
    }
  },
 
  brand: {
    get: function() {
      return this.userFriendlyServerName;
    },
    set: function(value) {
      this.userFriendlyServerName = value;
    }
  },
 
  brandLowerCase: {
    get: function() {
      return this._brandLowerCase || this._serverLabel || "";
    },
    set: function(value) {
      this._brandLowerCase = value;
    }
  },
 
  serverLabel: {
    get: function() {
      Eif (this._serverLabel) {
        return this._serverLabel;
      }
      var connection;
      if (this.brand) {
        var brand = this.brand.toLowerCase().split(".")[0];
        connection = Connection.knownConnections[brand];
        return connection ? connection.serverLabel : brand;
      }
      if (this.domain) {
        connection = Connection.defaultConnection(this.domain);
        return connection.serverLabel;
      }
      return "";
    },
    set: function(value) {
      this._serverLabel = value;
    }
  },
 
  replicatedCorpusUrls: {
    get: function() {
      return this._replicatedCorpusUrls || FieldDBObject.DEFAULT_COLLECTION;
    },
    set: function(value) {
      if (value === this._replicatedCorpusUrls) {
        return;
      }
      if (!value) {
        delete this._replicatedCorpusUrls;
        return;
      }
      this._replicatedCorpusUrls = value;
    }
  },
 
  olacExportConnections: {
    get: function() {
      return this._olacExportConnections || FieldDBObject.DEFAULT_COLLECTION;
    },
    set: function(value) {
      if (value === this._olacExportConnections) {
        return;
      }
      if (!value) {
        delete this._olacExportConnections;
        return;
      }
      this._olacExportConnections = value;
    }
  },
 
  toJSON: {
    value: function(includeEvenEmptyAttributes, removeEmptyAttributes) {
      this.debug("Customizing toJSON ", includeEvenEmptyAttributes, removeEmptyAttributes);
      includeEvenEmptyAttributes = true;
 
      this.debug(" forcing corpusUrls to be defined ", this.corpusUrl, this.corpusUrls);
      // this.corpusUrls = Connection.cleanCorpusUrls(this.corpusUrls);
      this.brandLowerCase = this.brandLowerCase;
      var json = FieldDBObject.prototype.toJSON.apply(this, arguments);
 
      delete json.dateCreated;
      delete json.dateModified;
      delete json.database;
 
      // TODO eventually dont include the label and hint but now include it for backward compaitibilty
      json.pouchname = json.dbname = this.dbname || "";
      json.title = this.title || json.dbname;
      json.titleAsUrl = this.titleAsUrl || json.dbname;
      json.website = this.website || "";
      json.fieldDBtype = this.fieldDBtype;
      delete json._type;
 
      this.debug(json);
      return json;
    }
  }
 
});
 
/*
 * This function is the same in all webservicesconfig, now any couchapp can
 * login to any server, and register on the corpus server which matches its
 * origin.
 */
Connection.knownConnections = {
  localhost: new Connection({
    protocol: "https://",
    domain: "localhost",
    port: "6984",
    dbname: "default",
    path: "",
    serverLabel: "localhost",
    authUrls: ["https://localhost:3183"],
    websiteUrls: ["https://localhost:3182"],
    corpusUrls: ["https://localhost:6984"],
    userFriendlyServerName: "Localhost"
  }),
  beta: new Connection({
    protocol: "https://",
    domain: "corpusdev.lingsync.org",
    port: "443",
    dbname: "default",
    path: "",
    serverLabel: "beta",
    brandLowerCase: "lingsync_beta",
    authUrls: ["https://authdev.lingsync.org"],
    websiteUrls: ["http://lingsync.org"],
    corpusUrls: ["https://corpusdev.lingsync.org"],
    userFriendlyServerName: "LingSync Beta"
  }),
  lingsync: new Connection({
    protocol: "https://",
    domain: "corpus.lingsync.org",
    port: "443",
    dbname: "default",
    path: "",
    serverLabel: "production",
    brandLowerCase: "lingsync",
    authUrls: ["https://auth.lingsync.org"],
    websiteUrls: ["http://lingsync.org"],
    corpusUrls: ["https://corpus.lingsync.org"],
    userFriendlyServerName: "LingSync.org"
  }),
  mcgill: new Connection({
    protocol: "https://",
    domain: "corpus.lingsync.org",
    port: "443",
    dbname: "default",
    path: "",
    serverLabel: "mcgill",
    authUrls: ["https://auth.lingsync.org"],
    websiteUrls: ["http://lingsync.org"],
    corpusUrls: ["https://corpus.lingsync.org"],
    userFriendlyServerName: "McGill ProsodyLab"
  }),
  concordia: new Connection({
    protocol: "https://",
    domain: "corpus.lingsync.org",
    port: "443",
    dbname: "default",
    path: "",
    serverLabel: "concordia",
    authUrls: ["https://auth.lingsync.org"],
    websiteUrls: ["http://lingsync.org"],
    corpusUrls: ["https://corpus.lingsync.org"],
    userFriendlyServerName: "Concordia Linguistics"
  })
};
Connection.knownConnections.production = Connection.knownConnections.lingsync;
Connection.knownConnections.development = Connection.knownConnections.beta;
// Connection.knownConnections.test = Connection.knownConnections.beta;
 
/**
 * Set otherwise to be the default connection of this app.
 *
 * By Default, apps will try to contact NODE_ENV,
 * if in a browser they will try to contact beta unless you specify Connection.otherwise
 */
Connection.otherwise = null;
 
Connection.defaultConnection = function(optionalHREF, passAsReference) {
  /*
   * If its a couch app, it can only contact databases on its same origin, so
   * modify the domain to be that origin. the chrome extension can contact any
   * authorized server that is authorized in the chrome app's manifest
   */
  var connection;
  var otherwise;
  try {
    otherwise = process.env.NODE_ENV;
  } catch (e) {}
  if (!otherwise) {
    try {
      otherwise = localStorage.getItem("serverLabel");
    } catch (e) {
      // not running in node nor normal browser environment.
    }
  }
 
  if (FieldDBObject.application && FieldDBObject.application.serverLabel) {
    otherwise = FieldDBObject.application.serverLabel;
  }
 
  otherwise = otherwise || Connection.otherwise || "beta";
  if (!Connection.knownConnections[otherwise]) {
    FieldDBObject.bug("I dont know how to connect to " + otherwise + " please report this.");
    throw new Error("I dont know how to connect to " + otherwise + " please report this.");
  }
 
  /* Ensuring at least the localhost connection is known */
  Iif (!Connection.knownConnections) {
    Connection.knownConnections = {};
  }
  Iif (!Connection.knownConnections.localhost) {
    Connection.knownConnections.localhost = new Connection({
      protocol: "https://",
      domain: "localhost",
      port: "6984",
      dbname: "default",
      path: "",
      serverLabel: "localhost",
      brandLowerCase: "localhost",
      authUrls: ["https://localhost:3183"],
      corpusUrls: ["https://localhost:6984"],
      userFriendlyServerName: "Localhost"
    });
  }
  Iif (!optionalHREF && FieldDBObject.application && FieldDBObject.application.connection) {
    connection = FieldDBObject.application.connection;
    optionalHREF = connection.serverLabel;
  }
 
  if (!optionalHREF) {
    try {
      if (window && window.location) {
        optionalHREF = window.location.href;
      } else {
        connection = Connection.knownConnections[otherwise];
        optionalHREF = connection.authUrls[0];
      }
    } catch (e) {
      connection = Connection.knownConnections[otherwise];
      // if they specified an otherwise that doesnt exist correct it
      // to use beta
      Iif (!connection) {
        FieldDBObject.bug("I dont know how to connect to " + otherwise + " please report this.");
        throw new Error("I dont know how to connect to " + otherwise + " please report this.");
      }
      optionalHREF = connection.authUrls[0];
    }
  }
 
  if (Connection.knownConnections[optionalHREF]) {
    connection = Connection.knownConnections[optionalHREF];
  } else Iif (optionalHREF.indexOf("_design/") > -1) {
    if (optionalHREF.indexOf("corpusdev.lingsync.org") >= 0) {
      connection = Connection.knownConnections.beta;
    } else if (optionalHREF.indexOf("lingsync.org") >= 0) {
      connection = Connection.knownConnections.production;
    } else if (optionalHREF.indexOf("prosody.linguistics.mcgill") >= 0) {
      connection = Connection.knownConnections.mcgill;
    } else if (optionalHREF.indexOf("localhost") >= 0) {
      connection = Connection.knownConnections.localhost;
    }
  } else {
    Iif (optionalHREF.indexOf("jlbnogfhkigoniojfngfcglhphldldgi") >= 0) {
      connection = Connection.knownConnections.mcgill;
    } else Iif (optionalHREF === "LingSync Beta") {
      connection = Connection.knownConnections.beta;
    } else Iif (optionalHREF === "LingSync Testing") {
      connection = Connection.knownConnections.beta;
    } else Iif (optionalHREF === "LingSync") {
      connection = Connection.knownConnections.production;
    } else if (optionalHREF === "Localhost") {
      connection = Connection.knownConnections.localhost;
    } else if (optionalHREF === "McGill ProsodyLab") {
      connection = Connection.knownConnections.mcgill;
    } else Iif (optionalHREF === "Concordia") {
      connection = Connection.knownConnections.concordia;
    } else if (optionalHREF.indexOf("eeipnabdeimobhlkfaiohienhibfcfpa") >= 0) {
      connection = Connection.knownConnections.beta;
    } else if (optionalHREF.indexOf("ocmdknddgpmjngkhcbcofoogkommjfoj") >= 0) {
      connection = Connection.knownConnections.production;
    } else if (optionalHREF.indexOf("dev.lingsync.org") >= 0) {
      connection = Connection.knownConnections.beta;
    } else if (optionalHREF.indexOf("lingsync.org") >= 0) {
      connection = Connection.knownConnections.production;
    } else Iif (optionalHREF.indexOf("prosody.linguistics.mcgill") >= 0) {
      connection = Connection.knownConnections.mcgill;
    } else Iif (optionalHREF.indexOf("linguistics.concordia") >= 0) {
      connection = Connection.knownConnections.concordia;
    } else Iif (optionalHREF.indexOf("lingsync") >= 0) {
      connection = Connection.knownConnections.production;
    } else if (optionalHREF.indexOf("localhost") >= 0) {
      connection = Connection.knownConnections.localhost;
    } else if (optionalHREF.indexOf("chrome-extension") === 0) {
      connection = Connection.knownConnections[otherwise];
    } else if (optionalHREF.indexOf("file") === 0) {
      connection = Connection.knownConnections[otherwise];
    }
  }
 
  if (!connection) {
    console.warn("The user is trying to use a server which is unknown to the system. Attempting to construct its connection. ", optionalHREF);
    var connectionUrlObject;
    try {
      Iif (!Connection.URLParser) {
        Connection.URLParser = URL;
      }
    } catch (e) {
      console.log("Cant figure out what the URL parser is");
      Connection.URLParser = {
        parse: function(url) {
          console.warn("Not parsing this url", url);
          return {};
        }
      };
    }
    try {
      connectionUrlObject = new Connection.URLParser(optionalHREF);
    } catch (e) {
      Eif (e.message.indexOf("Invalid URL") === -1) {
        connectionUrlObject = Connection.URLParser.parse(optionalHREF);
      }
      // console.log("Cant use new Connection.URLParser() in this environment.", connectionUrlObject);
    }
    if (!connectionUrlObject || !connectionUrlObject.hostname) {
      console.warn("There was no way to deduce the HREF, probably we are in Node or loading from a file://. Using " + otherwise + " instead. ", optionalHREF);
      connection = Connection.knownConnections[otherwise];
    } else {
      var domainName = connectionUrlObject.hostname.split(".");
      while (domainName.length > 2) {
        domainName.shift();
      }
      domainName = domainName.join(".");
      connection = new Connection({
        protocol: connectionUrlObject.protocol + "//",
        domain: connectionUrlObject.hostname,
        port: connectionUrlObject.port,
        dbname: "default",
        path: connectionUrlObject.pathname.replace("/", ""),
        serverLabel: domainName.substring(0, domainName.lastIndexOf(".")),
        brandLowerCase: domainName.substring(0, domainName.lastIndexOf(".")),
        authUrls: [optionalHREF],
        userFriendlyServerName: domainName
      });
      Connection.knownConnections[connection.serverLabel] = connection;
    }
  }
  if (!passAsReference) {
    // console.log("connection is", connection);
    return connection.clone();
  }
  return connection;
};
 
/**
 * Ensures that dbnames can be used inside of corpus identifiers, which are couchdb database names.
 *
 * @param  {string} originalIdentifier the desired dbname or username
 * @return {object}                  the resulting dbname or username, the original dbname, and the changes that were applied.
 */
Connection.validateIdentifier = function(originalIdentifier, username) {
  if (!originalIdentifier) {
    return {
      changes: ["Identifier was empty"],
      equivalent: function() {
        return false;
      }
    };
  }
  var identifier = originalIdentifier.toString();
  var changes = [];
  if (identifier.toLowerCase() !== identifier) {
    changes.push("The identifier has to be lowercase so that it can be used in your CouchDB database names.");
    identifier = identifier.toLowerCase();
  }
 
  if (identifier.split("-").length > 1) {
    if (username) {
      identifier = identifier.replace(/-/g, "");
      changes.push("We are using - as a reserved symbol in database URIs (Uniform Resource Identifiers), so you can't use it in your username.");
    } else {
      // permit the all - which might be in the username or the database
      // identifier = identifier.replace("-", ":::").replace(/-/g, "_").replace(":::", "-");
    }
  }
 
  if (Diacritics.remove(identifier) !== identifier) {
    changes.push("You have to use ascii characters in your identifiers because your identifier is used in your in web urls, so its better if you can use something more web friendly.");
    identifier = Diacritics.remove(identifier);
  }
 
  if (identifier.replace(/[^a-z0-9_-]/g, "_") !== identifier) {
    changes.push("You have some characters which web servers wouldn't trust in your identifier.");
    if (username) {
      identifier = identifier.replace(/[^a-z0-9_-]/g, "");
    } else {
      identifier = identifier.replace(/[^a-z0-9_-]/g, "_");
    }
  }
 
  Iif (identifier.length < 2) {
    changes.push("Your identifier is really too short.");
  }
 
  if (changes.length > 0) {
    changes.unshift("You asked to use " + originalIdentifier + " but we would reccomend using this instead: " + identifier + " the following are a list of reason's why.");
  }
 
  return {
    identifier: identifier,
    original: originalIdentifier,
    changes: changes,
    equivalent: function() {
      if (this.original && typeof this.original.toLowerCase === "function") {
        return this.original.toLowerCase() === this.identifier;
      }
    }
  };
};
 
Connection.validateUsername = function(originalIdentifier) {
  return Connection.validateIdentifier(originalIdentifier, "username");
};
 
Connection.cleanCorpusUrls = function(corpusUrls) {
  // console.log("cleaning cleanCorpusUrls of all default urls", corpusUrls);
  if (!corpusUrls || !corpusUrls.length) {
    return corpusUrls;
  }
  var defaultUrls = [];
  for (var connection in Connection.knownConnections) {
    Iif (!Connection.knownConnections.hasOwnProperty(connection)) {
      continue;
    }
    defaultUrls = defaultUrls.concat(Connection.knownConnections[connection].corpusUrls);
    // console.log("defaultUrls", defaultUrls);
  }
  while (corpusUrls.length && defaultUrls.indexOf(corpusUrls[0]) > -1) {
    // console.log("shifting empty", corpusUrls[0]);
    corpusUrls.shift();
  }
  return corpusUrls;
};
 
/**
 * This is the base schema of a corpus connection, other fields may be added.
 * This schema is used by the API docs, it should be updated as the above newConnection changes.
 *
 * @type {Object}
 */
Connection.baseSchema = {
  "id": "Connection",
  "properties": {
    "corpusid": {
      "type": "string"
    },
    "dbname": {
      "type": "string"
    },
    "pouchname": {
      "type": "string"
    },
    "protocol": {
      "type": "string"
    },
    "domain": {
      "type": "string"
    },
    "port": {
      "type": "string"
    },
    "path": {
      "type": "string"
    },
    "authUrl": {
      "items": {
        "$ref": "string"
      },
      "type": "Array"
    },
    "clientUrls": {
      "items": {
        "$ref": "ClientApp"
      },
      "type": "Array"
    },
    "corpusUrls": {
      "items": {
        "$ref": "string"
      },
      "type": "Array"
    },
    "lexiconUrls": {
      "items": {
        "$ref": "string"
      },
      "type": "Array"
    },
    "searchUrls": {
      "items": {
        "$ref": "string"
      },
      "type": "Array"
    },
    "audioUrls": {
      "items": {
        "$ref": "string"
      },
      "type": "Array"
    }
  }
};
 
exports.Connection = Connection;