[
  {
    "path": ".gitignore",
    "content": ".build*\n.npm\nsampleApp/packages\nsmart.lock\nnpm-debug.log\n"
  },
  {
    "path": ".gitmodules",
    "content": "[submodule \"resumable\"]\n\tpath = resumable\n\turl = https://github.com/23/resumable.js.git\n"
  },
  {
    "path": ".travis.yml",
    "content": "language: node_js\nnode_js:\n  - \"6.9.1\"\n\nbefore_install:\n  - \"curl https://install.meteor.com | /bin/sh\"\n  - \"npm install -g coffee-script\"\n  - \"npm install -g spacejam\"\n  # - \"export PHANTOMJS_CDNURL=http://cnpmjs.org/downloads\"\n  # - \"npm install -g phantomjs-prebuilt\"\n  - \"export PATH=$PATH:$HOME/.meteor\"\n\nscript: \"spacejam test-packages ./\"\n"
  },
  {
    "path": ".versions",
    "content": "allow-deny@1.0.5\nbabel-compiler@6.14.1\nbabel-runtime@1.0.1\nbase64@1.0.10\nbinary-heap@1.0.10\nblaze@2.1.8\nblaze-tools@1.0.9\nboilerplate-generator@1.0.11\ncaching-compiler@1.1.9\ncallback-hook@1.0.10\ncheck@1.2.5\ncoffeescript@1.12.3_1\nddp@1.2.5\nddp-client@1.3.3\nddp-common@1.2.8\nddp-server@1.3.13\ndeps@1.0.12\ndiff-sequence@1.0.7\necmascript@0.6.3\necmascript-runtime@0.3.15\nejson@1.0.13\ngeojson-utils@1.0.10\nhtml-tools@1.0.10\nhtmljs@1.0.10\nhttp@1.2.11\nid-map@1.0.9\njquery@1.11.10\nlocal-test:vsivsi:file-collection@1.3.8\nlogging@1.1.17\nmeteor@1.6.1\nminimongo@1.0.20\nmodules@0.7.9\nmodules-runtime@0.7.9\nmongo@1.1.15\nmongo-id@1.0.6\nnpm-mongo@2.2.16_1\nobserve-sequence@1.0.15\nordered-dict@1.0.9\npromise@0.8.8\nrandom@1.0.10\nreactive-var@1.0.11\nretry@1.0.9\nroutepolicy@1.0.12\nspacebars@1.0.12\nspacebars-compiler@1.0.12\ntest-helpers@1.0.11\ntinytest@1.0.12\ntracker@1.1.2\nui@1.0.11\nunderscore@1.0.10\nurl@1.1.0\nvsivsi:file-collection@1.3.8\nwebapp@1.3.13\nwebapp-hashing@1.0.9\n"
  },
  {
    "path": "HISTORY.md",
    "content": "## Revision history\n\n### V.NEXT\n\n* Improvements in the Cordova documentation. Thanks @rsmelo92.\n\n### V1.3.8\n\n* Added check to guard against catastrophic remote file deletion triggered by [this Meteor bug](https://github.com/vsivsi/meteor-file-collection/issues/152).\n* Updated resumable.js to latest upstream version\n* Removed jquery Atmosphere package as a dependency, as resumable.js no longer requires it.\n* Documentation improvements\n\n### V1.3.7\n\n* Fixed server internal error when an HTTP requests matches the file-collection `baseURL` but does not match any of the defined HTTP interface definition paths. Also added unit test for this case. Thanks to @nathanbrizzee for reporting.\n* Fixed (via gridfs-locking-stream npm package) an event memory leak when renewing locks on open files.\n* Updated resumable.js to latest upstream version\n* Updated npm and atmosphere dependencies for Meteor 1.4.2.3\n\n### V1.3.6\n\n* Fixed absolute URL for Cordova downloads. (thanks @crapthings)\n* Updated npm and atmosphere dependencies for Meteor 1.3.4.4\n\n### V1.3.5\n\n* Added GET support for `Last-Modified-Since` HTTP header (thanks @edemaine)\n* Fixed broken server tests when run on Windows (thanks @edemaine)\n* Added `selector` parameter type check on function overriding default `remove` method (thanks @brucejo75)\n* Updated Meteor package deps to 1.3.2.x versions\n* Documentation updates for CORS, and cookie handling in sample code.\n\n### V1.3.4\n\n* Added `withCredentials: true` to the default Resumable object parameters to allow authentication with CORS\n* Changed precedence of developer provided HTTP request handlers to come before default resumable.js route handlers, to permit adding headers to responses on that route.\n* Updated resumable.js to latest `master`\n* Updated npm dependencies.\n\n### V1.3.3\n\n* Use the internal MongoDB 2.1.x driver to create the indexes, not the Meteor provided 1.4.x driver, which is incompatible with MongoDB 3.2. Thanks to @snajjar for reporting.\n* Updated package dependencies.\n\n### v1.3.2\n\n* Fixed bug when no HTTP options array is provided and resumable.js isn't used. Thanks to @ndarilek the PR.\n* Updated npm dependencies.\n* Documentation improvements.\n\n### v1.3.1\n\n* Fixed bugs affecting the built-in resumable.js support when application specified GET/POST routes also matched `/_resumable`. Fixes ensure that multipart parsing for POST requests only happens once, and that `_resumable` routes are fully handled before invoking application route handlers. Thanks to @lightpriest and @mzygmunt for reporting.\n\n### v1.3.0\n\n* Added ability to define custom HTTP OPTIONS request handlers, e.g. to support CORS\n* The above feature can be used to add support for files in Apache Cordova apps. Thanks to @dnish for initial work on this.\n* `maxUploadSize` option enables a configurable maximum file size for POST, PUT and resumable.js uploads. Thanks to @DanielDornhardt for this feature suggestion.\n* Fixed improper ObjectID type in callback from `fc.upsertStream()`. Thanks @DrDanRyan for reporting.\n* Updated to MongoDB 2.1.x driver\n* Updated npm dependencies\n* Added TravisCI support\n\n### v1.2.2\n\n* Fixed an uncaught throw in `importFile()` when the input file doesn't exist, thanks to @dpatte\n* Updated resumable.js to latest master\n* Updated dependencies\n* Documentation improvements\n* Fixed bug causing resumable HEAD requests to always return 404, even when a chunk was present in the gridFS store. Thanks to @dnish for help figuring this out.\n* Fixed bug causing resumable GET requests to always return 204, even when a chunk was present in the gridFS store.\n* Added unit tests for resumable.js GET/HEAD test request backend support\n* Don't create unused readable streams for HTTP HEAD requests.\n* Unit tests fixed for Meteor 1.2.x by adding many missing meteor packages to test build.\n\n### v1.2.1\n\n* This version number was accidentally skipped over, so there was no v1.2.1 release.\n\n### v1.2.0\n\n* Add the ability to perform limited local updates to the client minimongo collection using `fc.localUpdate()`\n* Thanks to @Digital-Thor for his work on integrating [Sortable](https://github.com/RubaXa/Sortable/tree/master/meteor) and file-collection, demonstrating the usefulness of supporting local client-side update\n* Fixed bug permitting `update` replacement of entire gridFS documents\n* Added update related unit tests\n* Defend against `Mongo.Collection !== Mongo.Collection.protype.constructor`\n* Updated npm dependencies\n* Updated resumable.js\n* Switch to using HEAD requests for resumable.js chunk test requests\n* Use `Meteor.Error` consistently\n\n### v1.1.5\n\n* Fixed issues related to lock timeouts and proper return values from `fc.remove()`\n* Thanks to @timothyarmes for reporting these issues [issue 59](https://github.com/vsivsi/meteor-file-collection/issues/59)\n* Added unit test coverage for basic `remove` functionality\n* Documentation improvements\n* Bumped npm dependencies\n* Updated resumable.js to upstream master\n\n### v1.1.4\n\n* Resolving architecture specific build issues with newest mongodb driver\n\n### v1.1.3\n\n* Updated resumable.js and npm dependencies\n\n### v1.1.2\n\n* Checked in the `.versions` file\n* Updated project directory structure, adding `src` and `test` subdirs.\n* Updated npm dependencies.\n* Documentation improvements.\n\n### v1.1.1\n\n* Added informative `throw` when server-only methods are erroneously called on the client\n* Moved to current resumable.js master\n* Bumped npm dependencies to latest versions\n* Added explicit package version to `onTest()` call to work around a Meteor issue when running `meteor test-packages` within an app.\n* Added ablity to set the resumable.js server side support MongoDB index name, via the `resumableIndexName` option to `new FileCollection()`. This fixes problems related to [issue 55](https://github.com/vsivsi/meteor-file-collection/issues/55). Thanks to @poojabansal for reporting.\n\n### v1.1.0\n\n* Changed the resumable.js server-side support to return status 204 for testChunk GET requests, rather than 404, which causes undesirable log entries in the client console.\n* Fixed bug where received duplicate chunks could mistakenly both be written during resumable.js uploads\n* Made POST body MIME/multipart parsing more resistent to malformed requests\n* Added unit tests for resumable client and server-side support\n* Automatic lock renewal support, can be controlled with `autoRenewLock` option on `fc.upsertStream()` and `fc.findOneStream()`\n* `range` option to `fc.findOneStream()` now allows `start` or `end` to be safely omitted.\n* Default `chunkSize` changed to 2MB - 1KB, matching the MongoDB recommendation for chunk sizes a little less than a power of 2.\n* General performance improvements writing data to gridFS\n* Updated mongodb, gridfs-locks and gridfs-locking-stream to newest versions\n\n### v1.0.6\n\n* Fixes #48, which caused unicode filenames to be corrupted in download SaveAs... dialogs. Thanks to @xurwxj for reporting.\n* Bump versions of dependencies\n\n### v1.0.5\n\n* Version bump to enable publishing Windows platform build for Meteor 1.1\n\n### v1.0.4\n\n* Updated npm package dependencies\n\n### v1.0.3\n\n* Add automatic indexing for resumable.js queries, to improve uploading performance\n* Bumped version of mongodb native driver\n\n### v1.0.2\n\n* Fixes failed unit test caused by null $set update query when using Meteor 1.0.4\n* Update version of resumable.js\n* Update mongodb npm package version\n* Update meteor core package versions\n\n### v1.0.1\n\n* Fixes potential race condition in the underlying gridfs-locks package\n* Updates npm package versions\n\n### v1.0.0\n\n* Added support for HTTP range requests (thanks to @riaan53!)\n* Switched internally to using new style node.js streams for greatly improved flow-control when streaming large files\n* HTTP access definitions may now include an optional custom express.js request handler function\n* HTTP access file lookup functions may now access parsed MIME/multipart parameters for POST requests\n* Updated all dependencies\n* *BREAKING CHANGE:* `fc.upsertStream` may no longer append (mode 'w+') to existing files. This is a restriction added to the underlying node.js gridFS driver, and was a little used feature that was traded-off for node.js 0.10 new stream support\n\n### v0.3.6\n\n* Updated dependencies including resumable.js\n\n### v0.3.5\n\n* Rebuilt/published previous version using actual Meteor 1.0 instead of a checkout of Meteor 1.0\n\n### v0.3.4\n\n* Documentation improvements\n* Dependent package version updates\n\n### v0.3.3\n\n* Added a polyfill for `Function.prototype.bind()` to enable compatibility with PhantomJS, which as of version 1.9.7 lacks support for `.bind()`\n* Bumped mongodb npm package version.\n\n### v0.3.2\n\n* Bumped versions of npm dependencies, including a fix for a bson build error in the npm mongodb driver.\n\n### v0.3.1\n\n* Bumped versions of npm dependencies, including a fix for a rare gridfs file locking bug.\n* Documentation fixes.\n\n### v0.3.0\n\n* Updated package name and information to conform with Meteor 0.9.0 package system. Thanks to @ryw for a PR that showed what needed to be done.\n* Added versions.json file\n* Documentation updates\n* Added additional error checking when receiving a 'close' event.\n* Don't automatically index the fileCollection.\n* Updated express and mopngodb packages to latest versions\n* All features deprecated in v0.2.0 are obsolete and removed\n\n### v0.2.3\n\n* Added additional checking that `_id` values in URLs are 24-digit hex strings before attempting to make them into ObjectIds\n* Bumped express.js to latest version\n\n### v0.2.2\n\n* Fixed #15\n* Updated README for new sample apps.\n* Updated Resumable.js\n\n### v0.2.1\n\n* Added sanity checking of input to `fc.allow()` and `fc.deny()`\n* Allow options to be truly optional w/ callback in `findOneStream()` and `upsertStream()`\n* Fixed reversed/broken sort/skip options on `findOneStream()`\n* Fixed an issue where `ObjectID`s in file metadata change type after `upsertStream()`\n* Updated resumable.js\n* Documentation improvements.\n\n### v0.2.0\n\n* `fc.allow` and `fc.deny` now support rules for the `'read'` operation, which secures HTTP GET/HEAD requests.\n* `fc.allow` and `fc.deny` now support rules for the `'write'` operation, which impacts HTTP POST/PUT requests. `'write'` allow/deny rules are replacing the use of `'update'` rules, and work identically. The reason for the change is to avoid confusion with the `'update'` rules on Meteor collections and to better match the new `'read'` rules. `'update'` rules continue to work, but are now deprecated.\n* HTTP GET requests now support the `?filename=somename.txt` query. This is similar to the `?download=true` option, except that the default filename used by the browser \"Save As...\" dialog is specified by the request URL.\n* Added support for sending X-Auth-Token as an HTTP Cookie. This is safer than using the `?X-Auth-Token` URL query, which continues to work, but is now deprecated.\n* When using the built-in Resumable.js upload support, if you create `'write'` allow/deny rules that depend on `userId` you must set an `X-Auth-Token` cookie. See the client [example code in README.md](https://github.com/vsivsi/meteor-file-collection#example) for an example of how to do this.\n* Acceptance tests are now written in Coffeescript.\n* Version updates for most Npm packages.\n* Documentation improvements.\n* The sample application has been moved to its own [GitHub repo](https://github.com/vsivsi/meteor-file-job-sample-app).\n* Thanks to @elbowz for multiple feature suggestions.\n\n### v0.1.18\n\n* Allow/Deny rules are now called in the same order as in Meteor (deny rules go first).\n\n### v0.1.17\n\n* Fixed another issue when calling deprecated fileCollection object without new.\n\n### v0.1.16\n\n* Fixed issue when calling deprecated fileCollection object without new.\n\n### v0.1.15\n\n* Added FileCollection export\n* Updated docs to use FileCollection and note that fileCollection is deprecated and will be removed in 0.2.0\n* Added deprecation warning to console.warn for fileCollection use\n* Bumped express version\n\n### v0.1.14\n\n* Improved documentation. Thanks to @renarl for suggestion.\n* Updated express version.\n\n### v0.1.13\n\n* Updated versions of resumable, async, mongodb, gridfs-locks, gridfs-locking-stream and express\n* Documentation improvements\n\n### v0.1.12\n\n* Fixed typos in documentation. Thanks to @dawjdh\n\n### v0.1.11\n\n* Fixed sample code in README.md. Thanks to @rcy\n\n### v0.1.10\n\n* Fixed resumable.js upload crash\n\n### v0.1.9\n\n* Fix missing filenames in resumable.js uploads caused by changes in mongodb 1.4.3\n* upsertStream now correctly updates gridFS attributes when provided\n\n### v0.1.8\n\n* Updates for Meteor v0.8.1.1\n* Documentation improvements\n* Updated npm package versions\n\n### v0.1.7\n\n* Bumped package versions to fix more mongodb 2.4.x backwards compatility issues\n\n### v0.1.6\n\n* Bumped gridfs-locks version to fix a mongodb 2.4.x backwards compatility issue\n\n### v0.1.0 - v0.1.5\n\n* Initial revision and documentation improvements.\n"
  },
  {
    "path": "LICENSE",
    "content": "Copyright (C) 2014-2017 by Vaughn Iverson\n\nfile-collection is free software released under the MIT/X11 license:\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# file-collection\n\n[![Build Status](https://travis-ci.org/vsivsi/meteor-file-collection.svg)](https://travis-ci.org/vsivsi/meteor-file-collection)\n\n## Notice!\n\n#### **Effective 01-01-2018 this project will enter \"maintenance mode\". This means that I will no longer be implementing any new features or providing debugging help or \"general support\" via github issues.**\n\n**I will (for some period of time) still consider *high quality* pull-requests implementing bug fixes and generally useful new minor features. (\"High quality\" is admittedly subjective, but some must-haves: documentation, tests, backward compatibility, low change complexity, harmony with existing design...)**\n\n**If you would like to become a maintainer, Great!. The best way to get there is to make some high quality PRs! Eventually I will probably get tired of merging them and will just give you permission to push and publish.\nIf there is enough community interest, I will probably migrate all of my Meteor packages into a separate github org so that they can live on without my direct involvement.**\n\n**Why? Simple: I'm no longer actively developing or maintaining any Meteor based applications (and have no forseeable plans to do so). Having moved on, the effort to keep up with changes in the Meteor/Atmosphere ecosystem no longer has any payoff for me personally.**\n\n## Introduction\n\nfile-collection is a Meteor.js package that cleanly extends Meteor's Collection metaphor to efficiently manage collections of files and their data. File Collections are fully reactive, and if you know how to use Meteor Collections, you already know most of what you need to begin working with this package.\n\nMajor features:\n\n* HTTP upload and download including support for Meteor authentication\n* Client and Server integration of [resumable.js](http://resumablejs.com/) for robust chunked uploading\n* Also compatible with traditional HTTP POST or PUT file uploading\n* HTTP range requests support random access for resumable downloads, media seeking, etc.\n* Robust file locking allows safe replacement and removal of files even on a busy server\n* External changes to the underlying file store automatically synchronize with the Meteor collection\n* Designed for efficient handling of millions of small files as well as huge files 10GB and above\n\nThese features (and more) are possible because file-collection tightly integrates MongoDB [gridFS](http://docs.mongodb.org/manual/reference/gridfs/) with Meteor Collections, without any intervening plumbing or unnecessary layers of abstraction.\n\n#### Quick server-side example\n\n```javascript\nmyFiles = new FileCollection('myFiles',\n  { resumable: true,    // Enable built-in resumable.js chunked upload support\n    http: [             // Define HTTP route\n      { method: 'get',  // Enable a GET endpoint\n        path: '/:md5',  // this will be at route \"/gridfs/myFiles/:md5\"\n        lookup: function (params, query) {  // uses express style url params\n          return { md5: params.md5 };       // a query mapping url to myFiles\n}}]});\n\n// You can add publications and allow/deny rules here to securely\n// access myFiles from clients.\n// On the server, you can access everything without limitation:\n\n// Find a file document by name\nthatFile = myFiles.findOne({ filename: 'lolcat.gif' });\n\n// or get a file's data as a node.js Stream2\nthatFileStream = myFiles.findOneStream({ filename: 'lolcat.gif' });\n\n// Easily remove a file and its data\nresult = myFiles.remove(thatFile._id);\n```\n\n### Feature summary\n\nUnder the hood, file data is stored entirely within the Meteor MongoDB instance using a Mongo technology called [gridFS](http://docs.mongodb.org/manual/reference/gridfs/). Your file collection and the underlying gridFS collection remain perfectly in sync because they *are* the same collection; and file collections are automatically safe for concurrent read/write access to files via [MongoDB based locking](https://github.com/vsivsi/gridfs-locks). The file-collection package also provides a simple way to enable secure HTTP (GET, POST, PUT, DELETE) interfaces to your files, and additionally has built-in support for robust and resumable file uploads using the excellent [Resumable.js](http://www.resumablejs.com/) library.\n\n### What's new in v1.3?\n\n*   CORS/Cordova support via the ability to define custom HTTP OPTIONS request handlers\n*   Global and per-request file upload size limits via the new `maxUploadSize` option\n\nAdditional changes are detailed in the HISTORY file.\n\n### Design philosophy\n\n**Update: CollectionFS appears to no longer be actively maintained, so caveat emptor.**\n\nMy goal in writing this package was to stay true to the spirit of Meteor and build something efficient and secure that \"just works\" with a minimum of fuss.\n\nIf you've been searching for ways to deal with file data on Meteor, you've probably also encountered [collectionFS](https://atmospherejs.com/cfs/standard-packages). If not, you should definitely check it out. It's a great set of packages written by smart people, and I even pitched in to help with a rewrite of their MongoDB gridFS support.\n\nHere's the difference in a nutshell: collectionFS is a Ferrari, and file-collection is a Fiat.\n\nThey do approximately the same thing using some of the same technologies, but reflect different design priorities. file-collection is much simpler and somewhat less flexible; but if it meets your needs you'll find it has a lot fewer moving parts and may be significantly more efficient to work with and use.\n\nIf you're trying to quickly prototype an idea or you know that you just need a straightforward way of dealing with files, you should definitely try file-collection. Because it is so much simpler, you may also find that it is easier to understand and customize for the specific needs of your project.\n\n## Example\n\nEnough words, time for some more code...\n\nThe block below implements a `FileCollection` on server, including support for owner-secured HTTP file upload using `Resumable.js` and HTTP download. It also sets up the client to provide drag and drop chunked file uploads to the collection. The only things missing here are UI templates and some helper functions. See the [meteor-file-sample-app](https://github.com/vsivsi/meteor-file-sample-app) project for a complete working version written in [CoffeeScript](http://coffeescript.org/).\n\n```javascript\n// Create a file collection, and enable file upload and download using HTTP\nmyFiles = new FileCollection('myFiles',\n  { resumable: true,   // Enable built-in resumable.js upload support\n    http: [\n      { method: 'get',\n        path: '/:md5',  // this will be at route \"/gridfs/myFiles/:md5\"\n        lookup: function (params, query) {  // uses express style url params\n          return { md5: params.md5 };       // a query mapping url to myFiles\n        }\n      }\n    ]\n  }\n);\n\nif (Meteor.isServer) {\n\n  // Only publish files owned by this userId, and ignore\n  // file chunks being used by Resumable.js for current uploads\n  Meteor.publish('myData',\n    function (clientUserId) {\n      if (clientUserId === this.userId) {\n        return myFiles.find({ 'metadata._Resumable': { $exists: false },\n                              'metadata.owner': this.userId });\n      } else {        // Prevent client race condition:\n        return null;  // This is triggered when publish is rerun with a new\n                      // userId before client has resubscribed with that userId\n      }\n    }\n  );\n\n  // Allow rules for security. Should look familiar!\n  // Without these, no file writes would be allowed\n  myFiles.allow({\n    // The creator of a file owns it. UserId may be null.\n    insert: function (userId, file) {\n      // Assign the proper owner when a file is created\n      file.metadata = file.metadata || {};\n      file.metadata.owner = userId;\n      return true;\n    },\n    // Only owners can remove a file\n    remove: function (userId, file) {\n      // Only owners can delete\n      return (userId === file.metadata.owner);\n    },\n    // Only owners can retrieve a file via HTTP GET\n    read: function (userId, file) {\n      return (userId === file.metadata.owner);\n    },\n    // This rule secures the HTTP REST interfaces' PUT/POST\n    // Necessary to support Resumable.js\n    write: function (userId, file, fields) {\n      // Only owners can upload file data\n      return (userId === file.metadata.owner);\n    }\n  });\n}\n\nif (Meteor.isClient) {\n\n  Meteor.startup(function() {\n\n    // This assigns a file upload drop zone to some DOM node\n    myFiles.resumable.assignDrop($(\".fileDrop\"));\n\n    // This assigns a browse action to a DOM node\n    myFiles.resumable.assignBrowse($(\".fileBrowse\"));\n\n    // When a file is added via drag and drop\n    myFiles.resumable.on('fileAdded', function (file) {\n\n      // Create a new file in the file collection to upload\n      myFiles.insert({\n        _id: file.uniqueIdentifier,  // This is the ID resumable will use\n        filename: file.fileName,\n        contentType: file.file.type\n        },\n        function (err, _id) {  // Callback to .insert\n          if (err) { return console.error(\"File creation failed!\", err); }\n          // Once the file exists on the server, start uploading\n          myFiles.resumable.upload();\n        }\n      );\n    });\n\n    // This autorun keeps a cookie up-to-date with the Meteor Auth token\n    // of the logged-in user. This is needed so that the read/write allow\n    // rules on the server can verify the userId of each HTTP request.\n    Deps.autorun(function () {\n      // Sending userId prevents a race condition\n      Meteor.subscribe('myData', Meteor.userId());\n      // $.cookie() assumes use of \"jquery-cookie\" Atmosphere package.\n      // You can use any other cookie package you may prefer...\n      $.cookie('X-Auth-Token', Accounts._storedLoginToken(), { path: '/' });\n    });\n  });\n}\n```\n\n## Installation\n\nI've only tested with Meteor v0.9.x and v1.x.x, and older versions run on Meteor v0.8 as well, but why would you want to do that?\n\nTo add to your project, run:\n\n    meteor add vsivsi:file-collection\n\nThe package exposes a global object `FileCollection` on both client and server.\n\nIf you'd like to try out the sample app, you can clone the repo from github:\n\n```\ngit clone https://github.com/vsivsi/meteor-file-sample-app.git fcSample\n```\n\nThen go to the `fcSample` subdirectory and run meteor to launch:\n\n```\ncd fcSample\nmeteor\n```\n\nYou should now be able to point your browser to `http://localhost:3000/` and play with the sample app.\n\nA more advanced example that implements a basic image gallery with upload and download support and automatic thumbnail generation using the [job-collection package](https://atmospherejs.com/vsivsi/job-collection) is available here: https://github.com/vsivsi/meteor-file-job-sample-app\n\nTo run tests (using Meteor tiny-test):\n\n```\ngit clone --recursive https://github.com/vsivsi/meteor-file-collection FileCollection\ncd FileCollection\nmeteor test-packages ./\n```\nLoad `http://localhost:3000/` and the tests should run in your browser and on the server.\n\n## Use\n\nBelow you'll find the [MongoDB gridFS `files` data model](http://docs.mongodb.org/manual/reference/gridfs/#the-files-collection). This is also the schema used by file-collection because a FileCollection *is* a gridFS collection.\n\n```javascript\n{\n  \"_id\" : <ObjectId>,\n  \"length\" : <number>,\n  \"chunkSize\" : <number>\n  \"uploadDate\" : <Date>\n  \"md5\" : <string>\n\n  \"filename\" : <string>,\n  \"contentType\" : <string>,\n  \"aliases\" : <array of strings>,\n  \"metadata\" : <object>\n}\n```\n\nHere are a few things to keep in mind about the gridFS file data model:\n\n*    Some of the attributes belong to gridFS, and you may **lose data** if you mess around with these.\n*    For this reason, `_id`, `length`, `chunkSize`, `uploadDate` and `md5` are read-only.\n*    Some of the attributes belong to you. Your application can do whatever you want with them.\n*    `filename`, `contentType`, `aliases` and `metadata` are yours. Go to town.\n*    `contentType` should probably be a valid [MIME Type](https://en.wikipedia.org/wiki/MIME_type)\n*    `filename` is *not* guaranteed unique. `_id` is a better bet if you want to be sure of what you're getting.\n\nSound complicated? It really isn't and file-collection is here to help.\n\nFirst off, when you create a new file you use `myFiles.insert(...)` and just populate whatever attributes you care about. The file-collection package does the rest. You are guaranteed to get a valid gridFS file, even if you just do this: `id = myFiles.insert();`\n\nLikewise, when you run `myFiles.update(...)` on the server, file-collection tries really hard to make sure that you aren't clobbering one of the \"read-only\" attributes with your update modifier. For safety, clients are never allowed to directly `update`, although you can selectively give them that power via `Meteor.methods()`.\n\n### Limits and performance\n\nThere are essentially no hard limits on the number or size of files other than what your hardware will support.\n\nAt no point in normal operation is a file-sized data buffer ever in memory. All of the file data import/export mechanisms are [stream based](http://nodejs.org/api/stream.html#stream_stream), so even very active servers should not see much memory dedicated to file transfers.\n\nFile data is never copied within a collection. During chunked file uploading, file chunk references are changed, but the data itself is never copied. This makes file-collection particularly efficient when handling multi-gigabyte files.\n\nfile-collection uses robust multiple reader / exclusive writer file locking on top of gridFS, so essentially any number of readers and writers of shared files may peacefully coexist without risk of file corruption. Note that if you have other applications reading/writing directly to a gridFS collection (e.g. a node.js program, not using Meteor/file-collection), it will need to use the [`gridfs-locks`](https://www.npmjs.org/package/gridfs-locks) or [`gridfs-locking-stream`](https://www.npmjs.org/package/gridfs-locking-stream) npm packages to safely inter-operate with file-collection.\n\n### Security\n\nYou may have noticed that the gridFS `files` data model says nothing about file ownership. That's your job. If you look again at the example code block above, you will see a bare bones `Meteor.userId` based ownership scheme implemented with the attribute `file.metadata.owner`. As with any Meteor Collection, allow/deny rules are needed to enforce and defend that document attribute, and file-collection implements that in *almost* the same way that ordinary Meteor Collections do. Here's how they're a little different:\n\n*    A file is always initially created as a valid zero-length gridFS file using `insert` on the client/server. When it takes place on the client, the `insert` allow/deny rules apply.\n*    The `remove` allow/deny rules work just as you would expect for client calls, and they also secure the HTTP DELETE method when it's used.\n*    The `read` allow/deny rules secure access to file data requested via HTTP GET. These rules have no effect on client `find()` or `findOne()` methods; these operations are secured by `Meteor.publish()` as with any meteor collection.\n*    The `write` allow/deny rules secure writing file *data* to a previously inserted file via HTTP methods. This means that an HTTP POST/PUT cannot create a new file by itself. It needs to have been inserted first, and only then can data be added to it using HTTP.\n*    There are no `update` allow/deny rules because clients are always prohibited from directly updating a file document's attributes.\n*    All HTTP methods are disabled by default. When enabled, they can be authenticated to a Meteor `userId` by using a currently valid authentication token passed either in the HTTP request header or using an HTTP Cookie.\n\n## API\n\nThe `FileCollection` API is essentially an extension of the [Meteor Collection API](http://docs.meteor.com/#collections), with almost all of the same methods and a few new file specific ones mixed in.\n\nThe big loser is `upsert()`, it's gone in `FileCollection`. If you try to call it, you'll get an error. `update()` is also disabled on the client side, but it can be safely used on the server to implement `Meteor.Method()` calls for clients to use.\n\n### fc = new FileCollection([name], [options])\n#### Create a new `FileCollection` object - Server and Client\n\n```javascript\n\n// create a new FileCollection with all default values\n\nfc = new FileCollection('fs',  // base name of collection\n  { resumable: false,          // Disable resumable.js upload support\n    resumableIndexName: undefined,    // Not used when resumable is false\n    chunkSize: 2*1024*1024 - 1024,    // Use 2MB chunks for gridFS and resumable\n    baseURL: '\\gridfs\\fs',     // Default base URL for all HTTP methods\n    locks: {                   // Parameters for gridfs-locks\n      timeOut: 360,            // Seconds to wait for an unavailable lock\n      pollingInterval: 5,      // Seconds to wait between lock attempts\n      lockExpiration: 90       // Seconds until a lock expires\n    }\n    http: []    // HTTP method definitions, none by default\n  }\n);\n```\n\n**Note:** The same `FileCollection` call should be made on both the client and server.\n\n`name` is the root name of the underlying MongoDB gridFS collection. If omitted, it defaults to `'fs'`, the default gridFS collection name. Internally, three collections are used for each `FileCollection` instance:\n\n*     `[name].files` - This is the collection you actually see when using file-collection\n*     `[name].chunks` - This collection contains the actual file data chunks. It is managed automatically.\n*     `[name].locks` - This collection is used by `gridfs-locks` to make concurrent reading/writing safe.\n\n`FileCollection` is a subclass of `Meteor.Collection`, however it doesn't support the same `[options]`.\nMeteor Collections support `connection`, `idGeneration` and `transform` options. Currently, file-collection only supports the default Meteor server connection, although this may change in the future. All `_id` values used by `FileCollection` are MongoDB style IDs. The Meteor Collection transform functionality is unsupported in `FileCollection`.\n\nHere are the options `FileCollection` does support:\n\n*    `options.resumable` - `<boolean>`  When `true`, exposes the [Resumable.js API](http://www.resumablejs.com/) on the client and the matching resumable HTTP support on the server.\n*    `options.resumableIndexName` - `<string>`  When provided and `options.resumable` is `true`, this value will be the name of the internal-use MongoDB index that the server-side resumable.js support attempts to create. This is useful because the default index name MongoDB creates is long (94 chars out of a total maximum namespace length of 127 characters), which may create issues when combined with long collection and/or database names. If this collection already exists the first time an application runs using this setting, it will likely have no effect because an identical index will already exist (under a different name), causing MongoDB to ignore request to create a duplicate index with a different name. In this case, you must manually drop the old index and then restart your application to generate a new index with the requested name.\n*    `options.chunkSize` - `<integer>`  Sets the gridFS and Resumable.js chunkSize in bytes. The default value of a little less than 2MB is probably a good compromise for most applications, with the maximum being 8MB - 1. Partial chunks are not padded, so there is no storage space benefit to using small chunk sizes. If you are uploading very large files over a fast network and upload spped matters, then a `chunkSize` of 8MB - 1KB (= 8387584) will likly optimize upload speed. However, if you elect to use such large `chunkSize` values, make sure that the replication oplog of your MongoDB instance is large enough to handle this, or you will risk having your client and server collections lose synchronization during uploads. Meteor's development mode only uses an oplog of 8 MB, which will almost certainly cause problems for high speed uploads to apps using a large `chunkSize`.\nFor more information on Meteor's use of the MongoDB oplog, see: [Meteor livequery](https://www.meteor.com/livequery).\n*    `options.baseURL` - `<string>`  Sets the base route for all HTTP interfaces defined on this collection. Default value is `/gridfs/[name]`\n*    `options.locks` - `<object>`  Locking parameters, the defaults should be fine and you shouldn't need to set this, but see the `gridfs-locks` [`LockCollection` docs](https://github.com/vsivsi/gridfs-locks#lockcollectiondb-options) for more information.\n*    `option.maxUploadSize` - `<integer>`  Maximum number of bytes permitted for any HTTP POST, PUT or resumable.js file upload.\n*    `option.http` - <array of objects>  HTTP interface configuration objects, described below:\n\n#### Configuring HTTP methods\n\nEach object in the `option.http` array defines one HTTP request interface on the server, and has these three attributes:\n\n*    `obj.method` - `<string>`  The HTTP request method to define, one of `get`, `post`, `put`, `delete` (or `options` with a custom handler).\n*    `obj.path` - `<string>`  An [express.js style](http://expressjs.com/4x/api.html#req.params) route path with parameters. This path will be added to the path specified by `options.baseURL`.\n*    `obj.lookup` - `<function>`  A function that is called when an HTTP request matches the `method` and `path`. It is provided with the values of the route parameters and any URL query parameters, and it should return a mongoDB query object which can be used to find a file that matches those parameters. For POST requests, it is also provided any with MIME/multipart parameters and other file information from the multipart headers.\n*    `obj.handler` - `<function>` OPTIONAL! This is an advanced feature that allows the developer to provide a custom \"express.js style\" request handler to satisfy requests for this specific request interface. For an example of how this works, please see the resumable.js upload support implementation in the source file `resumable_server.coffee`.\n\nWhen arranging http interface definition objects in the array provided to `options.http`, be sure to put more specific paths for a given HTTP method before more general ones. For example: `\\hash\\:md5` should come before `\\:filename\\:_id` because `\"hash\"` would match to filename, and so `\\hash\\:md5` would never match if it came second. Obviously this is a contrived example to demonstrate that order is significant.\n\nNote that an authenticated userId is not provided to the `lookup` function. UserId based permissions should be managed using the allow/deny rules described later on.\n\nHere are some example HTTP interface definition objects to get you started:\n\n```javascript\n// GET file data by md5 sum\n{ method: 'get',\n  path:   '/hash/:md5',\n  lookup: function (params, query) {\n              return { md5: params.md5 } } }\n\n// DELETE a file by _id. Note that the URL parameter \":_id\" is a special\n// case, in that it will automatically be converted to a Meteor ObjectID\n// in the passed params object.\n{ method: 'delete',\n  path:   '/:_id',\n  lookup: function (params, query) {\n              return { _id: params._id } } }\n\n// GET a file based on a filename or alias name value\n{ method: 'get',\n  path:   '/name/:name',\n  lookup: function (params, query) {\n    return {$or: [ {filename: params.name },\n                   {aliases: {$in: [ params.name ]}} ]} }}\n\n// PUT data to a file based on _id and a secret value stored as metadata\n// where the secret is supplied as a query parameter e.g. ?secret=sfkljs\n{ method: 'put',\n  path:   '/write/:_id',\n  lookup: function (params, query) {\n    return { _id: params._id, \"metadata.secret\": query.secret} }}\n\n\n// POST data to a file based on _id and a secret value stored as metadata\n// where the secret is supplied as a MIME/Multipart parameter\n{ method: 'post',\n  path:   '/post/:_id',\n  lookup: function (params, query, multipart) {\n    return { _id: params._id, \"metadata.secret\": multipart.params.secret} }}\n\n// GET a file based on a query type and numeric coordinates metadata\n{ method: 'get',\n  path:   '/tile/:z/:x/:y',\n  lookup: function (params, query) {\n    return { \"metadata.x\": parseInt(params.x), // Note that all params\n             \"metadata.y\": parseInt(params.y), // (execept _id) are strings\n             \"metadata.z\": parseInt(params.z),\n             contentType: query.type} }}\n```\n\n#### CORS / Apache Cordova Support\n\nThe HTTP access in file-collection can be configured for compatibility with [Cross Origin Resource Sharing (CORS)](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing) via use of a custom handler for the `'options'`\nrequest method.\n\nThis provides a simple way to support accessing file-collection files in [Apache Cordova](https://github.com/meteor/meteor/wiki/Meteor-Cordova-integration) client applications:\n\n```javascript\nmyFiles = new FileCollection('myFiles',\n  { resumable: true,    // Enable built-in resumable.js chunked upload support\n    http: [             // Define HTTP route\n      { method: 'get',  // Enable a GET endpoint\n        path: '/:md5',  // this will be at route \"/gridfs/myFiles/:md5\"\n        lookup: function (params, query) {  // uses express style url params\n          return { md5: params.md5 };       // a query mapping url to myFiles\n        },\n        handler: function (req, res, next) {\n           if (req.headers && req.headers.origin) {\n             res.setHeader('Access-Control-Allow-Origin', 'http://meteor.local'); // For Cordova\n             res.setHeader('Access-Control-Allow-Credentials', true);\n           }\n           next();\n        }\n      },\n      { method: 'put',  // Enable a PUT endpoint\n        path: '/:md5',  // this will be at route \"/gridfs/myFiles/:md5\"\n        lookup: function (params, query) {  // uses express style url params\n          return { md5: params.md5 };       // a query mapping url to myFiles\n        },\n        handler: function (req, res, next) {\n           if (req.headers && req.headers.origin) {\n             res.setHeader('Access-Control-Allow-Origin', 'http://meteor.local'); // For Cordova\n             res.setHeader('Access-Control-Allow-Credentials', true);\n           }\n           next();\n        }\n      },\n      { method: 'options',  // Enable an OPTIONS endpoint (for CORS)\n        path: '/:md5',  // this will be at route \"/gridfs/myFiles/:md5\"\n        lookup: function (params, query) {  // uses express style url params\n          return { md5: params.md5 };       // a query mapping url to myFiles\n        },\n        handler: function (req, res, next) {  // Custom express.js handler for OPTIONS\n           res.writeHead(200, {\n              'Content-Type': 'text/plain',\n              'Access-Control-Allow-Origin': 'http://meteor.local',  // For Cordova\n              'Access-Control-Allow-Credentials': true,\n              'Access-Control-Allow-Headers': 'x-auth-token, user-agent',\n              'Access-Control-Allow-Methods': 'GET, PUT'\n           });\n           res.end();\n           return;\n        }\n      }\n    ]\n  }\n);\n```\n\nIf using resumable endpoint use this instead:\n\n```javascript\nmyFiles = new FileCollection('myFiles',\n  { resumable: true,    // Enable built-in resumable.js chunked upload support\n    http: [             // Define HTTP route\n      { \n        method: 'POST',  // Enable a POST endpoint\n        path: '/_resumable',  // this will be at route \"/gridfs/images/_resumable\"\n        lookup: function (params, query) {  // uses express style url params\n          return {};       // a dummy query\n        },\n        handler: function (req, res, next) {\n            if (req.headers && req.headers.origin) {\n                res.setHeader('Access-Control-Allow-Origin', req.headers.origin); // For Cordova\n                res.setHeader('Access-Control-Allow-Credentials', true);\n            }\n            next();\n        }\n      },\n      {\n        method: 'head',  // Enable an HEAD endpoint (for CORS)\n        path: '/_resumable',  // this will be at route \"/gridfs/images/_resumable/\"\n        lookup: function (params, query) {  // uses express style url params\n            return { };       // a dummy query\n        },\n        handler: function (req, res, next) {  // Custom express.js handler for HEAD\n           if (req.headers && req.headers.origin) {\n                  res.setHeader('Access-Control-Allow-Origin', req.headers.origin); // For Cordova\n                  res.setHeader('Access-Control-Allow-Credentials', true);\n              }\n            next();\n        }\n      },\n      {\n        method: 'options',  // Enable an OPTIONS endpoint (for CORS)\n        path: '/_resumable',  // this will be at route \"/gridfs/images/_resumable/\"\n        lookup: function (params, query) {  // uses express style url params\n            return { };       // a dummy query\n        },\n        handler: function (req, res, next) {  // Custom express.js handler for OPTIONS\n            res.writeHead(200, {\n                'Content-Type': 'text/plain',\n                'Access-Control-Allow-Origin': req.headers.origin,  // For Cordova\n                'Access-Control-Allow-Credentials': true,\n                'Access-Control-Allow-Headers': 'x-auth-token, user-agent',\n                'Access-Control-Allow-Methods': 'GET, POST, HEAD, OPTIONS'\n            });\n            res.end();\n            return;\n        }\n      }\n    ]\n  }\n);\n```\n\n**Note!:** Reportedly due to a bug in Cordova, you need to add the following line into your mobile-config.js\n```\nApp.accessRule(\"blob:*\");\n```\nPlease notice that this package will only work with \"blob\" types when using resumable on Cordova enviroment. If you are using a \"file\" type remember to convert it to blob before the upload.\n\n#### HTTP authentication\n\nAuthentication of HTTP requests is performed using Meteor login tokens. When Meteor [Accounts](http://docs.meteor.com/#accounts_api) are used in an application, a logged in client can see its current token using `Accounts._storedLoginToken()`. Tokens are passed in HTTP requests using either the HTTP header `X-Auth-Token: [token]` or using an HTTP cookie named `X-Auth-Token=[token]`. If the token matches a valid logged in user, then that userId will be provided to any allow/deny rules that are called for permission for an action.\n\nFor non-Meteor clients that aren't logged-in humans using browsers, it is possible to authenticate with Meteor using the DDP protocol and programmatically obtain a token. See the [ddp-login](https://www.npmjs.org/package/ddp-login) npm package for a node.js library and command-line utility capable of logging into Meteor (similar libraries also exist for other languages such as Python).\n\n#### HTTP request behaviors\n\nURLs used to HTTP GET file data within a browser can be configured to automatically trigger a \"File SaveAs...\" download by using the `?download=true` query in the request URL. Similarly, if the `?filename=[filename.ext]` query is used, a \"File SaveAs...\" download will be invoked, but using the specified filename as the default, rather than the GridFS `filename` as is the case with `?download=true`.\n\nTo cache files in the browser use the `?cache=172800` query in the request URL, where 172800 (48h) is the time in seconds. This will set the header response information to `cache-control:max-age=172800, private`. Caching is useful when streaming videos or audio files to avoid unwanted calls to the server.\n\nHTTP PUT requests write the data from the request body directly into the file. By contrast, HTTP POST requests assume that the body is formatted as MIME multipart/form-data (as an old-school browser form based file upload would generate), and the data written to the file is taken from the part named `\"file\"`. Below are example [cURL](`https://en.wikipedia.org/wiki/CURL#cURL`) commands that successfully invoke each of the four possible HTTP methods.\n\n```sh\n\n# This assumes a baseURL of '/gridfs/fs' and method definitions with a path\n# of '/:_id' for each method, for example:\n\n# { method: 'delete',\n#   path:   '/:_id',\n#   lookup: function (params, query) {\n#             return { _id: params._id } } }\n\n# The file with _id = 38a14c8fef2d6cef53c70792 must exist for these to succeed.\n# The auth token should match a logged-in userId\n\n# GET the file data\ncurl -X GET 'http://127.0.0.1:3000/gridfs/fs/38a14c8fef2d6cef53c70792' \\\n     -H 'X-Auth-Token: 3pl5vbN_ZbKDJ1ko5JteO3ZSTrnQIl5g6fd8XW0U4NQ'\n\n# POST with file in multipart/form-data\ncurl -X POST 'http://127.0.0.1:3000/gridfs/fs/38a14c8fef2d6cef53c70792' \\\n     -F 'file=@\"lolcat.gif\";type=image/gif' \\\n     -H 'X-Auth-Token: 3pl5vbN_ZbKDJ1ko5JteO3ZSTrnQIl5g6fd8XW0U4NQ'\n\n# PUT with file in request body\ncurl -X PUT 'http://127.0.0.1:3000/gridfs/fs/38a14c8fef2d6cef53c70792' \\\n     -H 'Content-Type: image/gif' \\\n     -H 'X-Auth-Token: 3pl5vbN_ZbKDJ1ko5JteO3ZSTrnQIl5g6fd8XW0U4NQ' \\\n     -T \"lolcat.gif\"\n\n# DELETE the file\ncurl -X DELETE 'http://127.0.0.1:3000/gridfs/fs/38a14c8fef2d6cef53c70792' \\\n     -H 'X-Auth-Token: 3pl5vbN_ZbKDJ1ko5JteO3ZSTrnQIl5g6fd8XW0U4NQ'\n```\n\nBelow are the methods defined on the returned `FileCollection` object\n\n### fc.resumable\n#### Resumable.js API object - Client only\n\n```javascript\nfc.resumable.assignDrop($(\".fileDrop\"));  // Assign a file drop target\n\n// When a file is dropped on the target (or added some other way)\nmyData.resumable.on('fileAdded', function (file) {\n  // file contains a resumable,js file object, do something with it...\n}\n```\n\n`fc.resumable` is a ready to use, preconfigured `Resumable` object that is available when a `FileCollection` is created with `options.resumable == true`. `fc.resumable` contains the results of calling `new Resumable([options])` where all of the options have been specified by file-collection to work with its server side support. See the [Resumable.js documentation](http://www.resumablejs.com/) for more details on how to use it.\n\n### fc.find(selector, [options])\n#### Find any number of files - Server and Client\n\n```javascript\n// Count the number of likely lolcats in collection, this is reactive\nlols = fc.find({ 'contentType': 'image/gif'}).count();\n```\n\n`fc.find()` is identical to [Meteor's `Collection.find()`](http://docs.meteor.com/#find)\n\n### fc.findOne(selector, [options])\n#### Find a single file. - Server and Client\n\n```javascript\n// Grab the file document for a known lolcat\n// This is not the file data, see fc.findOneStream() for that!\nmyLol = fc.findOne({ 'filename': 'lolcat.gif'});\n```\n\n`fc.findOne()` is identical to [Meteor's `Collection.findOne()`](http://docs.meteor.com/#findone)\n\n### fc.insert([file], [callback])\n#### Insert a new zero-length file. - Server and Client\n\n```javascript\n// Create a new zero-length file in the collection\n// All fields are optional and will get defaults if omitted\n_id = fc.insert({\n  _id: new Meteor.Collection.ObjectID(),\n  filename: 'nyancat.flv',\n  contentType: 'video/x-flv',\n  metadata: { owner: 'posterity' },\n  aliases: [ ]\n  }\n  // Callback here, if you really care...\n);\n```\n\n`fc.insert()` is the same as [Meteor's `Collection.insert()`](http://docs.meteor.com/#insert), except that the document is forced to be a [gridFS `files` document](http://docs.mongodb.org/manual/reference/gridfs/#the-files-collection). All attributes not supplied get default values, non-gridFS attributes are silently dropped. Inserts from the client that do not conform to the gridFS data model will automatically be denied. Client inserts will additionally be subjected to any `'insert'` allow/deny rules (which default to deny all inserts).\n\n### fc.remove(selector, [callback])\n#### Remove a file and all of its data. - Server and Client\n\n```javascript\n// Make it go away, data and all\nfc.remove(\n  { filename: 'nyancat.flv' }\n  // Callback here, if you want to be absolultely sure it's really gone...\n);\n```\n\n`fc.remove()` is nearly the same as [Meteor's `Collection.remove()`](http://docs.meteor.com/#remove), except that in addition to removing the file document, it also removes the file data chunks and locks from the gridFS store. For safety, undefined and empty selectors (`undefined`, `null` or `{}`) are all rejected. Client calls are subjected to any `'remove'`  allow/deny rules (which default to deny all removes). Returns the number of documents actually removed on the server, except when invoked on the client without a callback. In that case it returns the simulated number of documents removed from the local mini-mongo store.\n\n### fc.update(selector, modifier, [options], [callback])\n#### Update application controlled gridFS file attributes. - Server only\n\nNote: A local-only version of update is available on the client. See docs for `fc.localUpdate()` for details.\n\n```javascript\n// Update some attributes we own\nfc.update(\n  { filename: 'keyboardcat.mp4' },\n  {\n    $set: { 'metadata.comment': 'Play them off...' } },\n    $push: { aliases: 'Fatso.mp4' }\n  }\n  // Optional options here\n  // Optional callback here\n);\n```\n\n`fc.update()` is nearly the same as [Meteor's `Collection.update()`](http://docs.meteor.com/#update), except that it is a server only method, and it will return an error if:\n\n*     any of the gridFS \"read-only\" attributes would be modified\n*     any standard gridFS document level attributes would be removed\n*     the `upsert` option is attempted\n\nSince `fc.update()` only runs on the server, it is *not* subjected to any allow/deny rules.\n\n### fc.localUpdate(selector, modifier, [options], [callback])\n#### Update local minimongo file attributes. - Client only\n\n**Warning!** Changes made using this function do not persist to the server! You must implement your own Meteor methods to perform persistent updates from a client. For example:\n\n```javascript\n// Implement latency compensated update using Meteor methods and localUpdate\nMeteor.methods({\n  updateFileComment: function (fileId, comment) {\n    // Always check method params!\n    check(fileId, Mongo.ObjectID);\n    check(comment, Match.Where(function (x) {\n      check(x, String);\n      return x.length <= 140;\n    }));\n    // You'll probably want to do some kind of ownership check here...\n\n    var update = null;\n    // If desired you can avoid this by initializing fc.update\n    // on the client to be fc.localUpdate\n    if (this.isSimulation) {\n      update = fc.localUpdate; // Client stub updates locally for latency comp\n    } else { // isServer\n      update = fc.update;  // Server actually persists the update\n    }\n    // Use whichever function the environment dictates\n    update({ _id: _id }, {\n        $set: { 'metadata.comment': comment }\n      }\n      // Optional options here\n      // Optional callback here\n    );\n  }\n});\n```\n\n`fc.localUpdate()` is nearly the same as [Meteor's server-side `Collection.update()`](http://docs.meteor.com/#update), except that it is a client only method, and changes made using it do not propagate to the server. This call is useful for implementing latency compensation in the client UI when performing server updates using a Meteor method. This call can be invoked in the client Method stub to simulate what will be happening on the server. For this reason, this call can perform updates using complex selectors and the `multi` option, unlike client side updates on normal Mongo Collections.\n\nIt will return an error if:\n\n*     any of the gridFS \"read-only\" attributes would be modified\n*     any standard gridFS document level attributes would be removed\n*     the `upsert` option is attempted\n\nSince `fc.localUpdate()` only changes data on the client, it is *not* subjected to any allow/deny rules.\n\n### fc.allow(options)\n#### Allow client insert and remove, and HTTP data accesses and updates, subject to your limitations. - Server only\n\n`fc.allow(options)` is essentially the same as [Meteor's `Collection.allow()`](http://docs.meteor.com/#allow), except that the Meteor Collection `fetch` and `transform` options are not supported by `FileCollection`. In addition to returning true/false, rules may also return a (possibly empty) options object to indicate truth while affecting the behavior of the allowed request.  See the `maxUploadSize` option on `'write'` allow rules as an example. Note that more than one allow rule may apply to a given request, but unlike deny rules, they are not all guaranteed to run. Allow rules are run in the order in which they are defined, and the first one to return a truthy value wins, which can be significant if they return options or otherwise modify state.\n\n`insert` rules are essentially the same as for ordinary Meteor collections.\n\n`remove` rules also apply to HTTP DELETE requests.\n\nIn addition to Meteor's `insert` and `remove` rules, file-collection also uses `read` and `write` rules. These are used to secure access to file data via HTTP GET and POST/PUT requests, respectively.\n\n`read` rules apply only to HTTP GET/HEAD requests retrieving file data, and have the same parameters as all other rules.\n\n`write` rules are analogous to `update` rules on Meteor collections, except that they apply only to HTTP PUT/POST requests modifying file data, and will only (and always) see changes to the `length` and `md5` fields. For that reason the `fieldNames` parameter is omitted. Similarly, because MongoDB updates are not directly involved, no `modifier` parameter is provided to the `write` function. Write rules may optionally return an object with a positive integer `maxUploadSize` attribute instead of `true`. This indicates the maximum allowable upload size for this request. If this max upload size is provided, it will override any value provided for the `maxUploadSize` option on the fileCollection as a whole. Nonpositive values of `maxUploadSize` mean there will be no upload size limit for this request.\n\nThe parameters for callback functions for all four types of allow/deny rules are the same:\n\n```js\nfunction (userId, file) {\n   // userId is Meteor account if authenticated\n   // file is the gridFS file record for the matching file\n}\n```\n\n### fc.deny(options)\n#### Override allow rules. - Server only\n\n```javascript\nfc.deny({\n  remove: function (userId, file) { return true; }  // Nobody can remove, boo!\n});\n```\n\n`fc.deny(options)` is the same as [Meteor's `Collection.deny()`](http://docs.meteor.com/#deny), except that the Meteor Collection `fetch` and `transform` options are not supported by `FileCollection`. See `fc.allow()` above for more deatils.\n\n### fc.findOneStream(selector, [options], [callback])\n#### Find a file collection file and return a readable stream for its data. - Server only\n\n```javascript\n// Get a readable data stream for a known lolcat\nlolStream = fc.findOneStream({ 'filename': 'lolcat.gif'});\n```\n\n`fc.findOneStream()` is like `fc.findOne()` except instead of returning the `files` document for the found file, it returns a [Readable stream](http://nodejs.org/api/stream.html#stream_class_stream_readable) for the found file's data.\n\n`options.range` -- To get partial data from the file, use the `range` option to specify an object with `start` and `end` attributes:\n\n```javascript\nstream = fc.findOneStream({ 'filename': 'lolcat.gif'}, { range: { start: 100, end: 200 }})\n```\n\n`options.autoRenewLock` -- When true, the read lock on the underlying gridFS file will automatically be renewed before it expires, potentially multiple times. If you need more control over lock expiration behavior in your application, set this option to `false`. Default: `true`\n\nOther available options are `options.sort` and `options.skip` which have the same behavior as they do for Meteor's [`Collection.findOne()`](http://docs.meteor.com/#findone).\n\nThe returned stream is a gridfs-locking-stream `readStream`, which has some [special methods and events it emits](https://github.com/vsivsi/gridfs-locking-stream#locking-options). You probably won't need to use these, but the stream will emit `'expires-soon'` and `'expired'` events if its read lock is getting too old, and it has three methods that can be used to control locking:\n*     `stream.heldLock()` - Returns the gridfs-locks [`Lock` object](https://github.com/vsivsi/gridfs-locks#lock) held by the stream\n*     `stream.renewLock([callback])` - Renews the held lock for another expiration interval\n*     `stream.releaseLock([callback])` - Releases the held lock if you are done with the stream.\n\nThis last call, `stream.releaseLock()` may be useful if you use `file.findOneStream()` and then do not read the file to the end (which would cause the lock to release automatically). In this case, calling `stream.releaseLock()` is nice because it frees the lock before the expiration time is up. This would probably only matter for applications with lots of writers and readers contending for the same files, but it's good to know it exists. The values used for the locking parameters are set when the `FileCollection` is created via the `options.locks` option.\n\nWhen the stream has ended, the `callback` is called with the gridFS file document.\n\n### fc.upsertStream(file, [options], [callback])\n#### Create/update a file collection file and return a writable stream to its data. - Server only\n\n```javascript\n// Get a writeable data stream to re-store all that is right and good\nnyanStream = fc.upsertStream({ filename: 'nyancat.flv',\n                               contentType: 'video/x-flv',\n                               metadata: { caption: 'Not again!'}\n                             });\n```\n\n`fc.upsertStream()` is a little bit like Meteor's `Collection.upsert()` only really not... If the `file` parameter contains an `_id` field, then the call will work on the file with that `_id`. If a file with that `_id` doesn't exist, or if no `_id` is provided, then a new file is `insert`ed into the file collection. Any application owned gridFS attributes (`filename`, `contentType`, `aliases`, `metadata`) that are present in the `file` parameter will be used for the file.\n\nOnce that is done, `fc.upsertStream()` returns a [writable stream](http://nodejs.org/api/stream.html#stream_class_stream_writable) for the file.\n\n`options.autoRenewLock` -- Default: `true`. When true, the write lock on the underlying gridFS file will automatically be renewed before it expires, potentially multiple times. If you need more control over lock expiration behavior in your application, set this option to `false`.\n\n*NOTE! Breaking Change*! Prior to file-collection v1.0, it was possible to specify `options.mode = 'w+'` and append to an existing file. This option is now ignored, and all calls to `fc.upsertStream()` will overwrite any existing data in the file.\n\nThe returned stream is a gridfs-locking-stream `writeStream`, which has some [special methods and events it emits](https://github.com/vsivsi/gridfs-locking-stream#locking-options). You probably won't need to use these, but the stream will emit `'expires-soon'` and `'expired'` events if its exclusive write lock is getting too old, and it has three methods that can be used to control locking:\n*     `stream.heldLock()` - Returns the gridfs-locks [`Lock` object](https://github.com/vsivsi/gridfs-locks#lock) held by the stream\n*     `stream.renewLock([callback])` - Renews the held lock for another expiration interval\n*     `stream.releaseLock([callback])` - Releases the held lock if you are done with the stream.\n\nYou probably won't need these, but it's good to know they're there. The values used for the locking parameters are set when the `FileCollection` is created via the `options.locks` option.\n\nWhen the write stream has closed, the `callback` is called as `callback(error, file)`, where file is the gridFS file document following the write.\n\n### fc.exportFile(selector, filePath, callback)\n#### Export a file collection file to the local fileSystem. - Server only\n\n```javascript\n// Write a file to wherever it belongs in the filesystem\nfc.exportFile({ 'filename': 'nyancat.flv'},\n              '/dev/null',\n              function(err) {\n                // Deal with it\n              });\n```\n\n`fc.exportFile()` is a convenience method that [pipes](http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options) the readable stream produced by `fc.findOneStream()` into a local [file system writable stream](http://nodejs.org/api/fs.html#fs_fs_createwritestream_path_options).\n\nThe `selector` parameter works as it does with `fc.findOneStream()`. The `filePath` is the String directory path and filename in the local filesystem to write the file data to. The value of the `filename` attribute in the found gridFS file document is ignored. The callback is mandatory and will be called with a single parameter that will be either an `Error` object or `null` depending on the success of the operation.\n\n### fc.importFile(filePath, file, callback)\n#### Import a local filesystem file into a file collection file. - Server only\n\n```javascript\n// Read a file into the collection from the filesystem\nfc.importFile('/funtimes/lolcat_183.gif',\n              { filename: 'lolcat_183.gif',\n                contentType: 'image/gif'\n              },\n              function(err, file) {\n                // Deal with it\n                // Or file contains all of the details.\n              });\n```\n\n`fc.importFile()` is a convenience method that [pipes](http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options) a local [file system readable stream](http://nodejs.org/api/fs.html#fs_fs_createreadstream_path_options) into the writable stream produced by a call to `fc.upsertStream()`.\n\nThe `file` parameter works as it does with `fc.upsertStream()`. The `filePath` is the String directory path and filename in the local filesystem of the file to open and copy into the gridFS file. The callback is mandatory and will be called with the same callback signature as `fc.upsertStream()`.\n"
  },
  {
    "path": "package.js",
    "content": "/***************************************************************************\n###     Copyright (C) 2014-2017 by Vaughn Iverson\n###     fileCollection is free software released under the MIT/X11 license.\n###     See included LICENSE file for details.\n***************************************************************************/\n\nvar currentVersion = '1.3.8';\n\nPackage.describe({\n  summary: 'Collections that efficiently store files using MongoDB GridFS, with built-in HTTP support',\n  name: 'vsivsi:file-collection',\n  version: currentVersion,\n  git: 'https://github.com/vsivsi/meteor-file-collection.git'\n});\n\nNpm.depends({\n  // latest mongodb driver is 2.2.x, but early revs, currently seems broken\n  mongodb: '2.1.21',\n  'gridfs-locking-stream': '1.1.1',\n  'gridfs-locks': '1.3.4',\n  dicer: '0.2.5',\n  async: '2.1.4',\n  express: '4.14.1',\n  'cookie-parser': '1.4.3',\n  // Version 2.x of through2 is Streams3, so don't go there yet!\n  through2: '0.6.5'\n});\n\nPackage.onUse(function(api) {\n  api.use('coffeescript@1.12.3_1', ['server','client']);\n  api.use('webapp@1.3.13', 'server');\n  api.use('mongo@1.1.15', ['server', 'client']);\n  api.use('minimongo@1.0.20', 'server');\n  api.use('check@1.2.5', ['server', 'client']);\n  api.addFiles('resumable/resumable.js', 'client');\n  api.addFiles('src/gridFS.coffee', ['server','client']);\n  api.addFiles('src/server_shared.coffee', 'server');\n  api.addFiles('src/gridFS_server.coffee', 'server');\n  api.addFiles('src/resumable_server.coffee', 'server');\n  api.addFiles('src/http_access_server.coffee', 'server');\n  api.addFiles('src/resumable_client.coffee', 'client');\n  api.addFiles('src/gridFS_client.coffee', 'client');\n  api.export('FileCollection');\n});\n\nPackage.onTest(function (api) {\n  api.use('vsivsi:file-collection@' + currentVersion, ['server', 'client']);\n  api.use('coffeescript@1.12.3_1', ['server', 'client']);\n  api.use('tinytest@1.0.12', ['server', 'client']);\n  api.use('test-helpers@1.0.11', ['server','client']);\n  api.use('http@1.2.11', ['server','client']);\n  api.use('ejson@1.0.13',['server','client']);\n  api.use('mongo@1.1.15', ['server', 'client']);\n  api.use('check@1.2.5', ['server', 'client']);\n  api.use('tracker@1.1.2', 'client');\n  api.addFiles('test/file_collection_tests.coffee', ['server', 'client']);\n});\n"
  },
  {
    "path": "packages/.gitignore",
    "content": "/fileCollection\n"
  },
  {
    "path": "src/gridFS.coffee",
    "content": "############################################################################\n#     Copyright (C) 2014-2017 by Vaughn Iverson\n#     fileCollection is free software released under the MIT/X11 license.\n#     See included LICENSE file for details.\n############################################################################\n\nshare.defaultChunkSize = 2*1024*1024 - 1024\nshare.defaultRoot = 'fs'\n\nshare.resumableBase = '/_resumable'\n\nshare.insert_func = (file = {}, chunkSize) ->\n   try\n      id = new Mongo.ObjectID(\"#{file._id}\")\n   catch\n      id = new Mongo.ObjectID()\n   subFile = {}\n   subFile._id = id\n   subFile.length = 0\n   subFile.md5 = 'd41d8cd98f00b204e9800998ecf8427e'\n   subFile.uploadDate = new Date()\n   subFile.chunkSize = chunkSize\n   subFile.filename = file.filename ? ''\n   subFile.metadata = file.metadata ? {}\n   subFile.aliases = file.aliases ? []\n   subFile.contentType = file.contentType ? 'application/octet-stream'\n   return subFile\n\nshare.reject_file_modifier = (modifier) ->\n\n   forbidden = Match.OneOf(\n      Match.ObjectIncluding({ _id:        Match.Any })\n      Match.ObjectIncluding({ length:     Match.Any })\n      Match.ObjectIncluding({ chunkSize:  Match.Any })\n      Match.ObjectIncluding({ md5:        Match.Any })\n      Match.ObjectIncluding({ uploadDate: Match.Any })\n   )\n\n   required = Match.OneOf(\n      Match.ObjectIncluding({ _id:         Match.Any })\n      Match.ObjectIncluding({ length:      Match.Any })\n      Match.ObjectIncluding({ chunkSize:   Match.Any })\n      Match.ObjectIncluding({ md5:         Match.Any })\n      Match.ObjectIncluding({ uploadDate:  Match.Any })\n      Match.ObjectIncluding({ metadata:    Match.Any })\n      Match.ObjectIncluding({ aliases:     Match.Any })\n      Match.ObjectIncluding({ filename:    Match.Any })\n      Match.ObjectIncluding({ contentType: Match.Any })\n   )\n\n   return Match.test modifier, Match.OneOf(\n      Match.ObjectIncluding({ $set: forbidden })\n      Match.ObjectIncluding({ $unset: required })\n      Match.ObjectIncluding({ $inc: forbidden })\n      Match.ObjectIncluding({ $mul: forbidden })\n      Match.ObjectIncluding({ $bit: forbidden })\n      Match.ObjectIncluding({ $min: forbidden })\n      Match.ObjectIncluding({ $max: forbidden })\n      Match.ObjectIncluding({ $rename: required })\n      Match.ObjectIncluding({ $currentDate: forbidden })\n      Match.Where (pat) -> # This requires that the update isn't a replacement\n        return not Match.test pat, Match.OneOf(\n          Match.ObjectIncluding({ $inc: Match.Any })\n          Match.ObjectIncluding({ $set: Match.Any })\n          Match.ObjectIncluding({ $unset: Match.Any })\n          Match.ObjectIncluding({ $addToSet: Match.Any })\n          Match.ObjectIncluding({ $pop: Match.Any })\n          Match.ObjectIncluding({ $pullAll: Match.Any })\n          Match.ObjectIncluding({ $pull: Match.Any })\n          Match.ObjectIncluding({ $pushAll: Match.Any })\n          Match.ObjectIncluding({ $push: Match.Any })\n          Match.ObjectIncluding({ $bit: Match.Any })\n        )\n   )\n"
  },
  {
    "path": "src/gridFS_client.coffee",
    "content": "############################################################################\n#     Copyright (C) 2014-2017 by Vaughn Iverson\n#     fileCollection is free software released under the MIT/X11 license.\n#     See included LICENSE file for details.\n############################################################################\n\nif Meteor.isClient\n\n   class FileCollection extends Mongo.Collection\n\n      constructor: (@root = share.defaultRoot, options = {}) ->\n         unless @ instanceof FileCollection\n            return new FileCollection(root, options)\n\n         unless @ instanceof Mongo.Collection\n            throw new Meteor.Error 'The global definition of Mongo.Collection has changed since the file-collection package was loaded. Please ensure that any packages that redefine Mongo.Collection are loaded before file-collection.'\n\n         unless Mongo.Collection is Mongo.Collection.prototype.constructor\n           throw new Meteor.Error 'The global definition of Mongo.Collection has been patched by another package, and the prototype constructor has been left in an inconsistent state. Please see this link for a workaround: https://github.com/vsivsi/meteor-file-sample-app/issues/2#issuecomment-120780592'\n\n         if typeof @root is 'object'\n            options = @root\n            @root = share.defaultRoot\n\n         @base = @root\n         @baseURL = options.baseURL ? \"/gridfs/#{@root}\"\n         @chunkSize = options.chunkSize ? share.defaultChunkSize\n         super @root + '.files', { idGeneration: 'MONGO' }\n\n         # This call sets up the optional support for resumable.js\n         # See the resumable.coffee file for more information\n         if options.resumable\n            share.setup_resumable.bind(@)()\n\n      # remove works as-is. No modifications necessary so it currently goes straight to super\n\n      # Insert only creates an empty (but valid) gridFS file. To put data into it from a client,\n      # you need to use an HTTP POST or PUT after the record is inserted. For security reasons,\n      # you shouldn't be able to POST or PUT to a file that hasn't been inserted.\n\n      insert: (file, callback = undefined) ->\n         # This call ensures that a full gridFS file document\n         # gets built from whatever is provided\n         file = share.insert_func file, @chunkSize\n         super file, callback\n\n      # This will only update the local client-side minimongo collection\n      # You can shadow update with this to enable latency compensation when\n      # updating the server-side collection using a Meteor method call\n      localUpdate: (selector, modifier, options = {}, callback = undefined) ->\n         if not callback? and typeof options is 'function'\n            callback = options\n            options = {}\n\n         if options.upsert?\n            err = new Meteor.Error \"Update does not support the upsert option\"\n            if callback?\n               return callback err\n            else\n               throw err\n\n         if share.reject_file_modifier(modifier)\n            err = new Meteor.Error \"Modifying gridFS read-only document elements is a very bad idea!\"\n            if callback?\n               return callback err\n            else\n               throw err\n         else\n            @find().collection.update selector, modifier, options, callback\n\n      allow: () ->\n        throw new Meteor.Error \"File Collection Allow rules may not be set in client code.\"\n\n      deny: () ->\n        throw new Meteor.Error \"File Collection Deny rules may not be set in client code.\"\n\n      upsert: () ->\n         throw new Meteor.Error \"File Collections do not support 'upsert'\"\n\n      update: () ->\n         throw new Meteor.Error \"File Collections do not support 'update' on client, use method calls instead\"\n\n      findOneStream: () ->\n         throw new Meteor.Error \"File Collections do not support 'findOneStream' in client code.\"\n\n      upsertStream: () ->\n         throw new Meteor.Error \"File Collections do not support 'upsertStream' in client code.\"\n\n      importFile: () ->\n         throw new Meteor.Error \"File Collections do not support 'importFile' in client code.\"\n\n      exportFile: () ->\n         throw new Meteor.Error \"File Collections do not support 'exportFile' in client code.\"\n"
  },
  {
    "path": "src/gridFS_server.coffee",
    "content": "############################################################################\n#     Copyright (C) 2014-2017 by Vaughn Iverson\n#     fileCollection is free software released under the MIT/X11 license.\n#     See included LICENSE file for details.\n############################################################################\n\nif Meteor.isServer\n\n   mongodb = Npm.require 'mongodb'\n   grid = Npm.require 'gridfs-locking-stream'\n   gridLocks = Npm.require 'gridfs-locks'\n   fs = Npm.require 'fs'\n   path = Npm.require 'path'\n   dicer = Npm.require 'dicer'\n   express = Npm.require 'express'\n\n   class FileCollection extends Mongo.Collection\n\n      constructor: (@root = share.defaultRoot, options = {}) ->\n         unless @ instanceof FileCollection\n            return new FileCollection(@root, options)\n\n         unless @ instanceof Mongo.Collection\n            throw new Meteor.Error 'The global definition of Mongo.Collection has changed since the file-collection package was loaded. Please ensure that any packages that redefine Mongo.Collection are loaded before file-collection.'\n\n         unless Mongo.Collection is Mongo.Collection.prototype.constructor\n           throw new Meteor.Error 'The global definition of Mongo.Collection has been patched by another package, and the prototype constructor has been left in an inconsistent state. Please see this link for a workaround: https://github.com/vsivsi/meteor-file-sample-app/issues/2#issuecomment-120780592'\n\n         if typeof @root is 'object'\n            options = @root\n            @root = share.defaultRoot\n\n         @chunkSize = options.chunkSize ? share.defaultChunkSize\n\n         @db = Meteor.wrapAsync(mongodb.MongoClient.connect)(process.env.MONGO_URL,{})\n\n         @lockOptions =\n            timeOut: options.locks?.timeOut ? 360\n            lockExpiration: options.locks?.lockExpiration ? 90\n            pollingInterval: options.locks?.pollingInterval ? 5\n\n         @locks = gridLocks.LockCollection @db,\n            root: @root\n            timeOut: @lockOptions.timeOut\n            lockExpiration: @lockOptions.lockExpiration\n            pollingInterval: @lockOptions.pollingInterval\n\n         @gfs = new grid(@db, mongodb, @root)\n\n         @baseURL = options.baseURL ? \"/gridfs/#{@root}\"\n\n         # if there are HTTP options, setup the express HTTP access point(s)\n         if options.resumable or options.http\n            share.setupHttpAccess.bind(@)(options)\n\n         # Default client allow/deny permissions\n         @allows = { read: [], insert: [], write: [], remove: [] }\n         @denys = { read: [], insert: [], write: [], remove: [] }\n\n         # Call super's constructor\n         super @root + '.files', { idGeneration: 'MONGO' }\n\n         # Default indexes\n         if options.resumable\n            indexOptions = {}\n            if typeof options.resumableIndexName is 'string'\n               indexOptions.name = options.resumableIndexName\n\n            @db.collection(\"#{@root}.files\").ensureIndex({\n                  'metadata._Resumable.resumableIdentifier': 1\n                  'metadata._Resumable.resumableChunkNumber': 1\n                  length: 1\n               }, indexOptions)\n\n         @maxUploadSize = options.maxUploadSize ? -1  # Negative is no limit...\n\n         ## Delay this feature until demand is clear. Unit tests / documentation needed.\n\n         # unless options.additionalHTTPHeaders? and (typeof options.additionalHTTPHeaders is 'object')\n         #    options.additionalHTTPHeaders = {}\n         #\n         # for h, v of options.additionalHTTPHeaders\n         #    share.defaultResponseHeaders[h] = v\n\n         # Setup specific allow/deny rules for gridFS, and tie-in the application settings\n\n         FileCollection.__super__.allow.bind(@)\n            # Because allow rules are not guaranteed to run,\n            # all checking is done in the deny rules below\n            insert: (userId, file) => true\n            remove: (userId, file) => true\n\n         FileCollection.__super__.deny.bind(@)\n\n            insert: (userId, file) =>\n\n               # Make darn sure we're creating a valid gridFS .files document\n               check file,\n                  _id: Mongo.ObjectID\n                  length: Match.Where (x) =>\n                     check x, Match.Integer\n                     x is 0\n                  md5: Match.Where (x) =>\n                     check x, String\n                     x is 'd41d8cd98f00b204e9800998ecf8427e' # The md5 of an empty file\n                  uploadDate: Date\n                  chunkSize: Match.Where (x) =>\n                     check x, Match.Integer\n                     x is @chunkSize\n                  filename: String\n                  contentType: String\n                  aliases: [ String ]\n                  metadata: Object\n\n               # Enforce a uniform chunkSize\n               unless file.chunkSize is @chunkSize\n                  console.warn \"Invalid chunksize\"\n                  return true\n\n               # call application rules\n               if share.check_allow_deny.bind(@) 'insert', userId, file\n                  return false\n\n               return true\n\n            update: (userId, file, fields) =>\n               ## Cowboy updates are not currently allowed from the client. Too much to screw up.\n               ## For example, if you store file ownership info in a sub document under 'metadata'\n               ## it will be complicated to guard against that being changed if you allow other parts\n               ## of the metadata sub doc to be updated. Write specific Meteor methods instead to\n               ## allow reasonable changes to the \"metadata\" parts of the gridFS file record.\n               return true\n\n            remove: (userId, file) =>\n               ## Remove is now handled via the default method override below, so this should\n               ## never be called.\n               return true\n\n         self = @ # Necessary in the method definition below\n\n         ## Remove method override for this server-side collection\n         Meteor.server.method_handlers[\"#{@_prefix}remove\"] = (selector) ->\n\n            check selector, Object\n\n            unless LocalCollection._selectorIsIdPerhapsAsObject(selector)\n               throw new Meteor.Error 403, \"Not permitted. Untrusted code may only remove documents by ID.\"\n\n            cursor = self.find selector\n\n            if cursor.count() > 1\n               throw new Meteor.Error 500, \"Remote remove selector targets multiple files.\\nSee https://github.com/vsivsi/meteor-file-collection/issues/152#issuecomment-278824127\"\n\n            [file] = cursor.fetch()\n\n            if file\n               if share.check_allow_deny.bind(self) 'remove', this.userId, file\n                  return self.remove file\n               else\n                  throw new Meteor.Error 403, \"Access denied\"\n            else\n               return 0\n\n      # Register application allow rules\n      allow: (allowOptions) ->\n         for type, func of allowOptions\n            unless type of @allows\n               throw new Meteor.Error \"Unrecognized allow rule type '#{type}'.\"\n            unless typeof func is 'function'\n               throw new Meteor.Error \"Allow rule #{type} must be a valid function.\"\n            @allows[type].push(func)\n\n      # Register application deny rules\n      deny: (denyOptions) ->\n         for type, func of denyOptions\n            unless type of @denys\n               throw new Meteor.Error \"Unrecognized deny rule type '#{type}'.\"\n            unless typeof func is 'function'\n               throw new Meteor.Error \"Deny rule #{type} must be a valid function.\"\n            @denys[type].push(func)\n\n      insert: (file = {}, callback = undefined) ->\n         file = share.insert_func file, @chunkSize\n         super file, callback\n\n      # Update is dangerous! The checks inside attempt to keep you out of\n      # trouble with gridFS. Clients can't update at all. Be careful!\n      # Only metadata, filename, aliases and contentType should ever be changed\n      # directly by a server.\n\n      update: (selector, modifier, options = {}, callback = undefined) ->\n         if not callback? and typeof options is 'function'\n            callback = options\n            options = {}\n\n         if options.upsert?\n            err = new Meteor.Error \"Update does not support the upsert option\"\n            if callback?\n               return callback err\n            else\n               throw err\n\n         if share.reject_file_modifier(modifier) and not options.force\n            err = new Meteor.Error \"Modifying gridFS read-only document elements is a very bad idea!\"\n            if callback?\n               return callback err\n            else\n               throw err\n         else\n            super selector, modifier, options, callback\n\n      upsert: (selector, modifier, options = {}, callback = undefined) ->\n         if not callback? and typeof options is 'function'\n            callback = options\n         err = new Meteor.Error \"File Collections do not support 'upsert'\"\n         if callback?\n            callback err\n         else\n            throw err\n\n      upsertStream: (file, options = {}, callback = undefined) ->\n         if not callback? and typeof options is 'function'\n            callback = options\n            options = {}\n         callback = share.bind_env callback\n         cbCalled = false\n         mods = {}\n         mods.filename = file.filename if file.filename?\n         mods.aliases = file.aliases if file.aliases?\n         mods.contentType = file.contentType if file.contentType?\n         mods.metadata = file.metadata if file.metadata?\n\n         options.autoRenewLock ?= true\n\n         if options.mode is 'w+'\n            throw new Meteor.Error \"The ability to append file data in upsertStream() was removed in version 1.0.0\"\n\n         # Make sure that we have an ID and it's valid\n         if file._id\n            found = @findOne {_id: file._id}\n\n         unless file._id and found\n            file._id = @insert mods\n         else if Object.keys(mods).length > 0\n            @update { _id: file._id }, { $set: mods }\n\n         writeStream = Meteor.wrapAsync(@gfs.createWriteStream.bind(@gfs))\n            root: @root\n            _id: mongodb.ObjectID(\"#{file._id}\")\n            mode: 'w'\n            timeOut: @lockOptions.timeOut\n            lockExpiration: @lockOptions.lockExpiration\n            pollingInterval: @lockOptions.pollingInterval\n\n         if writeStream\n\n            if options.autoRenewLock\n               writeStream.on 'expires-soon', () =>\n                  writeStream.renewLock (e, d) ->\n                     if e or not d\n                        console.warn \"Automatic Write Lock Renewal Failed: #{file._id}\", e\n\n            if callback?\n               writeStream.on 'close', (retFile) ->\n                  if retFile\n                     retFile._id = new Mongo.ObjectID retFile._id.toHexString()\n                     callback(null, retFile)\n               writeStream.on 'error', (err) ->\n                  callback(err)\n\n            return writeStream\n\n         return null\n\n      findOneStream: (selector, options = {}, callback = undefined) ->\n         if not callback? and typeof options is 'function'\n            callback = options\n            options = {}\n\n         callback = share.bind_env callback\n         opts = {}\n         opts.sort = options.sort if options.sort?\n         opts.skip = options.skip if options.skip?\n         file = @findOne selector, opts\n\n         if file\n            options.autoRenewLock ?= true\n\n            # Init the start and end range, default to full file or start/end as specified\n            range =\n               start: options.range?.start ? 0\n               end: options.range?.end ? file.length - 1\n\n            readStream = Meteor.wrapAsync(@gfs.createReadStream.bind(@gfs))\n               root: @root\n               _id: mongodb.ObjectID(\"#{file._id}\")\n               timeOut: @lockOptions.timeOut\n               lockExpiration: @lockOptions.lockExpiration\n               pollingInterval: @lockOptions.pollingInterval\n               range:\n                 startPos: range.start\n                 endPos: range.end\n\n            if readStream\n               if options.autoRenewLock\n                  readStream.on 'expires-soon', () =>\n                     readStream.renewLock (e, d) ->\n                        if e or not d\n                           console.warn \"Automatic Read Lock Renewal Failed: #{file._id}\", e\n\n               if callback?\n                  readStream.on 'close', () ->\n                     callback(null, file)\n                  readStream.on 'error', (err) ->\n                     callback(err)\n               return readStream\n\n         return null\n\n      remove: (selector, callback = undefined) ->\n         callback = share.bind_env callback\n         if selector?\n            ret = 0\n            @find(selector).forEach (file) =>\n               res = Meteor.wrapAsync(@gfs.remove.bind(@gfs))\n                  _id: mongodb.ObjectID(\"#{file._id}\")\n                  root: @root\n                  timeOut: @lockOptions.timeOut\n                  lockExpiration: @lockOptions.lockExpiration\n                  pollingInterval: @lockOptions.pollingInterval\n               ret += if res then 1 else 0\n            callback? and callback null, ret\n            return ret\n         else\n            err = new Meteor.Error \"Remove with an empty selector is not supported\"\n            if callback?\n               callback err\n               return\n            else\n               throw err\n\n      importFile: (filePath, file, callback) ->\n         callback = share.bind_env callback\n         filePath = path.normalize filePath\n         file ?= {}\n         file.filename ?= path.basename filePath\n         readStream = fs.createReadStream filePath\n         readStream.on('error', share.bind_env(callback))\n         writeStream = @upsertStream file\n         readStream.pipe(share.streamChunker(@chunkSize)).pipe(writeStream)\n            .on('close', share.bind_env((d) -> callback(null, d)))\n            .on('error', share.bind_env(callback))\n\n      exportFile: (selector, filePath, callback) ->\n         callback = share.bind_env callback\n         filePath = path.normalize filePath\n         readStream = @findOneStream selector\n         writeStream = fs.createWriteStream filePath\n         readStream.pipe(writeStream)\n            .on('finish', share.bind_env(callback))\n            .on('error', share.bind_env(callback))\n"
  },
  {
    "path": "src/http_access_server.coffee",
    "content": "############################################################################\n#     Copyright (C) 2014-2017 by Vaughn Iverson\n#     fileCollection is free software released under the MIT/X11 license.\n#     See included LICENSE file for details.\n############################################################################\n\nif Meteor.isServer\n\n   express = Npm.require 'express'\n   cookieParser = Npm.require 'cookie-parser'\n   mongodb = Npm.require 'mongodb'\n   grid = Npm.require 'gridfs-locking-stream'\n   gridLocks = Npm.require 'gridfs-locks'\n   dicer = Npm.require 'dicer'\n\n   find_mime_boundary = (req) ->\n      RE_BOUNDARY = /^multipart\\/.+?(?:; boundary=(?:(?:\"(.+)\")|(?:([^\\s]+))))$/i\n      result = RE_BOUNDARY.exec req.headers['content-type']\n      result?[1] or result?[2]\n\n   # Fast MIME Multipart parsing of generic HTTP POST request bodies\n   dice_multipart = (req, res, next) ->\n\n      next = share.bind_env next\n\n      unless req.method is 'POST' and not req.diced\n         next()\n         return\n\n      req.diced = true   # Don't reenter for the same request on multiple routes\n\n      responseSent = false\n      handleFailure = (msg, err = \"\", retCode = 500) ->\n         console.error \"#{msg} \\n\", err\n         unless responseSent\n            responseSent = true\n            res.writeHead retCode, share.defaultResponseHeaders\n            res.end()\n\n      boundary = find_mime_boundary req\n\n      unless boundary\n         handleFailure \"No MIME multipart boundary found for dicer\"\n         return\n\n      params = {}\n      count = 0\n      fileStream = null\n      fileType = 'text/plain'\n      fileName = 'blob'\n\n      d = new dicer { boundary: boundary }\n\n      d.on 'part', (p) ->\n         p.on 'header', (header) ->\n            RE_FILE = /^form-data; name=\"file\"; filename=\"([^\"]+)\"/\n            RE_PARAM = /^form-data; name=\"([^\"]+)\"/\n            for k, v of header\n               if k is 'content-type'\n                  fileType = v\n               if k is 'content-disposition'\n                  if re = RE_FILE.exec(v)\n                     fileStream = p\n                     fileName = re[1]\n                  else if param = RE_PARAM.exec(v)?[1]\n                     data = ''\n                     count++\n                     p.on 'data', (d) ->\n                        data += d.toString()\n                     p.on 'end', () ->\n                        count--\n                        params[param] = data\n                        if count is 0 and fileStream\n                           req.multipart =\n                              fileStream: fileStream\n                              fileName: fileName\n                              fileType: fileType\n                              params: params\n                           responseSent = true\n                           next()\n                  else\n                     console.warn \"Dicer part\", v\n\n            if count is 0 and fileStream\n               req.multipart =\n                  fileStream: fileStream\n                  fileName: fileName\n                  fileType: fileType\n                  params: params\n               responseSent = true\n               next()\n\n         p.on 'error', (err) ->\n            handleFailure 'Error in Dicer while parsing multipart:', err\n\n      d.on 'error', (err) ->\n         handleFailure 'Error in Dicer while parsing parts:', err\n\n      d.on 'finish', () ->\n         unless fileStream\n            handleFailure \"Error in Dicer, no file found in POST\"\n\n      req.pipe(d)\n\n   # Handle a generic HTTP POST file upload\n\n   # This curl command should be properly handled by this code:\n   # % curl -X POST 'http://127.0.0.1:3000/gridfs/fs/38a14c8fef2d6cef53c70792' \\\n   #        -F 'file=@\"universe.png\";type=image/png' -H 'X-Auth-Token: zrtrotHrDzwA4nC5'\n\n   post = (req, res, next) ->\n      # Handle filename or filetype data when included\n      req.gridFS.contentType = req.multipart.fileType if req.multipart.fileType\n      req.gridFS.filename = req.multipart.fileName if req.multipart.fileName\n\n      # Write the file data.  No chunks here, this is the whole thing\n      stream = @upsertStream req.gridFS\n      if stream\n         req.multipart.fileStream.pipe(share.streamChunker(@chunkSize)).pipe(stream)\n            .on 'close', (retFile) ->\n               if retFile\n                  res.writeHead(200, share.defaultResponseHeaders)\n                  res.end()\n            .on 'error', (err) ->\n               res.writeHead(500, share.defaultResponseHeaders)\n               res.end()\n      else\n         res.writeHead(410, share.defaultResponseHeaders)\n         res.end()\n\n   # Handle a generic HTTP GET request\n   # This also handles HEAD requests\n   # If the request URL has a \"?download=true\" query, then a browser download response is triggered\n\n   get = (req, res, next) ->\n\n      headers = {}\n      for h, v of share.defaultResponseHeaders\n         headers[h] = v\n\n      ## If If-Modified-Since header present, and parses to a date, then we\n      ## return 304 (Not Modified Since) if the modification date is less than\n      ## the specified date, or they both format to the same UTC string\n      ## (which can deal with some sub-second rounding caused by formatting).\n      if req.headers['if-modified-since']\n         since = Date.parse req.headers['if-modified-since']  ## NaN if invaild\n         if since and req.gridFS.uploadDate and (req.headers['if-modified-since'] == req.gridFS.uploadDate.toUTCString() or since >= req.gridFS.uploadDate.getTime())\n            res.writeHead 304, headers\n            res.end()\n            return\n\n      # If range request in the header\n      if req.headers['range']\n        # Set status code to partial data\n        statusCode = 206\n\n        # Pick out the range required by the browser\n        parts = req.headers[\"range\"].replace(/bytes=/, \"\").split(\"-\")\n        start = parseInt(parts[0], 10)\n        end = (if parts[1] then parseInt(parts[1], 10) else req.gridFS.length - 1)\n\n        # Unable to handle range request - Send the valid range with status code 416\n        if (start < 0) or (end >= req.gridFS.length) or (start > end) or isNaN(start) or isNaN(end)\n          headers['Content-Range'] = 'bytes ' + '*/' + req.gridFS.length\n          res.writeHead 416, headers\n          res.end()\n          return\n\n        # Determine the chunk size\n        chunksize = (end - start) + 1\n\n        # Construct the range request header\n        headers['Content-Range'] = 'bytes ' + start + '-' + end + '/' + req.gridFS.length\n        headers['Accept-Ranges'] = 'bytes'\n        headers['Content-Type'] = req.gridFS.contentType\n        headers['Content-Length'] = chunksize\n        headers['Last-Modified'] = req.gridFS.uploadDate.toUTCString()\n\n        # Read the partial request from gridfs stream\n        unless req.method is 'HEAD'\n           stream = @findOneStream(\n             _id: req.gridFS._id\n           ,\n             range:\n               start: start\n               end: end\n           )\n\n      # Otherwise prepare to stream the whole file\n      else\n        # Set default status code\n        statusCode = 200\n\n        # Set default headers\n        headers['Content-Type'] = req.gridFS.contentType\n        headers['Content-MD5'] = req.gridFS.md5\n        headers['Content-Length'] = req.gridFS.length\n        headers['Last-Modified'] = req.gridFS.uploadDate.toUTCString()\n\n        # Open file to stream\n        unless req.method is 'HEAD'\n           stream = @findOneStream { _id: req.gridFS._id }\n\n      # Trigger download in browser, optionally specify filename.\n      if (req.query.download and req.query.download.toLowerCase() == 'true') or req.query.filename\n        filename = encodeURIComponent(req.query.filename ? req.gridFS.filename)\n        headers['Content-Disposition'] = \"attachment; filename=\\\"#{filename}\\\"; filename*=UTF-8''#{filename}\"\n\n      # If specified in url query set cache to specified value, might want to add more options later.\n      if req.query.cache and not isNaN(parseInt(req.query.cache))\n        headers['Cache-Control'] = \"max-age=\" + parseInt(req.query.cache)+\", private\"\n\n      # HEADs don't have a body\n      if req.method is 'HEAD'\n        res.writeHead 204, headers\n        res.end()\n        return\n\n      # Stream file\n      if stream\n         res.writeHead statusCode, headers\n         stream.pipe(res)\n            .on 'close', () ->\n               res.end()\n            .on 'error', (err) ->\n               res.writeHead(500, share.defaultResponseHeaders)\n               res.end(err)\n      else\n         res.writeHead(410, share.defaultResponseHeaders)\n         res.end()\n\n   # Handle a generic HTTP PUT request\n\n   # This curl command should be properly handled by this code:\n   # % curl -X PUT 'http://127.0.0.1:3000/gridfs/fs/7868f3df8425ae68a572b334' \\\n   #        -T \"universe.png\" -H 'Content-Type: image/png' -H 'X-Auth-Token: tEPAwXbGwgfGiJL35'\n\n   put = (req, res, next) ->\n\n      # Handle content type if it's present\n      if req.headers['content-type']\n         req.gridFS.contentType = req.headers['content-type']\n\n      # Write the file\n      stream = @upsertStream req.gridFS\n      if stream\n         req.pipe(share.streamChunker(@chunkSize)).pipe(stream)\n            .on 'close', (retFile) ->\n               if retFile\n                  res.writeHead(200, share.defaultResponseHeaders)\n                  res.end()\n               else\n            .on 'error', (err) ->\n               res.writeHead(500, share.defaultResponseHeaders)\n               res.end(err)\n      else\n         res.writeHead(404, share.defaultResponseHeaders)\n         res.end(\"#{req.url} Not found!\")\n\n   # Handle a generic HTTP DELETE request\n\n   # This curl command should be properly handled by this code:\n   # % curl -X DELETE 'http://127.0.0.1:3000/gridfs/fs/7868f3df8425ae68a572b334' \\\n   #        -H 'X-Auth-Token: tEPAwXbGwgfGiJL35'\n\n   del = (req, res, next) ->\n\n      @remove req.gridFS\n      res.writeHead(204, share.defaultResponseHeaders)\n      res.end()\n\n   # Setup all of the application specified paths and file lookups in express\n   # Also performs allow/deny permission checks for POST/PUT/DELETE\n\n   build_access_point = (http) ->\n\n      # Loop over the app supplied http paths\n      for r in http\n\n         if r.method.toUpperCase() is 'POST'\n            @router.post r.path, dice_multipart\n\n         # Add an express middleware for each application REST path\n         @router[r.method] r.path, do (r) =>\n\n            (req, res, next) =>\n\n               # params and queries literally named \"_id\" get converted to ObjectIDs automatically\n               req.params._id = share.safeObjectID(req.params._id) if req.params?._id?\n               req.query._id = share.safeObjectID(req.query._id) if req.query?._id?\n\n               # Build the path lookup mongoDB query object for the gridFS files collection\n               lookup = r.lookup?.bind(@)(req.params or {}, req.query or {}, req.multipart)\n               unless lookup?\n                  # No lookup returned, so bailing\n                  res.writeHead(500, share.defaultResponseHeaders)\n                  res.end()\n                  return\n               else\n                  # Perform the collection query\n                  req.gridFS = @findOne lookup\n                  unless req.gridFS\n                     res.writeHead(404, share.defaultResponseHeaders)\n                     res.end()\n                     return\n\n                  # Make sure that the requested method is permitted for this file in the allow/deny rules\n                  switch req.method\n                     when 'HEAD', 'GET'\n                        unless share.check_allow_deny.bind(@) 'read', req.meteorUserId, req.gridFS\n                           res.writeHead(403, share.defaultResponseHeaders)\n                           res.end()\n                           return\n                     when 'POST', 'PUT'\n                        req.maxUploadSize = @maxUploadSize\n                        unless opts = share.check_allow_deny.bind(@) 'write', req.meteorUserId, req.gridFS\n                           res.writeHead(403, share.defaultResponseHeaders)\n                           res.end()\n                           return\n                        if opts.maxUploadSize? and typeof opts.maxUploadSize is 'number'\n                           req.maxUploadSize = opts.maxUploadSize\n                        if req.maxUploadSize > 0\n                           unless req.headers['content-length']?\n                              res.writeHead(411, share.defaultResponseHeaders)\n                              res.end()\n                              return\n                           unless parseInt(req.headers['content-length']) <= req.maxUploadSize\n                              res.writeHead(413, share.defaultResponseHeaders)\n                              res.end()\n                              return\n                     when 'DELETE'\n                        unless share.check_allow_deny.bind(@) 'remove', req.meteorUserId, req.gridFS\n                           res.writeHead(403, share.defaultResponseHeaders)\n                           res.end()\n                           return\n                     when 'OPTIONS'  # Should there be a permission for options?\n                        unless (share.check_allow_deny.bind(@)('read', req.meteorUserId, req.gridFS) or\n                                share.check_allow_deny.bind(@)('write', req.meteorUserId, req.gridFS) or\n                                share.check_allow_deny.bind(@)('remove', req.meteorUserId, req.gridFS))\n                           res.writeHead(403, share.defaultResponseHeaders)\n                           res.end()\n                           return\n                     else\n                        res.writeHead(500, share.defaultResponseHeaders)\n                        res.end()\n                        return\n\n                  next()\n\n         # Add an express middleware for each custom request handler\n         if typeof r.handler is 'function'\n            @router[r.method] r.path, r.handler.bind(@)\n\n      # Add all of generic request handling methods to the express route\n      @router.route('/*')\n         .all (req, res, next) ->   # There needs to be a valid req.gridFS object here\n            if req.gridFS?\n               next()\n               return\n            else\n               res.writeHead(404, share.defaultResponseHeaders)\n               res.end()\n         .head(get.bind(@))   # Generic HTTP method handlers\n         .get(get.bind(@))\n         .put(put.bind(@))\n         .post(post.bind(@))\n         .delete(del.bind(@))\n         .all (req, res, next) ->   # Unkown methods are denied\n            res.writeHead(500, share.defaultResponseHeaders)\n            res.end()\n\n   # Performs a meteor userId lookup by hased access token\n\n   lookup_userId_by_token = (authToken) ->\n      userDoc = Meteor.users?.findOne\n         'services.resume.loginTokens':\n            $elemMatch:\n               hashedToken: Accounts?._hashLoginToken(authToken)\n      return userDoc?._id or null\n\n   # Express middleware to convert a Meteor access token provided in an HTTP request\n   # to a Meteor userId attached to the request object as req.meteorUserId\n\n   handle_auth = (req, res, next) ->\n      unless req.meteorUserId?\n         # Lookup userId if token is provided in HTTP heder\n         if req.headers?['x-auth-token']?\n            req.meteorUserId = lookup_userId_by_token req.headers['x-auth-token']\n         # Or as a URL query of the same name\n         else if req.cookies?['X-Auth-Token']?\n            req.meteorUserId = lookup_userId_by_token req.cookies['X-Auth-Token']\n         else\n            req.meteorUserId = null\n      next()\n\n   # Set up all of the middleware, including optional support for Resumable.js chunked uploads\n   share.setupHttpAccess = (options) ->\n\n      # Set up support for resumable.js if requested\n      if options.resumable\n         options.http = [] unless options.http?\n         resumableHandlers = []\n         otherHandlers = []\n         for h in options.http\n            if h.path is share.resumableBase\n               resumableHandlers.push h\n            else\n               otherHandlers.push h\n         resumableHandlers = resumableHandlers.concat share.resumablePaths\n         options.http = resumableHandlers.concat otherHandlers\n\n      # Don't setup any middleware unless there are routes defined\n      if options.http?.length > 0\n         r = express.Router()\n         r.use express.query()   # Parse URL query strings\n         r.use cookieParser()    # Parse cookies\n         r.use handle_auth       # Turn x-auth-tokens into Meteor userIds\n         WebApp.rawConnectHandlers.use(@baseURL, share.bind_env(r))\n\n         # Setup application HTTP REST interface\n         @router = express.Router()\n         build_access_point.bind(@)(options.http, @router)\n         WebApp.rawConnectHandlers.use(@baseURL, share.bind_env(@router))\n"
  },
  {
    "path": "src/resumable_client.coffee",
    "content": "############################################################################\n#     Copyright (C) 2014-2017 by Vaughn Iverson\n#     fileCollection is free software released under the MIT/X11 license.\n#     See included LICENSE file for details.\n############################################################################\n\nif Meteor.isClient\n\n   # This is a polyfill for bind(), added to make phantomjs 1.9.7 work\n   unless Function.prototype.bind\n      Function.prototype.bind = (oThis) ->\n         if typeof this isnt \"function\"\n            # closest thing possible to the ECMAScript 5 internal IsCallable function\n            throw new TypeError(\"Function.prototype.bind - what is trying to be bound is not callable\")\n\n         aArgs = Array.prototype.slice.call arguments, 1\n         fToBind = this\n         fNOP = () ->\n         fBound = () ->\n            func = if (this instanceof fNOP and oThis) then this else oThis\n            return fToBind.apply(func, aArgs.concat(Array.prototype.slice.call(arguments)))\n\n         fNOP.prototype = this.prototype\n\n         fBound.prototype = new fNOP()\n         return fBound\n\n   share.setup_resumable = () ->\n      url = \"#{@baseURL}#{share.resumableBase}\"\n      url = Meteor.absoluteUrl(url.replace /^\\//, '') if Meteor.isCordova\n      r = new Resumable\n         target: url\n         generateUniqueIdentifier: (file) -> \"#{new Mongo.ObjectID()}\"\n         fileParameterName: 'file'\n         chunkSize: @chunkSize\n         testChunks: true\n         testMethod: 'HEAD'\n         permanentErrors: [204, 404, 415, 500, 501]\n         simultaneousUploads: 3\n         maxFiles: undefined\n         maxFilesErrorCallback: undefined\n         prioritizeFirstAndLastChunk: false\n         query: undefined\n         headers: {}\n         maxChunkRetries: 5\n         withCredentials: true\n\n      unless r.support\n         console.warn \"resumable.js not supported by this Browser, uploads will be disabled\"\n         @resumable = null\n      else\n         @resumable = r\n"
  },
  {
    "path": "src/resumable_server.coffee",
    "content": "############################################################################\n#     Copyright (C) 2014-2017 by Vaughn Iverson\n#     fileCollection is free software released under the MIT/X11 license.\n#     See included LICENSE file for details.\n############################################################################\n\nif Meteor.isServer\n\n   express = Npm.require 'express'\n   mongodb = Npm.require 'mongodb'\n   grid = Npm.require 'gridfs-locking-stream'\n   gridLocks = Npm.require 'gridfs-locks'\n   dicer = Npm.require 'dicer'\n   async = Npm.require 'async'\n\n   # This function checks to see if all of the parts of a Resumable.js uploaded file are now in the gridFS\n   # Collection. If so, it completes the file by moving all of the chunks to the correct file and cleans up\n\n   check_order = (file, callback) ->\n      fileId = mongodb.ObjectID(\"#{file.metadata._Resumable.resumableIdentifier}\")\n      lock = gridLocks.Lock(fileId, @locks, {}).obtainWriteLock()\n      lock.on 'locked', () =>\n\n         files = @db.collection \"#{@root}.files\"\n\n         cursor = files.find(\n            {\n               'metadata._Resumable.resumableIdentifier': file.metadata._Resumable.resumableIdentifier\n               length:\n                  $ne: 0\n            },\n            {\n               fields:\n                  length: 1\n                  metadata: 1\n               sort:\n                  'metadata._Resumable.resumableChunkNumber': 1\n            }\n         )\n\n         cursor.count (err, count) =>\n            if err\n               lock.releaseLock()\n               return callback err\n\n            unless count >= 1\n               cursor.close()\n               lock.releaseLock()\n               return callback()\n\n            unless count is file.metadata._Resumable.resumableTotalChunks\n               cursor.close()\n               lock.releaseLock()\n               return callback()\n\n            # Manipulate the chunks and files collections directly under write lock\n            chunks = @db.collection \"#{@root}.chunks\"\n\n            cursor.batchSize file.metadata._Resumable.resumableTotalChunks + 1\n\n            cursor.toArray (err, parts) =>\n\n               if err\n                  lock.releaseLock()\n                  return callback err\n\n               async.eachLimit parts, 5,\n                  (part, cb) =>\n                     if err\n                        console.error \"Error from cursor.next()\", err\n                        cb err\n                     return cb new Meteor.Error \"Received null part\" unless part\n                     partId = mongodb.ObjectID(\"#{part._id}\")\n                     partlock = gridLocks.Lock(partId, @locks, {}).obtainWriteLock()\n                     partlock.on 'locked', () =>\n                        async.series [\n                              # Move the chunks to the correct file\n                              (cb) -> chunks.update { files_id: partId, n: 0 },\n                                 { $set: { files_id: fileId, n: part.metadata._Resumable.resumableChunkNumber - 1 }}\n                                 cb\n                              # Delete the temporary chunk file documents\n                              (cb) -> files.remove { _id: partId }, cb\n                           ],\n                           (err, res) =>\n                              return cb err if err\n                              unless part.metadata._Resumable.resumableChunkNumber is part.metadata._Resumable.resumableTotalChunks\n                                 partlock.removeLock()\n                                 cb()\n                              else\n                                 # check for a final hanging gridfs chunk\n                                 chunks.update { files_id: partId, n: 1 },\n                                    { $set: { files_id: fileId, n: part.metadata._Resumable.resumableChunkNumber }}\n                                    (err, res) ->\n                                       partlock.removeLock()\n                                       return cb err if err\n                                       cb()\n                     partlock.on 'timed-out', () -> cb new Meteor.Error 'Partlock timed out!'\n                     partlock.on 'expired', () -> cb new Meteor.Error 'Partlock expired!'\n                     partlock.on 'error', (err) ->\n                        console.error \"Error obtaining partlock #{part._id}\", err\n                        cb err\n                  (err) =>\n                     if err\n                        lock.releaseLock()\n                        return callback err\n                     # Build up the command for the md5 hash calculation\n                     md5Command =\n                       filemd5: fileId\n                       root: \"#{@root}\"\n                     # Send the command to calculate the md5 hash of the file\n                     @db.command md5Command, (err, results) ->\n                       if err\n                          lock.releaseLock()\n                          return callback err\n                       # Update the size and md5 to the file data\n                       files.update { _id: fileId }, { $set: { length: file.metadata._Resumable.resumableTotalSize, md5: results.md5 }},\n                          (err, res) =>\n                             lock.releaseLock()\n                             callback err\n\n      lock.on 'expires-soon', () ->\n         lock.renewLock().once 'renewed', (ld) ->\n            unless ld\n               console.warn \"Resumable upload lock renewal failed!\"\n      lock.on 'expired', () -> callback new Meteor.Error \"File Lock expired\"\n      lock.on 'timed-out', () -> callback new Meteor.Error \"File Lock timed out\"\n      lock.on 'error', (err) -> callback err\n\n   # Handle HTTP POST requests from Resumable.js\n\n   resumable_post_lookup = (params, query, multipart) ->\n      return { _id: share.safeObjectID(multipart?.params?.resumableIdentifier) }\n\n   resumable_post_handler = (req, res, next) ->\n\n      # This has to be a resumable POST\n      unless req.multipart?.params?.resumableIdentifier\n         console.error \"Missing resumable.js multipart information\"\n         res.writeHead(501, share.defaultResponseHeaders)\n         res.end()\n         return\n\n      resumable = req.multipart.params\n      resumable.resumableTotalSize = parseInt resumable.resumableTotalSize\n      resumable.resumableTotalChunks = parseInt resumable.resumableTotalChunks\n      resumable.resumableChunkNumber = parseInt resumable.resumableChunkNumber\n      resumable.resumableChunkSize = parseInt resumable.resumableChunkSize\n      resumable.resumableCurrentChunkSize = parseInt resumable.resumableCurrentChunkSize\n\n      if req.maxUploadSize > 0\n         unless resumable.resumableTotalSize <= req.maxUploadSize\n            res.writeHead(413, share.defaultResponseHeaders)\n            res.end()\n            return\n\n      # Sanity check the chunk sizes that are critical to reassembling the file from parts\n      unless ((req.gridFS.chunkSize is resumable.resumableChunkSize) and\n              (resumable.resumableChunkNumber <= resumable.resumableTotalChunks) and\n              (resumable.resumableTotalSize/resumable.resumableChunkSize <= resumable.resumableTotalChunks+1) and\n              (resumable.resumableCurrentChunkSize is resumable.resumableChunkSize) or\n              ((resumable.resumableChunkNumber is resumable.resumableTotalChunks) and\n               (resumable.resumableCurrentChunkSize < 2*resumable.resumableChunkSize)))\n\n         res.writeHead(501, share.defaultResponseHeaders)\n         res.end()\n         return\n\n      chunkQuery =\n         length: resumable.resumableCurrentChunkSize\n         'metadata._Resumable.resumableIdentifier': resumable.resumableIdentifier\n         'metadata._Resumable.resumableChunkNumber': resumable.resumableChunkNumber\n\n      # This is to handle duplicate chunk uploads in case of network weirdness\n      findResult = @findOne chunkQuery, { fields: { _id: 1 }}\n\n      if findResult\n         # Duplicate chunk... Don't rewrite it.\n         # console.warn \"Duplicate chunk detected: #{resumable.resumableChunkNumber}, #{resumable.resumableIdentifier}\"\n         res.writeHead(200, share.defaultResponseHeaders)\n         res.end()\n      else\n         # Everything looks good, so write this part\n         req.gridFS.metadata._Resumable = resumable\n         writeStream = @upsertStream\n            filename: \"_Resumable_#{resumable.resumableIdentifier}_#{resumable.resumableChunkNumber}_#{resumable.resumableTotalChunks}\"\n            metadata: req.gridFS.metadata\n\n         unless writeStream\n            res.writeHead(404, share.defaultResponseHeaders)\n            res.end()\n            return\n\n         req.multipart.fileStream.pipe(share.streamChunker(@chunkSize)).pipe(writeStream)\n            .on 'close', share.bind_env((retFile) =>\n               if retFile\n                  # Check to see if all of the parts are now available and can be reassembled\n                  check_order.bind(@)(req.gridFS, (err) ->\n                     if err\n                        console.error \"Error reassembling chunks of resumable.js upload\", err\n                        res.writeHead(500, share.defaultResponseHeaders)\n                     else\n                        res.writeHead(200, share.defaultResponseHeaders)\n                     res.end()\n                  )\n               else\n                  console.error \"Missing retFile on pipe close\"\n                  res.writeHead(500, share.defaultResponseHeaders)\n                  res.end()\n               )\n\n            .on 'error', share.bind_env((err) =>\n               console.error \"Piping Error!\", err\n               res.writeHead(500, share.defaultResponseHeaders)\n               res.end())\n\n   resumable_get_lookup = (params, query) ->\n      q = { _id: share.safeObjectID(query.resumableIdentifier) }\n      return q\n\n   # This handles Resumable.js \"test GET\" requests, that exist to determine\n   # if a part is already uploaded. It also handles HEAD requests, which\n   # should be a bit more efficient and resumable.js now supports\n   resumable_get_handler = (req, res, next) ->\n      query = req.query\n      chunkQuery =\n         $or: [\n            {\n               _id: share.safeObjectID(query.resumableIdentifier)\n               length: parseInt query.resumableTotalSize\n            }\n            {\n               length: parseInt query.resumableCurrentChunkSize\n               'metadata._Resumable.resumableIdentifier': query.resumableIdentifier\n               'metadata._Resumable.resumableChunkNumber': parseInt query.resumableChunkNumber\n            }\n         ]\n\n      result = @findOne chunkQuery, { fields: { _id: 1 }}\n      if result\n         # Chunk is present\n         res.writeHead(200, share.defaultResponseHeaders)\n      else\n         # Chunk is missing\n         res.writeHead(204, share.defaultResponseHeaders)\n\n      res.end()\n\n   # Setup the GET and POST HTTP REST paths for Resumable.js in express\n   share.resumablePaths = [\n      {\n         method: 'head'\n         path: share.resumableBase\n         lookup: resumable_get_lookup\n         handler: resumable_get_handler\n      }\n      {\n         method: 'post'\n         path: share.resumableBase\n         lookup: resumable_post_lookup\n         handler: resumable_post_handler\n      }\n      {\n         method: 'get'\n         path: share.resumableBase\n         lookup: resumable_get_lookup\n         handler: resumable_get_handler\n      }\n   ]\n"
  },
  {
    "path": "src/server_shared.coffee",
    "content": "############################################################################\n#     Copyright (C) 2014-2017 by Vaughn Iverson\n#     fileCollection is free software released under the MIT/X11 license.\n#     See included LICENSE file for details.\n############################################################################\n\nif Meteor.isServer\n\n   through2 = Npm.require 'through2'\n\n   share.defaultResponseHeaders =\n      'Content-Type': 'text/plain'\n\n   share.check_allow_deny = (type, userId, file, fields) ->\n\n      checkRules = (rules) ->\n         res = false\n         for func in rules[type] when not res\n            res = func(userId, file, fields)\n         return res\n\n      result = not checkRules(@denys) and checkRules(@allows)\n      return result\n\n   share.bind_env = (func) ->\n      if func?\n         return Meteor.bindEnvironment func, (err) -> throw err\n      else\n         return func\n\n   share.safeObjectID = (s) ->\n      if s?.match /^[0-9a-f]{24}$/i  # Validate that _id is a 12 byte hex string\n         new Mongo.ObjectID s\n      else\n         null\n\n   share.streamChunker = (size = share.defaultChunkSize) ->\n      makeFuncs = (size) ->\n         bufferList = [ new Buffer(0) ]\n         total = 0\n         flush = (cb) ->\n            outSize = if total > size then size else total\n            if outSize > 0\n               outputBuffer = Buffer.concat bufferList, outSize\n               this.push outputBuffer\n               total -= outSize\n            lastBuffer = bufferList.pop()\n            newBuffer = lastBuffer.slice(lastBuffer.length - total)\n            bufferList = [ newBuffer ]\n            if total < size\n               cb()\n            else\n               flush.bind(this) cb\n         transform = (chunk, enc, cb) ->\n            bufferList.push chunk\n            total += chunk.length\n            if total < size\n               cb()\n            else\n               flush.bind(this) cb\n         return [transform, flush]\n      return through2.apply this, makeFuncs(size)\n"
  },
  {
    "path": "test/file_collection_tests.coffee",
    "content": "############################################################################\n#     Copyright (C) 2014-2017 by Vaughn Iverson\n#     fileCollection is free software released under the MIT/X11 license.\n#     See included LICENSE file for details.\n############################################################################\n\nif Meteor.isServer\n  os = Npm.require 'os'\n  path = Npm.require 'path'\n\nbind_env = (func) ->\n  if typeof func is 'function'\n    return Meteor.bindEnvironment func, (err) -> throw err\n  else\n    return func\n\nsubWrapper = (sub, func) ->\n  (test, onComplete) ->\n    if Meteor.isClient\n      Tracker.autorun () ->\n        if sub.ready()\n          func test, onComplete\n    else\n      func test, onComplete\n\ndefaultColl = new FileCollection()\n\nTinytest.add 'FileCollection default constructor', (test) ->\n  test.instanceOf defaultColl, FileCollection, \"FileCollection constructor failed\"\n  test.equal defaultColl.root, 'fs', \"default root isn't 'fs'\"\n  test.equal defaultColl.chunkSize, 2*1024*1024 - 1024, \"bad default chunksize\"\n  test.equal defaultColl.baseURL, \"/gridfs/fs\", \"bad default base URL\"\n\nidLookup = (params, query) ->\n   return { _id: params._id }\n\nlongString = ''\nwhile longString.length < 4096\n   longString += '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'\n\ntestColl = new FileCollection \"test\",\n  baseURL: \"/test\"\n  chunkSize: 16\n  resumable: true\n  maxUploadSize: 2048\n  http: [\n     { method: 'get', path: '/:_id', lookup: idLookup}\n     { method: 'post', path: '/:_id', lookup: idLookup}\n     { method: 'put', path: '/:_id', lookup: idLookup}\n     { method: 'delete', path: '/:_id', lookup: idLookup}\n     { method: 'options', path: '/:_id', lookup: idLookup, handler: (req, res, next) ->\n          res.writeHead(200, { 'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': 'http://meteor.local' })\n          res.end()\n          return\n     }\n  ]\n\nnoReadColl = new FileCollection \"noReadColl\",\n  baseURL: \"/noread\"\n  chunkSize: 1024*1024\n  resumable: false\n  http: [\n     { method: 'get', path: '/:_id', lookup: idLookup}\n     { method: 'post', path: '/:_id', lookup: idLookup}\n     { method: 'put', path: '/:_id', lookup: idLookup}\n     { method: 'delete', path: '/:_id', lookup: idLookup}\n  ]\n\nnoAllowColl = new FileCollection \"noAllowColl\"\ndenyColl = new FileCollection \"denyColl\"\n\nMeteor.methods\n  updateTest: (id, reject) ->\n    check id, Mongo.ObjectID\n    check reject, Boolean\n    if this.isSimulation\n      testColl.localUpdate { _id: id }, { $set: { 'metadata.test2': true } }\n    else if reject\n      throw new Meteor.Error \"Rejected by server\"\n    else\n      testColl.update { _id: id }, { $set: { 'metadata.test2': false } }\n\nif Meteor.isServer\n\n  Meteor.publish 'everything', () -> testColl.find {}\n  Meteor.publish 'noAllowCollPub', () -> noAllowColl.find {}\n  Meteor.publish 'noReadCollPub', () -> noReadColl.find {}\n  Meteor.publish 'denyCollPub', () -> denyColl.find {}\n\n  sub = null\n\n  testColl.allow\n    insert: () -> true\n    write: () -> true\n    remove: () -> true\n    read: () -> true\n\n  testColl.deny\n    insert: () -> false\n    write: () -> false\n    remove: () -> false\n    read: () -> false\n\n  noAllowColl.allow\n    read: () -> false\n    insert: () -> false\n    write: () -> false\n    remove: () -> false\n\n  noReadColl.allow\n    read: () -> false\n    insert: () -> true\n    write: () -> { maxUploadSize: 15 }\n    remove: () -> true\n\n  noReadColl.deny\n    read: () -> false\n    insert: () -> false\n    write: () -> false\n    remove: () -> false\n\n  denyColl.deny\n    read: () -> true\n    insert: () -> true\n    write: () -> true\n    remove: () -> true\n\n  Tinytest.add 'set allow/deny on FileCollection', (test) ->\n    test.equal testColl.allows.read[0](), true\n    test.equal testColl.allows.insert[0](), true\n    test.equal testColl.allows.remove[0](), true\n    test.equal testColl.allows.write[0](), true\n    test.equal testColl.denys.read[0](), false\n    test.equal testColl.denys.write[0](), false\n    test.equal testColl.denys.insert[0](), false\n    test.equal testColl.denys.remove[0](), false\n\n  Tinytest.add 'check server REST API', (test) ->\n    test.equal typeof testColl.router, 'function'\n\nif Meteor.isClient\n  sub = Meteor.subscribe 'everything'\n\n  Tinytest.add 'Server-only methods throw on client', (test) ->\n    test.throws () -> testColl.allow({})\n    test.throws () -> testColl.deny({})\n    test.throws () -> testColl.upsert({})\n    test.throws () -> testColl.update({})\n    test.throws () -> testColl.findOneStream({})\n    test.throws () -> testColl.upsertStream({})\n    test.throws () -> testColl.importFile({})\n    test.throws () -> testColl.exportFile({})\n\nTinytest.add 'FileCollection constructor with options', (test) ->\n  test.instanceOf testColl, FileCollection, \"FileCollection constructor failed\"\n  test.equal testColl.root, 'test', \"root collection not properly set\"\n  test.equal testColl.chunkSize, 16, \"chunkSize not set properly\"\n  test.equal testColl.baseURL, \"/test\", \"base URL not set properly\"\n\nTinytest.add 'FileCollection insert, findOne and remove', (test) ->\n  _id = testColl.insert {}\n  test.isNotNull _id, \"No _id returned by insert\"\n  test.instanceOf _id, Mongo.ObjectID\n  file = testColl.findOne {_id : _id}\n  test.isNotNull file, \"Invalid file returned by findOne\"\n  test.equal typeof file, \"object\"\n  test.equal file.length, 0\n  test.equal file.md5, 'd41d8cd98f00b204e9800998ecf8427e'\n  test.instanceOf file.uploadDate, Date\n  test.equal file.chunkSize, 16\n  test.equal file.filename, ''\n  test.equal typeof file.metadata, \"object\"\n  test.instanceOf file.aliases, Array\n  test.equal file.contentType, 'application/octet-stream'\n  result = testColl.remove {_id : _id}\n  test.equal result, 1, \"Incorrect number of files removed\"\n  file = testColl.findOne {_id : _id}\n  test.isUndefined file, \"File was not removed\"\n\nTinytest.addAsync 'FileCollection insert, findOne and remove with callback', subWrapper(sub, (test, onComplete) ->\n  _id = testColl.insert {}, (err, retid) ->\n    test.fail(err) if err\n    test.isNotNull _id, \"No _id returned by insert\"\n    test.isNotNull retid, \"No _id returned by insert callback\"\n    test.instanceOf _id, Mongo.ObjectID, \"_id is wrong type\"\n    test.instanceOf retid, Mongo.ObjectID, \"retid is wrong type\"\n    test.equal _id, retid, \"different ids returned in return and callback\"\n    file = testColl.findOne {_id : retid}\n    test.isNotNull file, \"Invalid file returned by findOne\"\n    test.equal typeof file, \"object\"\n    test.equal file.length, 0\n    test.equal file.md5, 'd41d8cd98f00b204e9800998ecf8427e'\n    test.instanceOf file.uploadDate, Date\n    test.equal file.chunkSize, 16\n    test.equal file.filename, ''\n    test.equal typeof file.metadata, \"object\"\n    test.instanceOf file.aliases, Array\n    test.equal file.contentType, 'application/octet-stream'\n    finishCount = 0\n    finish = () ->\n      finishCount++\n      if finishCount > 1\n         onComplete()\n    obs = testColl.find({_id : _id}).observeChanges\n       removed: (id) ->\n          obs.stop()\n          test.ok EJSON.equals(id, _id), 'Incorrect file _id removed'\n          finish()\n    testColl.remove {_id : retid}, (err, result) ->\n      test.fail(err) if err\n      test.equal result, 1, \"Incorrect number of files removed\"\n      finish()\n)\n\nTinytest.add 'FileCollection insert and find with options', (test) ->\n  _id = testColl.insert { filename: 'testfile', metadata: { x: 1 }, aliases: [\"foo\"], contentType: 'text/plain' }\n  test.isNotNull _id, \"No _id returned by insert\"\n  test.instanceOf _id, Meteor.Collection.ObjectID\n  file = testColl.findOne {_id : _id}\n  test.isNotNull file, \"Invalid file returned by findOne\"\n  test.equal typeof file, \"object\"\n  test.equal file.length, 0\n  test.equal file.md5, 'd41d8cd98f00b204e9800998ecf8427e'\n  test.instanceOf file.uploadDate, Date\n  test.equal file.chunkSize, 16\n  test.equal file.filename, 'testfile'\n  test.equal typeof file.metadata, \"object\"\n  test.equal file.metadata.x, 1\n  test.instanceOf file.aliases, Array\n  test.equal file.aliases[0], 'foo'\n  test.equal file.contentType, 'text/plain'\n\nTinytest.addAsync 'FileCollection insert and find with options in callback', subWrapper(sub, (test, onComplete) ->\n  _id = testColl.insert { filename: 'testfile', metadata: { x: 1 }, aliases: [\"foo\"], contentType: 'text/plain' }, (err, retid) ->\n    test.fail(err) if err\n    test.isNotNull _id, \"No _id returned by insert\"\n    test.isNotNull retid, \"No _id returned by insert callback\"\n    test.instanceOf _id, Mongo.ObjectID, \"_id is wrong type\"\n    test.instanceOf retid, Mongo.ObjectID, \"retid is wrong type\"\n    test.equal _id, retid, \"different ids returned in return and callback\"\n    file = testColl.findOne {_id : retid}\n    test.isNotNull file, \"Invalid file returned by findOne\"\n    test.equal typeof file, \"object\"\n    test.equal file.length, 0\n    test.equal file.md5, 'd41d8cd98f00b204e9800998ecf8427e'\n    test.instanceOf file.uploadDate, Date\n    test.equal file.chunkSize, 16\n    test.equal file.filename, 'testfile'\n    test.equal typeof file.metadata, \"object\"\n    test.equal file.metadata.x, 1\n    test.instanceOf file.aliases, Array\n    test.equal file.aliases[0], 'foo'\n    test.equal file.contentType, 'text/plain'\n    onComplete()\n)\n\nif Meteor.isServer\n\n  Tinytest.addAsync 'Proper error handling for missing file on import',\n    (test, onComplete) ->\n      bogusfile = \"/bogus/file.not\"\n      testColl.importFile bogusfile, {}, bind_env (err, doc) ->\n         test.fail(err) unless err\n         onComplete()\n\n  Tinytest.addAsync 'Server accepts good and rejects bad updates', (test, onComplete) ->\n    _id = testColl.insert()\n    testColl.update _id, { $set: { \"metadata.test\": 1 } }, (err, res) ->\n      test.fail(err) if err\n      test.equal res, 1\n      testColl.update _id, { $inc: { \"metadata.test\": 1 } }, (err, res) ->\n        test.fail(err) if err\n        test.equal res, 1\n        doc = testColl.findOne _id\n        test.equal doc.metadata.test, 2\n        testColl.update _id, { $set: { md5: 1 } }, (err, res) ->\n          test.isUndefined res\n          test.instanceOf err, Meteor.Error\n          testColl.update _id, { $unset: { filename: 1 } }, (err, res) ->\n            test.isUndefined res\n            test.instanceOf err, Meteor.Error\n            testColl.update _id, { foo: \"bar\" }, (err, res) ->\n              test.isUndefined res\n              test.instanceOf err, Meteor.Error\n              onComplete()\n\n  Tinytest.addAsync 'Insert and then Upsert stream to gridfs and read back, write to file system, and re-import',\n    (test, onComplete) ->\n      _id = testColl.insert { filename: 'writefile', contentType: 'text/plain' }, (err, _id) ->\n        test.fail(err) if err\n        writestream = testColl.upsertStream { _id: _id }\n        writestream.on 'close', bind_env (file) ->\n          test.equal typeof file, 'object', \"Bad file object after upsert stream\"\n          test.equal file.length, 10, \"Improper file length\"\n          test.equal file.md5, 'e807f1fcf82d132f9bb018ca6738a19f', \"Improper file md5 hash\"\n          test.equal file.contentType, 'text/plain', \"Improper contentType\"\n          test.equal typeof file._id, 'object'\n          test.equal _id, new Mongo.ObjectID file._id.toHexString()\n          readstream = testColl.findOneStream {_id: file._id }\n          readstream.on 'data', bind_env (chunk) ->\n            test.equal chunk.toString(), '1234567890','Incorrect data read back from stream'\n          readstream.on 'end', bind_env () ->\n            testfile = path.join os.tmpdir(), \"/FileCollection.\" + file._id + \".test\"\n            testColl.exportFile file, testfile, bind_env (err, doc) ->\n              test.fail(err) if err\n              testColl.importFile testfile, {}, bind_env (err, doc) ->\n                test.fail(err) if err\n                test.equal typeof doc, 'object', \"No document imported\"\n                if typeof doc == 'object'\n                  readstream = testColl.findOneStream {_id: doc._id }\n                  readstream.on 'data', bind_env (chunk) ->\n                    test.equal chunk.toString(), '1234567890','Incorrect data read back from file stream'\n                  readstream.on 'end', bind_env () ->\n                    onComplete()\n                else\n                  onComplete()\n        writestream.write '1234567890'\n        writestream.end()\n\n  Tinytest.addAsync 'Just Upsert stream to gridfs and read back, write to file system, and re-import',\n    (test, onComplete) ->\n      writestream = testColl.upsertStream { filename: 'writefile', contentType: 'text/plain' }, bind_env (err, file) ->\n        test.equal typeof file, 'object', \"Bad file object after upsert stream\"\n        test.equal file.length, 10, \"Improper file length\"\n        test.equal file.md5, 'e46c309de99c3dfbd6acd9e77751ae98', \"Improper file md5 hash\"\n        test.equal file.contentType, 'text/plain', \"Improper contentType\"\n        test.equal typeof file._id, 'object'\n        test.instanceOf file._id, Mongo.ObjectID, \"_id is wrong type\"\n        readstream = testColl.findOneStream {_id: file._id }\n        readstream.on 'data', bind_env (chunk) ->\n          test.equal chunk.toString(), 'ZYXWVUTSRQ','Incorrect data read back from stream'\n        readstream.on 'end', bind_env () ->\n          testfile = path.join os.tmpdir(), \"/FileCollection.\" + file._id + \".test\"\n          testColl.exportFile file, testfile, bind_env (err, doc) ->\n            test.fail(err) if err\n            testColl.importFile testfile, {}, bind_env (err, doc) ->\n              test.fail(err) if err\n              test.equal typeof doc, 'object', \"No document imported\"\n              if typeof doc == 'object'\n                readstream = testColl.findOneStream {_id: doc._id }\n                readstream.on 'data', bind_env (chunk) ->\n                  test.equal chunk.toString(), 'ZYXWVUTSRQ','Incorrect data read back from file stream'\n                readstream.on 'end', bind_env () ->\n                  onComplete()\n              else\n                onComplete()\n      writestream.write 'ZYXWVUTSRQ'\n      writestream.end()\n\nTinytest.addAsync 'REST API PUT/GET', (test, onComplete) ->\n  _id = testColl.insert { filename: 'writefile', contentType: 'text/plain' }, (err, _id) ->\n    test.fail(err) if err\n    url = Meteor.absoluteUrl 'test/' + _id\n    HTTP.put url, { content: '0987654321'}, (err, res) ->\n      test.fail(err) if err\n      HTTP.call \"OPTIONS\", url, (err, res) ->\n         test.fail(err) if err\n         test.equal res.headers?['access-control-allow-origin'], 'http://meteor.local'\n         HTTP.get url, (err, res) ->\n           test.fail(err) if err\n           test.equal res.content, '0987654321'\n           onComplete()\n\nTinytest.addAsync 'REST API GET null id', (test, onComplete) ->\n  _id = testColl.insert { filename: 'writefile', contentType: 'text/plain' }, (err, _id) ->\n    test.fail(err) if err\n    url = Meteor.absoluteUrl 'test/'\n    HTTP.get url, (err, res) ->\n      test.isNotNull err\n      if err.response?  # Not sure why, but under phantomjs the error object is different\n        test.equal err.response.statusCode, 404\n      else\n        console.warn \"PhantomJS skipped statusCode check\"\n      onComplete()\n\nTinytest.addAsync 'maxUploadSize enforced by when HTTP PUT upload is too large', (test, onComplete) ->\n   _id = testColl.insert { filename: 'writefile', contentType: 'text/plain' }, (err, _id) ->\n      test.fail(err) if err\n      url = Meteor.absoluteUrl 'test/' + _id\n      HTTP.put url, { content: longString }, (err, res) ->\n         test.isNotNull err\n         if err.response?  # Not sure why, but under phantomjs the error object is different\n            test.equal err.response.statusCode, 413\n         else\n            console.warn \"PhantomJS skipped statusCode check\"\n         onComplete()\n\nTinytest.addAsync 'maxUploadSize enforced by when HTTP POST upload is too large', (test, onComplete) ->\n   _id = testColl.insert { filename: 'writefile', contentType: 'text/plain' }, (err, _id) ->\n      test.fail(err) if err\n      url = Meteor.absoluteUrl 'test/' + _id\n      content = \"\"\"\n         --AaB03x\\r\n         Content-Disposition: form-data; name=\"blahBlahBlah\"\\r\n         Content-Type: text/plain\\r\n         \\r\n         BLAH\\r\n         --AaB03x\\r\n         Content-Disposition: form-data; name=\"file\"; filename=\"foobar\"\\r\n         Content-Type: text/plain\\r\n         \\r\n         #{longString}\\r\n         --AaB03x--\\r\n      \"\"\"\n      HTTP.post url, { headers: { 'Content-Type': 'multipart/form-data; boundary=\"AaB03x\"'}, content: content }, (err, res) ->\n         test.isNotNull err\n         if err.response?  # Not sure why, but under phantomjs the error object is different\n            test.equal err.response.statusCode, 413\n         else\n            console.warn \"PhantomJS skipped statusCode check\"\n         onComplete()\n\nTinytest.addAsync 'If-Modified-Since header support', (test, onComplete) ->\n  _id = testColl.insert { filename: 'writefile', contentType: 'text/plain' }, (err, _id) ->\n    test.fail(err) if err\n    url = Meteor.absoluteUrl 'test/' + _id\n    HTTP.get url, (err, res) ->\n      test.fail(err) if err\n      test.equal res.statusCode, 200, 'Failed without If-Modified-Since header'\n      modified = res.headers['last-modified']\n      test.equal typeof modified, 'string', 'Invalid Last-Modified response'\n      HTTP.get url, {headers: {'If-Modified-Since': modified}}, (err, res) ->\n        test.fail(err) if err\n        test.equal res.statusCode, 304, 'Returned file despite present If-Modified-Since'\n        HTTP.get url, {headers: {'If-Modified-Since': 'hello'}}, (err, res) ->\n          test.fail(err) if err\n          test.equal res.statusCode, 200, 'Skipped file despite unparsable If-Modified-Since'\n          modified = new Date(Date.parse(modified) - 2000).toUTCString()  ## past test\n          HTTP.get url, {headers: {'If-Modified-Since': modified}}, (err, res) ->\n            test.fail(err) if err\n            test.equal res.statusCode, 200, 'Skipped file despite past If-Modified-Since'\n            modified = new Date(Date.parse(modified) + 4000).toUTCString()  ## future test\n            HTTP.get url, {headers: {'If-Modified-Since': modified}}, (err, res) ->\n              test.fail(err) if err\n              test.equal res.statusCode, 304, 'Returned file despite future If-Modified-Since'\n              onComplete()\n\nTinytest.addAsync 'REST API POST/GET/DELETE', (test, onComplete) ->\n  _id = testColl.insert { filename: 'writefile', contentType: 'text/plain' }, (err, _id) ->\n    test.fail(err) if err\n    url = Meteor.absoluteUrl 'test/' + _id\n    content = \"\"\"\n      --AaB03x\\r\n      Content-Disposition: form-data; name=\"blahBlahBlah\"\\r\n      Content-Type: text/plain\\r\n      \\r\n      BLAH\\r\n      --AaB03x\\r\n      Content-Disposition: form-data; name=\"file\"; filename=\"foobar\"\\r\n      Content-Type: text/plain\\r\n      \\r\n      ABCDEFGHIJ\\r\n      --AaB03x--\\r\n    \"\"\"\n    HTTP.post url, { headers: { 'Content-Type': 'multipart/form-data; boundary=\"AaB03x\"'}, content: content},\n      (err, res) ->\n        test.fail(err) if err\n        HTTP.get url, (err, res) ->\n          test.fail(err) if err\n          test.equal res.content,'ABCDEFGHIJ'\n          HTTP.del url, (err, res) ->\n            test.fail(err) if err\n            onComplete()\n\ncreateContent = (_id, data, name, chunkNum, chunkSize = 16) ->\n  totalChunks = Math.floor(data.length / chunkSize)\n  totalChunks += 1 unless totalChunks*chunkSize is data.length\n  throw new Error \"Bad chunkNum\" if chunkNum > totalChunks\n  begin = (chunkNum - 1) * chunkSize\n  end = if chunkNum is totalChunks then data.length else chunkNum * chunkSize\n\n  \"\"\"\n    --AaB03x\\r\n    Content-Disposition: form-data; name=\"resumableChunkNumber\"\\r\n    Content-Type: text/plain\\r\n    \\r\n    #{chunkNum}\\r\n    --AaB03x\\r\n    Content-Disposition: form-data; name=\"resumableChunkSize\"\\r\n    Content-Type: text/plain\\r\n    \\r\n    #{chunkSize}\\r\n    --AaB03x\\r\n    Content-Disposition: form-data; name=\"resumableCurrentChunkSize\"\\r\n    Content-Type: text/plain\\r\n    \\r\n    #{end - begin}\\r\n    --AaB03x\\r\n    Content-Disposition: form-data; name=\"resumableTotalSize\"\\r\n    Content-Type: text/plain\\r\n    \\r\n    #{data.length}\\r\n    --AaB03x\\r\n    Content-Disposition: form-data; name=\"resumableType\"\\r\n    Content-Type: text/plain\\r\n    \\r\n    text/plain\\r\n    --AaB03x\\r\n    Content-Disposition: form-data; name=\"resumableIdentifier\"\\r\n    Content-Type: text/plain\\r\n    \\r\n    #{_id}\\r\n    --AaB03x\\r\n    Content-Disposition: form-data; name=\"resumableFilename\"\\r\n    Content-Type: text/plain\\r\n    \\r\n    #{name}\\r\n    --AaB03x\\r\n    Content-Disposition: form-data; name=\"resumableRelativePath\"\\r\n    Content-Type: text/plain\\r\n    \\r\n    #{name}\\r\n    --AaB03x\\r\n    Content-Disposition: form-data; name=\"resumableTotalChunks\"\\r\n    Content-Type: text/plain\\r\n    \\r\n    #{totalChunks}\\r\n    --AaB03x\\r\n    Content-Disposition: form-data; name=\"file\"; filename=\"#{name}\"\\r\n    Content-Type: text/plain\\r\n    \\r\n    #{data.substring(begin, end)}\\r\n    --AaB03x--\\r\n  \"\"\"\n\ncreateCheckQuery = (_id, data, name, chunkNum, chunkSize = 16) ->\n  totalChunks = Math.floor(data.length / chunkSize)\n  totalChunks += 1 unless totalChunks*chunkSize is data.length\n  throw new Error \"Bad chunkNum\" if chunkNum > totalChunks\n  begin = (chunkNum - 1) * chunkSize\n  end = if chunkNum is totalChunks then data.length else chunkNum * chunkSize\n  \"?resumableChunkNumber=#{chunkNum}&resumableChunkSize=#{chunkSize}&resumableCurrentChunkSize=#{end-begin}&resumableTotalSize=#{data.length}&resumableType=text/plain&resumableIdentifier=#{_id}&resumableFilename=#{name}&resumableRelativePath=#{name}&resumableTotalChunks=#{totalChunks}\"\n\nTinytest.addAsync 'Basic resumable.js REST interface POST/GET/DELETE', (test, onComplete) ->\n  testColl.insert { filename: 'writeresumablefile', contentType: 'text/plain' }, (err, _id) ->\n    test.fail(err) if err\n    url = Meteor.absoluteUrl \"test/_resumable\"\n    data = 'ABCDEFGHIJ'\n    content = createContent _id, data, \"writeresumablefile\", 1\n    HTTP.post url, { headers: { 'Content-Type': 'multipart/form-data; boundary=\"AaB03x\"'}, content: content },\n      (err, res) ->\n        test.fail(err) if err\n        url = Meteor.absoluteUrl 'test/' + _id\n        HTTP.get url, (err, res) ->\n          test.fail(err) if err\n          test.equal res.content, data\n          HTTP.del url, (err, res) ->\n            test.fail(err) if err\n            onComplete()\n\nTinytest.addAsync 'Basic resumable.js REST interface POST/GET/DELETE, multiple chunks', (test, onComplete) ->\n\n  data = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ012345'\n\n  testColl.insert { filename: 'writeresumablefile', contentType: 'text/plain' }, (err, _id) ->\n    test.fail(err) if err\n    url = Meteor.absoluteUrl \"test/_resumable\"\n    content = createContent _id, data, \"writeresumablefile\", 1\n    content2 = createContent _id, data, \"writeresumablefile\", 2\n    HTTP.post url, { headers: { 'Content-Type': 'multipart/form-data; boundary=\"AaB03x\"'}, content: content },\n      (err, res) ->\n        test.fail(err) if err\n        HTTP.get url + createCheckQuery(_id, data, \"writeresumablefile\", 2), (err, res) ->\n          test.fail(err) if err\n          test.equal res.statusCode, 204\n          HTTP.call 'head', url + createCheckQuery(_id, data, \"writeresumablefile\", 1), (err, res) ->\n            test.fail(err) if err\n            test.equal res.statusCode, 200\n            HTTP.post url, { headers: { 'Content-Type': 'multipart/form-data; boundary=\"AaB03x\"'}, content: content2 },\n              (err, res) ->\n                test.fail(err) if err\n                url = Meteor.absoluteUrl 'test/' + _id\n                HTTP.get url, (err, res) ->\n                  test.fail(err) if err\n                  test.equal res.content, data\n                  HTTP.del url, (err, res) ->\n                    test.fail(err) if err\n                    onComplete()\n\nTinytest.addAsync 'Basic resumable.js REST interface POST/GET/DELETE, duplicate chunks', (test, onComplete) ->\n\n  data = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ012345'\n\n  testColl.insert { filename: 'writeresumablefile', contentType: 'text/plain' }, (err, _id) ->\n    test.fail(err) if err\n    url = Meteor.absoluteUrl \"test/_resumable\"\n    content = createContent _id, data, \"writeresumablefile\", 1\n    content2 = createContent _id, data, \"writeresumablefile\", 2\n    HTTP.post url, { headers: { 'Content-Type': 'multipart/form-data; boundary=\"AaB03x\"'}, content: content2 },\n      (err, res) ->\n        test.fail(err) if err\n        HTTP.post url, { headers: { 'Content-Type': 'multipart/form-data; boundary=\"AaB03x\"'}, content: content2 },\n          (err, res) ->\n            test.fail(err) if err\n            HTTP.post url, { headers: { 'Content-Type': 'multipart/form-data; boundary=\"AaB03x\"'}, content: content },\n              (err, res) ->\n                test.fail(err) if err\n                url = Meteor.absoluteUrl 'test/' + _id\n                HTTP.get url, (err, res) ->\n                  test.fail(err) if err\n                  test.equal res.content, data\n                  HTTP.del url, (err, res) ->\n                    test.fail(err) if err\n                    onComplete()\n\nTinytest.addAsync 'Basic resumable.js REST interface POST/GET/DELETE, duplicate chunks 2', (test, onComplete) ->\n\n  data = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ012345'\n\n  testColl.insert { filename: 'writeresumablefile', contentType: 'text/plain' }, (err, _id) ->\n    test.fail(err) if err\n    url = Meteor.absoluteUrl \"test/_resumable\"\n    content = createContent _id, data, \"writeresumablefile\", 1\n    content2 = createContent _id, data, \"writeresumablefile\", 2\n    HTTP.post url, { headers: { 'Content-Type': 'multipart/form-data; boundary=\"AaB03x\"'}, content: content },\n      (err, res) ->\n        test.fail(err) if err\n        HTTP.post url, { headers: { 'Content-Type': 'multipart/form-data; boundary=\"AaB03x\"'}, content: content2 },\n          (err, res) ->\n            test.fail(err) if err\n            HTTP.post url, { headers: { 'Content-Type': 'multipart/form-data; boundary=\"AaB03x\"'}, content: content },\n              (err, res) ->\n                test.fail(err) if err\n                url = Meteor.absoluteUrl 'test/' + _id\n                HTTP.get url, (err, res) ->\n                  test.fail(err) if err\n                  test.equal res.content, data\n                  HTTP.del url, (err, res) ->\n                    test.fail(err) if err\n                    onComplete()\n\nTinytest.addAsync 'Basic resumable.js REST interface POST/GET/DELETE, duplicate chunks 3', (test, onComplete) ->\n\n  data = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdef'\n\n  testColl.insert { filename: 'writeresumablefile', contentType: 'text/plain' }, (err, _id) ->\n    test.fail(err) if err\n    url = Meteor.absoluteUrl \"test/_resumable\"\n    content = createContent _id, data, \"writeresumablefile\", 1\n    content2 = createContent _id, data, \"writeresumablefile\", 2\n    content3 = createContent _id, data, \"writeresumablefile\", 3\n    HTTP.post url, { headers: { 'Content-Type': 'multipart/form-data; boundary=\"AaB03x\"'}, content: content2 },\n      (err, res) ->\n        test.fail(err) if err\n        HTTP.post url, { headers: { 'Content-Type': 'multipart/form-data; boundary=\"AaB03x\"'}, content: content },\n          (err, res) ->\n            test.fail(err) if err\n            HTTP.post url, { headers: { 'Content-Type': 'multipart/form-data; boundary=\"AaB03x\"'}, content: content2 },\n              (err, res) ->\n                test.fail(err) if err\n                HTTP.post url, { headers: { 'Content-Type': 'multipart/form-data; boundary=\"AaB03x\"'}, content: content },\n                  (err, res) ->\n                    test.fail(err) if err\n                    HTTP.post url, { headers: { 'Content-Type': 'multipart/form-data; boundary=\"AaB03x\"'}, content: content3 },\n                      (err, res) ->\n                        test.fail(err) if err\n                        url = Meteor.absoluteUrl 'test/' + _id\n                        HTTP.get url, (err, res) ->\n                          test.fail(err) if err\n                          test.equal res.content, data\n                          HTTP.del url, (err, res) ->\n                            test.fail(err) if err\n                            onComplete()\n\nTinytest.addAsync 'maxUploadSize enforced by when resumable.js upload is too large', (test, onComplete) ->\n   testColl.insert { filename: 'writeresumablefile', contentType: 'text/plain' }, (err, _id) ->\n      test.fail(err) if err\n      url = Meteor.absoluteUrl \"test/_resumable\"\n      content = createContent _id, longString, \"writeresumablefile\", 1\n      HTTP.post url, { headers: { 'Content-Type': 'multipart/form-data; boundary=\"AaB03x\"'}, content: content },\n         (err, res) ->\n            test.isNotNull err\n            if err.response?  # Not sure why, but under phantomjs the error object is different\n               test.equal err.response.statusCode, 413\n            else\n               console.warn \"PhantomJS skipped statusCode check\"\n            onComplete()\n\nTinytest.addAsync 'REST API valid range requests', (test, onComplete) ->\n  _id = testColl.insert { filename: 'writefile', contentType: 'text/plain' }, (err, _id) ->\n    test.fail(err) if err\n    url = Meteor.absoluteUrl 'test/' + _id\n    HTTP.put url, { content: '0987654321'}, (err, res) ->\n      test.fail(err) if err\n      HTTP.get url, { headers: { 'Range': '0-'}},\n        (err, res) ->\n          test.fail(err) if err\n          test.equal res.headers['content-range'], 'bytes 0-9/10'\n          test.equal res.headers['accept-ranges'], 'bytes'\n          test.equal res.statusCode, 206\n          test.equal res.content, '0987654321'\n          HTTP.get url, { headers: { 'Range': '0-9'}},\n            (err, res) ->\n              test.fail(err) if err\n              test.equal res.headers['content-range'], 'bytes 0-9/10'\n              test.equal res.headers['accept-ranges'], 'bytes'\n              test.equal res.statusCode, 206\n              test.equal res.content, '0987654321'\n              HTTP.get url, { headers: { 'Range': '5-7'}},\n                (err, res) ->\n                  test.fail(err) if err\n                  test.equal res.headers['content-range'], 'bytes 5-7/10'\n                  test.equal res.headers['accept-ranges'], 'bytes'\n                  test.equal res.statusCode, 206\n                  test.equal res.content, '543'\n                  onComplete()\n\nTinytest.addAsync 'REST API invalid range requests', (test, onComplete) ->\n   _id = testColl.insert { filename: 'writefile', contentType: 'text/plain' }, (err, _id) ->\n      test.fail(err) if err\n      url = Meteor.absoluteUrl 'test/' + _id\n      HTTP.put url, { content: '0987654321'}, (err, res) ->\n         test.fail(err) if err\n         HTTP.get url, { headers: { 'Range': '0-10'}}, (err, res) ->\n            test.isNotNull err\n            if err.response?  # Not sure why, but under phantomjs the error object is different\n               test.equal err.response.statusCode, 416\n            else\n               console.warn \"PhantomJS skipped statusCode check\"\n            HTTP.get url, { headers: { 'Range': '5-3'}}, (err, res) ->\n               test.isNotNull err\n               if err.response?  # Not sure why, but under phantomjs the error object is different\n                  test.equal err.response.statusCode, 416\n               else\n                  console.warn \"PhantomJS skipped statusCode check\"\n               HTTP.get url, { headers: { 'Range': '-1-5'}}, (err, res) ->\n                  test.isNotNull err\n                  if err.response?  # Not sure why, but under phantomjs the error object is different\n                     test.equal err.response.statusCode, 416\n                  else\n                     console.warn \"PhantomJS skipped statusCode check\"\n                  HTTP.get url, { headers: { 'Range': '1-abc'}}, (err, res) ->\n                     test.isNotNull err\n                     if err.response?  # Not sure why, but under phantomjs the error object is different\n                        test.equal err.response.statusCode, 416\n                     else\n                        console.warn \"PhantomJS skipped statusCode check\"\n                     onComplete()\n\nTinytest.addAsync 'REST API requests header manipilation', (test, onComplete) ->\n  _id = testColl.insert { filename: 'writefile', contentType: 'text/plain' }, (err, _id) ->\n    test.fail(err) if err\n    url = Meteor.absoluteUrl 'test/' + _id\n    HTTP.put url, { content: '0987654321'}, (err, res) ->\n      test.fail(err) if err\n      HTTP.get url+'?download=true', (err, res) ->\n          test.equal res.headers['content-disposition'], \"attachment; filename=\\\"writefile\\\"; filename*=UTF-8''writefile\"\n          test.equal res.statusCode, 200\n          HTTP.get url+'?cache=123456', { headers: { 'Range': '1-5'}},\n            (err, res) ->\n              test.equal res.headers['cache-control'], 'max-age=123456, private'\n              test.equal res.statusCode, 206\n              HTTP.get url+'?cache=123', (err, res) ->\n                test.equal res.headers['cache-control'], 'max-age=123, private'\n                test.equal res.statusCode, 200\n                onComplete()\n\nTinytest.addAsync 'REST API requests header manipilation, UTF-8', (test, onComplete) ->\n  _id = testColl.insert { filename: '中文指南.txt', contentType: 'text/plain' }, (err, _id) ->\n    test.fail(err) if err\n    url = Meteor.absoluteUrl 'test/' + _id\n    HTTP.put url, { content: '0987654321'}, (err, res) ->\n      test.fail(err) if err\n      HTTP.get url+'?download=true', (err, res) ->\n          test.equal res.headers['content-disposition'], \"attachment; filename=\\\"%E4%B8%AD%E6%96%87%E6%8C%87%E5%8D%97.txt\\\"; filename*=UTF-8''%E4%B8%AD%E6%96%87%E6%8C%87%E5%8D%97.txt\"\n          test.equal res.statusCode, 200\n          HTTP.get url+'?cache=123456', { headers: { 'Range': '1-5'}},\n            (err, res) ->\n              test.equal res.headers['cache-control'], 'max-age=123456, private'\n              test.equal res.statusCode, 206\n              HTTP.get url+'?cache=123', (err, res) ->\n                test.equal res.headers['cache-control'], 'max-age=123, private'\n                test.equal res.statusCode, 200\n                onComplete()\n\nif Meteor.isClient\n\n  noAllowSub = Meteor.subscribe 'noAllowCollPub'\n  noReadSub = Meteor.subscribe 'noReadCollPub'\n  denySub = Meteor.subscribe 'denyCollPub'\n\n  Tinytest.addAsync 'Reject insert without true allow rule', subWrapper(noAllowSub, (test, onComplete) ->\n    _id = noAllowColl.insert {}, (err, retid) ->\n      if err\n        test.equal err.error, 403\n      else\n        test.fail new Error \"Insert without allow succeeded.\"\n      onComplete()\n  )\n\n  Tinytest.addAsync 'Reject insert with true deny rule', subWrapper(denySub, (test, onComplete) ->\n    _id = denyColl.insert {}, (err, retid) ->\n      if err\n        test.equal err.error, 403\n      else\n        test.fail new Error \"Insert with deny succeeded.\"\n      onComplete()\n  )\n\n  Tinytest.addAsync 'Reject HTTP GET without true allow rule', subWrapper(noReadSub, (test, onComplete) ->\n    _id = noReadColl.insert { filename: 'writefile', contentType: 'text/plain' }, (err, _id) ->\n      test.fail(err) if err\n      url = Meteor.absoluteUrl 'noread/' + _id\n      HTTP.put url, { content: '0987654321'}, (err, res) ->\n        test.fail(err) if err\n        HTTP.get url, (err, res) ->\n           test.isNotNull err\n           if err.response?  # Not sure why, but under phantomjs the error object is different\n              test.equal err.response.statusCode, 403\n           else\n              console.warn \"PhantomJS skipped statusCode check\"\n           onComplete()\n  )\n\n  Tinytest.addAsync 'Reject HTTP PUT larger than write allow rule allows', subWrapper(noReadSub, (test, onComplete) ->\n      _id = noReadColl.insert { filename: 'writefile', contentType: 'text/plain' }, (err, _id) ->\n         test.fail(err) if err\n         url = Meteor.absoluteUrl 'noread/' + _id\n         HTTP.put url, { content: '0123456789abcdef'}, (err, res) ->\n            test.isNotNull err\n            if err.response?  # Not sure why, but under phantomjs the error object is different\n               test.equal err.response.statusCode, 413\n            else\n               console.warn \"PhantomJS skipped statusCode check\"\n            onComplete()\n  )\n\n  Tinytest.addAsync 'Client basic localUpdate test', (test, onComplete) ->\n    id = testColl.insert()\n    test.equal (typeof testColl.localUpdate), 'function'\n    testColl.localUpdate { _id: id }, { $set: { 'metadata.test': true } }\n    doc = testColl.findOne { _id: id }\n    test.equal doc.metadata.test, true\n    onComplete()\n\n  Tinytest.addAsync 'Client localUpdate server method rejection test', (test, onComplete) ->\n    id = testColl.insert()\n    Meteor.call 'updateTest', id, true, (err, res) ->\n      test.instanceOf err, Meteor.Error\n      doc = testColl.findOne { _id: id }\n      test.isUndefined doc.metadata.test2\n      test.isUndefined res\n      Meteor.call 'updateTest', id, false, (err, res) ->\n        test.fail(err) if err\n        test.equal res, 1\n        doc = testColl.findOne { _id: id }\n        test.equal doc.metadata.test2, false\n        onComplete()\n\n  # Resumable.js tests\n\n  Tinytest.add 'Client has Resumable', (test) ->\n    test.instanceOf testColl.resumable, Resumable, \"Resumable object not found\"\n\n  Tinytest.addAsync 'Client resumable.js Upload', (test, onComplete) ->\n    thisId = null\n\n    testColl.resumable.on 'fileAdded', (file) ->\n      testColl.insert { _id: file.uniqueIdentifier, filename: file.fileName, contentType: file.file.type }, (err, _id) ->\n        test.fail(err) if err\n        thisId = \"#{_id}\"\n        testColl.resumable.upload()\n\n    testColl.resumable.on 'fileSuccess', (file) ->\n      test.equal thisId, file.uniqueIdentifier\n      url = Meteor.absoluteUrl 'test/' + file.uniqueIdentifier\n      HTTP.get url, (err, res) ->\n        test.fail(err) if err\n        test.equal res.content,'ABCDEFGHIJ'\n        HTTP.del url, (err, res) ->\n          test.fail(err) if err\n          testColl.resumable.events = []\n          onComplete()\n\n    testColl.resumable.on 'error', (msg, err) ->\n      test.fail err\n\n    myBlob = new Blob [ 'ABCDEFGHIJ' ], { type: 'text/plain' }\n    myBlob.name = 'resumablefile'\n    testColl.resumable.addFile myBlob\n\n  Tinytest.addAsync 'Client resumable.js Upload, Multichunk', (test, onComplete) ->\n    thisId = null\n\n    testColl.resumable.on 'fileAdded', (file) ->\n      testColl.insert { _id: file.uniqueIdentifier, filename: file.fileName, contentType: file.file.type }, (err, _id) ->\n        test.fail(err) if err\n        thisId = \"#{_id}\"\n        testColl.resumable.upload()\n\n    testColl.resumable.on 'fileSuccess', (file) ->\n      test.equal thisId, file.uniqueIdentifier\n      url = Meteor.absoluteUrl 'test/' + file.uniqueIdentifier\n      HTTP.get url, (err, res) ->\n        test.fail(err) if err\n        test.equal res.content,'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'\n        HTTP.del url, (err, res) ->\n          test.fail(err) if err\n          testColl.resumable.events = []\n          onComplete()\n\n    testColl.resumable.on 'error', (msg, err) ->\n      test.fail err\n\n    myBlob = new Blob [ 'ABCDEFGHIJ', 'KLMNOPQRSTUVWXYZ', '0123456789' ], { type: 'text/plain' }\n    myBlob.name = 'resumablefile'\n    testColl.resumable.addFile myBlob\n"
  }
]